Zi-yan Tseng
Zi-yan Tseng

Reputation: 184

pass php array to javascript using ajax

I try to get array from sql server using php , and parsing these array to javascript using ajax. However , I have tried many solution by google , I can't get the array.

This is my php code:

<?php
    include 'Connect.php';
    $Store_int = $_GET['num'];

    $sql = "SELECT * FROM `store` WHERE `Place_int` = " . $Store_int;

    mysqli_select_db($link, "web");
    $link->set_charset("utf8");
    $result = mysqli_query($link, $sql);

    $arr = array();
    while ($row = mysqli_fetch_object($result)) {
        $p = (string)$row->Name;
        $arr[] = $p;
    }
    //print_r($arr);
    $jsonArr = json_encode($arr, JSON_UNESCAPED_UNICODE);
    echo $jsonArr;
    mysqli_free_result($result);
    mysqli_close($link);
?>

Array in php will encode and display:

["pen","pencil","apple","cat","dog"]

and the .js file

function getArr(store_int) {
    var jsArray = new Array();
    $.ajax({
        url: "fromSQL_store.php",
        data: {
            num: $("#store_int").val()
        },
        type: "GET",
        dataType: "json",
        success: function (data) {
            alert(num);
            jsArray = JSON.parse(data.jsonArr);
        }, error: function (data) {
            alert("123");
        }
    });
    //alert(jsArray.length);
    return jsArray;
}

In .js , I will always get empty response(undefined) from php. Because the ajax will answer "error" function..., and the error status is 200.

Upvotes: 0

Views: 1127

Answers (2)

Junius L
Junius L

Reputation: 16152

Your array will always return undfined as the AJAX call is async, your function returns jsArray before it is set. and You don't need JSON.parse() as you have defined dataType as json in your ajax call. Pass a function to your getArr() function and use your data in that function.

function getArr(store_int, outputFn){ // what do you use store_int for?
   $.ajax({
       url: "fromSQL_store.php",
       data: {
           num: $("#store_int").val()
       },
       type: "GET",
       dataType: "json",
       success: function(data) {
           outputFn(data)
       },error: function(data){
           alert("123");
       }
   });
}

Then use it like

getArr('5', function (data) {
       console.log(data)
})

Console output

enter image description here

Upvotes: 1

EyuelDK
EyuelDK

Reputation: 3199

Your problem lies here. You are attempting to access data.jsonArr which is always undefined. The JSON data sent is actually embodied by data variable.

success: function(data) {
    alert(num);
    jsArray = JSON.parse(data.jsonArr); // Replace by jsArray = data;
}

NOTE, You might also need to specify that the MIME media type that is being outputted is JSON. Putting this at the top of your PHP script should solve your problem.

<?php
header('Content-Type: application/json');

Upvotes: 0

Related Questions