1

I made a simple php file, that saves data from MySQL db into 2 arrays. I am trying to send these two arrays to the js file (which is on seperate from the html file). I am trying to learn AJAX, but it seems i am not doing something correct.

Can you please explain what am i doing wrong?

My php file: get.php

<?php
define('DB_NAME', 'mouse');
define('DB_USER', 'root');
define('DB_PASS', '');
define('DB_HOST', 'localhost');
$link = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}else{
   echo 'Successfuly connected to database :) <br/>';
}
$sql = "SELECT x, y FROM mousetest";
$result = mysqli_query($link, $sql);
$x_array = [];
$y_array = [];
if (mysqli_num_rows($result) > 0) {
    while($row = mysqli_fetch_assoc($result)) {
        echo "x: " . $row["x"]. " - y: " . $row["y"]. "<br>";
        array_push($x_array, $row["x"]);
        array_push($y_array, $row["y"]);
    }
} else {
    echo "0 results";
}
echo json_encode($x_array);
echo "<br>";
echo json_encode($y_array);
mysqli_close($link);
$cd_answer = json_encode($x_array);
echo ($cd_answer);
?>

And this is my JS file:

$(document).ready(function(){
    $.ajax({
        type: "GET",
        url: "get.php",
        dataType: "json",
        data : {anything : 1},
        success:function(data){
            var x = jQuery.parseJSON(data); // parse the answer
            x = eval(x);
            console.log(x.length);
        }
    });
});

I really hope you understand, what i am trying to do. Where is the problem? I really thought this should work, as i went through it quite a few times to say the least...

nerdlyist
  • 2,842
  • 2
  • 20
  • 32
Tadej Bogataj
  • 399
  • 1
  • 4
  • 13
  • What is the error ? – Mihai Alexandru-Ionut Jan 20 '17 at 19:22
  • Well i just check if it logs in the console the length of the array, but it does nothing. I do not understand where the problem is. That is the problem :) – Tadej Bogataj Jan 20 '17 at 19:23
  • what you receive if `console.log(data)` ? – Mihai Alexandru-Ionut Jan 20 '17 at 19:25
  • Nothing, thats the problem – Tadej Bogataj Jan 20 '17 at 19:26
  • 1
    is this file and get.php in the same directory? If not you will need a better path in URL. Likewise use `done` rather than `success` for your callback see http://stackoverflow.com/questions/8840257/jquery-ajax-handling-continue-responses-success-vs-done – nerdlyist Jan 20 '17 at 19:28
  • I only know basicly php.. you have to return json format from `server-side`. – Mihai Alexandru-Ionut Jan 20 '17 at 19:28
  • They are in the same directory... I do return in a json format – Tadej Bogataj Jan 20 '17 at 19:28
  • 1
    not just echo some json arbitrarily, you need to return valid json. It looks like your output includes `Successfuly connected to database :)` `x: " . $row["x"]. " - y: " . $row["y"]. "` and potentially `0 results` which all are not valid json. On top of this you then print your two arrays as separate json objects, you need to put them in an associative array and then json encode that array not the separate parts. – Patrick Murphy Jan 20 '17 at 19:32
  • If i remove all the echo in php, except the last one, i get this error: VM6116:1 Uncaught SyntaxError: Unexpected token , in JSON at position 1 at JSON.parse () at Function.n.parseJSON (jquery.min.js:4) at Object.success (izris.js:9) at i (jquery.min.js:2) at Object.fireWith [as resolveWith] (jquery.min.js:2) at y (jquery.min.js:4) at XMLHttpRequest.c (jquery.min.js:4) Any Idea whats wrong? – Tadej Bogataj Jan 20 '17 at 19:34
  • that error is saying you have invalid json... – Patrick Murphy Jan 20 '17 at 19:34
  • I get that, but do you have any idea what is wrong with my code? I have no clue what the problem is... – Tadej Bogataj Jan 20 '17 at 19:35
  • visit the php file directly in your browser to view the output, copy the output to a json validator online. It should tell you where there are issues. – Patrick Murphy Jan 20 '17 at 19:38

1 Answers1

2

You can't use echo json_encode(...) twice. The client expects a single JSON object, not a series of them.

You should make each array an element of a containing array, which you then return as JSON.

$result = array('x' => $x_array, 'y' => $y_array);
echo json_encode($result);

Then in the jQuery code you would use:

var x = data.x;
var y = data.y;

Also, when you use dataType: 'json', jQuery automatically parses the JSON when it sets data. You shouldn't call jQuery.parseJSON() or eval().

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • I corrected the code as following: get.php: $result = array('x' => $x_array, 'y' => $y_array) echo json_encode($result); and the js file: $(document).ready(function(){ $.ajax({ type: "GET", url: "get.php", dataType: "json", data : {anything : 1}, success:function(data){ var x = data.x; var y = data.y; console.log(x.length); } }); }); But it still does not work... – Tadej Bogataj Jan 20 '17 at 19:38