1

i'm trying to show error message from server to client site using ajax , but it wont work when i make a function for error messages ,

     #other codes for saving the post,there is not error
     success_meesage = f'success'
     return JsonResponse({'success':'success','success_msg':success_meesage})
 else:
     error_message=f'there is an error into your two dates please make sure check in smaller than check out'
     return JsonResponse({'success':False,'error_taken':True,'error_message':error_message})

my ajax code

    const form = document.getElementById('post-form')
    form.addEventListener("submit",submitHanler);
    function submitHanler(e){
        e.preventDefault();
        $.ajax({
            type:'POST',
            url:"my-url",
            data:$("#post-form").serialize(),
            dataType:'json',
            success:successFunction,
            error:errorFunction,
                        
        })        
    }
    function successFunction(data){
        // console.log(data)
        if(data.success='success' && data.success_msg){
            form.reset();
            alertify.success(data.success_msg)
        }
    }
    function errorFunction(request, status, error){
        console.log(request.responseText)
 
        if(error.error_taken == true){
            alertify.alert('warning !','message')
            alertify.alert(error.error_message,function(){

            });
        }
           

        }

    }
i also tried this : function errorFunction(jqXHR, exception) it shows nothing as well , i tried many ways but none of them worked ! thank you in advance ..

2
  • is the errorFunction being called at all? Commented Aug 19, 2021 at 8:25
  • 1
    You need to return a non 200-399 status code, so: return JsonResponse({'success':False,'error_taken':True,'error_message':error_message}, status=400) Commented Aug 19, 2021 at 8:25

1 Answer 1

1

You are returning a JsonResponse, but with status code 200, so that means that, according to the status code, the request was successful.

We thus can return a JsonResponse with a status code outside the 200-399 range, for example a 400 HTTP response:

if some_condition:
    success_meesage = f'success'
    return JsonResponse(
        {'success':'success','success_msg':success_meesage}
    )
else:
    error_message=f'there is an error into your two dates please make sure check in smaller than check out'
    return JsonResponse(
        {'success':False,'error_taken':True,'error_message':error_message},
        status=400
    )
Sign up to request clarification or add additional context in comments.

1 Comment

stackoverflow.com/questions/68909508/… can this be fixed please ? thank yo

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.