0

When I use ajax to get the json result, and I set the global variable for storing the response, but when I use console.log, it also undefined,I don't know why, I use the PHP EOT to write the ajax call and declare javascript variable and here is my code as below:

And how to assgin the json result to the var json and json2?

ajax.php

$WH_GridLoadComplete = <<<WH_GridComplete

    var json;
    var json2;

    $.ajax({
        type:'POST',
        url:'getQTY.php',
        data:{"param3":"asdf"},
        dataType:"json",
        success:function(response){
            var json_object = JSON.parse(response);
            json = JSON.stringify(json_object);;
        }
    });

    $.ajax({
        type:'POST',
        url : 'getQTY.php',
        data : {"testing":"asdf"},
        dataType: "json",
        success : function(response){
            var json_object = JSON.parse(response);
            json2 = JSON.stringify(json_object);
        }
    });
    console.log(json);
    console.log(json2);
WH_GridComplete;

getQTY.php

if($_REQUEST['param3'] == 'asdf' || $_REQUEST["param3"] == ""){
    $B_qty = array();
    $conn_B = connectBdb();

    $ChkBShopItemSQL = "select itemcode,shopqty from shopitem where shopcode = 'B' AND shopqty <> 0;";
        foreach ($conn_B->query($ChkBShopItemSQL) AS $result) {
        $B_qty[$result['itemcode']] = $result['shopqty'];
    }
    echo json_encode($B_QTY);
}

if($_REQUEST["testing"] == "asdf" || $_REQUEST["testing"] == ""){
    $A_qty = array();
    $conn_A = connectAdb();
    $ChkAShopItemSQL = "select itemcode,shopqty from shopitem where shopcode = 'A' AND shopqty <> 0;";
        foreach ($conn_A->query($ChkAShopItemSQL) AS $result) {
        $A_qty[$result['itemcode']] = $result['shopqty'];
    }
    echo json_encode($A_qty);
}
leo leung
  • 27
  • 2
  • 5
  • 1
    Your `console.log` executed before the ajax call finished.Add `console.log` with in ajax success function – prasanth Mar 23 '19 at 16:15
  • Because the ajax method is asynchronous, so before actually getting the response and assigning it to the global variable, the console.log method is executed. – RopAli Munshi Mar 23 '19 at 16:16
  • how to I do can assign the response and assign to global variable? – leo leung Mar 23 '19 at 16:27

0 Answers0