0

I've been trying to parse my data for a few days now and still have no clue how to get the results from my PHP array that is encoded by using json_encode. I am new to JQuery.

this is not working:

$.post('coordinate_array.php',{},function(data) {  //ERROR HERE EXPECTING SOMETHING??
 results = JSON.parse(data);
 for(i = 0;i < results.length;i++) {
  Paint(results[i].x, results[i].y);
 }
});

I'm getting my data from this php file:

<?php
include 'db_conn.php';

header('Content-Type: application/json'); //not sure if i need this here??

$coordinate_sql = "SELECT x_coord, y_coord FROM coordinates";
$result = mysqli_query($conn,$coordinate_sql);

//see if query is good
if($result === false) {
    die(mysqli_error()); 
}

//array that will have number of desks in map area
    while($row = mysqli_fetch_assoc($result)){  

    //get desk array count      
    $desk[] = array('x' => $row['x_coord'], 
                                    'y' => $row['y_coord']);
} //end while loop
    echo json_encode($desk); //encode the array
?>
9
  • 4
    You're not showing anything, you need to do: print(json_encode($desk));. Also, die(mysqli_error()) isn't JSON, so if something goes wrong it will be invalid JSON... You may also have an error somewhere else in your PHP file causing some notice (or whatever) being printed before the JSON. Commented Oct 1, 2014 at 14:10
  • And your error is? Only thing I can see is that you're not outputting your json data. json_encode() RETURNS the encoded string. it doesn't do output, so your script is effectively useless since nothing gets output to the client. You need echo json_encode($desk) Commented Oct 1, 2014 at 14:11
  • I added the echo and still nothing draws on screen.. this is the result I get to show you guys that my array does have values : [{"x":"20","y":"20"},{"x":"30","y":"30"},{"x":"40","y":"40"},{"x":"50","y":"50"}] ... what can I be doing wrong in the JQuery?? Commented Oct 1, 2014 at 14:33
  • @MarcB this is my error : Parse error on line 1: $.post('coordinate_a ^ Expecting '{', '[' Commented Oct 1, 2014 at 14:35
  • Why are you doing JSON.parse, data returned is an array, not a string to be parsed. Commented Oct 1, 2014 at 14:36

1 Answer 1

2

You’re not echoing your JSON data, so the page requested by the JS call will always be empty. Use:

echo json_encode($desk);

at the end of your file.

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

1 Comment

@mario What is the result of this request? You should use a tool like curl to debug it, if not the Network tab in your browser.

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.