0

I have an ajax call as below:

$.ajax({
                type: "GET",
                url: "process.php",
                data: dataString,
                success: function( response ) {
                    $('#in-progress').hide();
                  $('#mydiv').html(response)
                  .append("")                   
                }                     

              });

What I want is, that I need to get the distinguished message from process.php. What should I do in thid regard so that I may not parse the message myself. I need to send some specific code or something from my process.php so that the ajax can process it separately. Shall I use some http response code and use it in statusCode ? What is the appropriate practice to do that ?

e.g. Success message will be "This is Success" Error message will be "There is an unknown error" - This message should be treated separately. Any idea ?

2 Answers 2

2

What I usually do to distinguish a success/error status from an ajax call, I return http status 500 with the error message encoded in json.

The error status 500 is being handled by the 'error' callback which I usually set on the $.ajaxSetup like so:

$.ajaxSetup({
  'error': function( XMLHttpRequest, textStatus, errorThrown ) {
     var data = $.parseJSON(XMLHttpRequest.responseText);
     // alert somehow.
},
Sign up to request clarification or add additional context in comments.

Comments

1

yes you could but you have to use json.

$.ajax({
                type: "GET",
                url: "process.php",
                data: dataString,
                dataType:   'json',
                success: function( response ) {
                    $('#in-progress').hide();
                  $('#mydiv').html(response)
                  .append("")                   
                }                     

              });

and if success in your response.php return your array in json. http://php.net/manual/en/function.json-encode.php,

imagine on your array

response.php

arr['success'] = true;
arr['message'] = 'Your good solution"
arr['code'] = 'Your code':
json_encode(arr);

and in js success:

if response.success == 'true'
 alert('good' + response.code);
else
 alert('bad' + response.code);
end

I think is something approach that what you need

1 Comment

to me both answer looks good and practical. thanks both of you, but I could only accept answer :)

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.