0

I am currently trying to call a php script through Ajax so I can read it in my html file. I am using Json and Ajax to achieve this. I am having an issue with my php script where I can't get the information to format correctly when sending it over to the html. Here's my php:

$return_arr = array();
$fetch = mysqli_query("SELECT User_Id, First_Name, Last_Name FROM Users"); 

while ($row = mysqli_fetch_array($fetch, MYSQLI_ASSOC)) {
    $row_array['User_Id'] = $row['User_Id'];
    $row_array['First_Name'] = $row['First_Name'];
    $row_array['Last_Name'] = $row['Last_Name'];
    array_push($return_arr,$row_array);
}

echo json_encode($return_arr);

I am getting the following type of response:

[{"User_Id":"6","First_Name":"Joe","Last_Name":"Shmo"},
{"User_Id":"17","First_Name":"Test","Last_Name":"Test"},
{"User_Id":"18","First_Name":"Test","Last_Name":"Test"},
{"User_Id":"19","First_Name":"Test","Last_Name":"Test"},
{"User_Id":"21","First_Name":"HI","Last_Name":"HI"}]

Now this causes me to have troubles while accessing in the html. I am trying to access it like:

data[0].User_Id

This gets undefined. I suspect the brackets are in the wrong places but can figure out how to switch them around.

1
  • Could you include the Javascript code you're using to fetch the data? Commented Jul 29, 2015 at 22:44

1 Answer 1

1

You need to do something like this:

<?php

header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');

echo json_encode( $return_arr );
Sign up to request clarification or add additional context in comments.

4 Comments

Very interesting. That worked correctly. What does this do exactly?
It tells the client that you're sending JSON data back.
The response you pasted above is probably just one big string (i.e. the string returned by json_encode). It looks like a JS object, but it isn't until you parse it into one. Instead of setting the header correctly, you could have done var dataJson = JSON.parse(data) and converted the string response into a JS object. Or told your AJAX library to expect JSON back.
It told your AJAX call that you were using JSON. When you don't tell your JS what data type you're using, it'll try to look into the Content-type. You can also simply write the datatype in your JS code. That's simpler to write and easier to understand.

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.