Sending PHP json_encode array in jQuery

OK, I think I need help! I searched for every keyword that I could think of, but I still can’t understand, please help. I'm more of a php guy, and I just started with jQuery.

Basically, I'm trying to send a jQuery message from a click function. And based on what my php function returns, show / hide 2 divs. My php function returns an array "json_encode" with two simple values, for example:

// =================== PHP code ============================ =======

$message_for_user = "blah blah";
$calculatedValue = 1230;
$responseVar = array(
                    'message'=>$message_for_user,
                    'calculatedValue'=>$calculatedValue
                    );
echo (json_encode($responseVar));

// ================== PHP code End ============================ =======

My javascript code should accept the values ​​returned by php:

// =================== Javascript code ============================= =================================================== =

$("div.calculator_result").click(function()
{
    $.post('myCalculator.php' ,{qid:itemID},function(response)
    {
        $("div.calculation_value").show(500).html(response['calculatedValue']);
        $("div#message_for_user").show(500).html(response['message']);
    }
}

//================== Javascript code ========================= ==========

, javascript , divs , php-.... ? , , , , .

, , (echo $calculateValue), , , echo'in json encode array,

+3
4
var json = $.parseJSON(response); alert(json.message);
+18

dataType:

$.post('myCalculator.php' ,{qid:itemID},function(response)
{
    $("div.calculation_value").show(500).html(response['calculatedValue']);
    $("div#message_for_user").show(500).html(response['message']);
}, 'json');

NB ), .

+2

JSON. jQuery ( , IE6 7 JSON). :

$.parseJSON(response)

, JSON, ( Firebug ), . , .

EDIT: $. getJSON, . , .:)

+1

, , Ajax, "json". ...

$.ajax({
   url: "external_file",
   method:"post",
   dataType: "json",  // **************** Note dataType****************
   success:function(response){
       console.log(response)
       // Response will be a javascript array, instead of a string.
   },
   error: function(){
       alert('something went wrong.')
   }
})
0

Source: https://habr.com/ru/post/1776120/


All Articles