简体   繁体   中英

PHP array to seperate JavaScript file via AJAX

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...

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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM