Edwin
Edwin

Reputation: 2114

jQuery's .ajax() not working with PHP

I've been trying to troubleshoot this, but can't find a good function that will execute a full stack trace. Here's what I have so far:

Javascript (in page /charts/userbase.php):

$.ajax({
    url: '/data/users.php',
    dataType: 'json',
    error: function() {
      console.log("I'm hitting an error.");
    },
    success: function(jsonData) {
      // do something
    }
});

/data/users.php (should dump JSON)

<?php
  //some processing precedes this
  $data = json_encode($data, JSON_NUMERIC_CHECK);
  $data = str_replace("\/", "/", $data);
  $data = str_replace("\"", "", $data);

  header("Content-type: application/json");
  echo $data;

?>

Visiting 127.0.0.1/data/users.php returns the correct JSON, but somehow I can't get jQuery's $.ajax() to work, and I can't seem to find any good documentation on how to output a stack trace if it fails. Any ideas on what I'm doing wrong?

EDIT: Damn, that was a lot of responses, really fast.

First off, I do post-procession on the JSON string because PHP keeps changing / into \/, which JS's native Date() can't handle, and it keeps adding ", which breaks parts of the code expecting booleans. I have already verified that it is returning the correct output.

Second, changing error to add jsonData prints out undefined, and the error(jqXHR, textStatus, errorThrown) returns an object, with status 200.

Maybe I'm wrong and it's not the ajax call, but I'm way more confused now.

EDIT 2: Running with console.log(arguments), I'm getting a parseError. I'll take a closer look, but I don't see anything wrong with what I have.

Last Edit: Turns out everyone was right on that last line; shouldn't have replaced the ". Still need str_replace("\/", "/", $data) though. I feel pretty dumb it took me a few hours to troubleshoot this, though.

Upvotes: 0

Views: 2857

Answers (2)

Mark Schultheiss
Mark Schultheiss

Reputation: 34168

can you add this to your ajax:

contentType: "application/json",

Upvotes: 0

Bot
Bot

Reputation: 11855

Check out http://api.jquery.com/jQuery.ajax/

What happens if you try

$.ajax({
    url: 'data/users.php',
    dataType: 'json',
    error: function() {
      console.log("I'm hitting an error.");
      console.log(arguements);
    },
    success: function(jsonData) {
      // do something
      console.log(jsonData);
    }
});

You should see console logs stating an error occurred because you are modifying the json string after you encoded it.

EDIT:

You say your JSON is good. Try using this to verify http://jsonlint.com/

Upvotes: 1

Related Questions