Neeraj Verma Neeraj Verma - 2 months ago 10
Javascript Question

javascript ajax not sending array to php on same page

I dig my head a lot about this topic , but every solution i tried have some error ...

after reading some posts i have tried to create a simple demo of jquery+ajax call+php , but it is not retrieving array by post method on same page

My script

var stuff ={'key1':'value1','key2':'value2'};

$("#btn").click(function(e) {

e.preventDefault();
$.ajax({
type : 'POST',
url : '3.php',
data : {result:JSON.stringify(stuff)},
success : function(response) {
console.log(response);
}
});

});


and

php

if(isset($_POST['result'])) {
$data = $_POST["result"];
$data = json_decode("$data", true);
echo "key1 : ".$data["key1"];

}


edit : success function is fine , it is giving me response , but i am not getting data by post ...

but neither i am getting any error , not any data , How can i trace what I m doing wrong ?

Answer
<?php

if(isset($_POST['result'])) {
    $data    = $_POST["result"];
    $data    = json_decode("$data", true);
    echo "key1 : ".$data["key1"];
    die();
}

?>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

<script>
var stuff ={'key1':'value1','key2':'value2'};


$( document ).ready(function() {

    $("#btn").click(function(e) {

    e.preventDefault();
  $.ajax({
    type    : 'POST',
    url     : '3.php',
    data    : {result:JSON.stringify(stuff)},
    success : function(response) {
        $('#result').html(response);
    }    
});

});

});

</script>



<input type='button' id='btn' value='RUNN'>


<div id='result'></div>
Comments