1

I am trying to make an ajax call and return a response. The problem is I can't seem to figure out how to get at the response. Here is my javascript code:

$.ajax({
    type: "POST", 
    url: "inc.test.php", 
    data: {list:postData},
    dataType: "json",
    success: function(response){
        if(response.success == 1){
            alert (response.testdata);
            }},
    error: function(jqXHR, textStatus, errorThrown){
        console.log(errorThrown); 
        console.log(textStatus);
        }
    });

Here is my inc.test.php code sending the json data back:

if($result)
    {
    $arr=array(
        "success" => 1,
        "testdata" => 'Testing');
    echo json_encode($arr);
    }

In my Console/Response I see this:

{"success":1,"testdata":"Testing"}

I've read tons of articles and can't seem to figure out whats going on. Please help!

2
  • Are you getting an error or are you just looking to deal with the response? Commented Oct 25, 2015 at 0:59
  • 1
    inspect the actual request response body in dev tools network and see if there are other characters being returned other than the json Commented Oct 25, 2015 at 1:07

3 Answers 3

1

success: function(response) {
  var resp = JSON.parse(response);
  // rest of code ...
  }

May be because you have to parse your code? You didn't specify what the issue is.

Sign up to request clarification or add additional context in comments.

Comments

0

Did you try using PHP's trim() function before sending the data? i think you have an extra space when you json_encode or use trim().

if($result)
    {
    $arr=array(
        "success" => 1, 
                    ^
        "testdata" => 'Testing');
                     ^
    echo json_encode($arr);
    }

1 Comment

That doesn't matter, it's an array declaration so you can have tabs and spaces there to format the code for readability.
0

if this is in wordpress , you may forgot to

wp_die(); 

in the end of php function called by ajax request

Comments

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.