Failed to send json data via ajax

I am creating json data with a click event. then I'm trying to send json data to my php script via ajax and alert the response. But I can not send json data to my PHP script. his return null.

jquery script:

var jsonObj = []; $("#additembtn").click(function(event){ event.preventDefault(); var obj = {}; obj["medicine_name"]=parsed.medicine_name; obj["quantity"]=unit; obj["price"]=price; jsonObj.push(obj); console.log(jsonObj); }) $("#order").click(function(event){ event.preventDefault(); $jsonObj=JSON.stringify(jsonObj) $.ajax({ url: "../siddiqa/function/ordermedicine.php", type: "POST", //dataType: "json", data: jsonObj, success:function(data, textStatus, jqXHR) { alert(data); }, error: function(jqXHR, textStatus, errorThrown) { //if fails } }) }) 

PHP SCRIPT

 <?php require_once('../configuration.php'); $con=new mysqli($hostname,$dbusername,$dbpass,$dbname); if (mysqli_connect_errno($con)) { die('The connection to the database could not be established.'); } $obj = json_decode($_POST['jsonObj']); echo $obj['medicine_name']; ?> 

Unable to get data in php script and php response returning NULL

+6
source share
2 answers

The problem is that you are trying to send an array and you need to send an object :

 $.ajax({ url: "../siddiqa/function/ordermedicine.php", type: "POST", data: { data: jsonObj }, success:function(data, textStatus, jqXHR) { alert(data); }, error: function(jqXHR, textStatus, errorThrown) { } }); 

Then on your PHP side you can get the value: $obj = $_POST['data'];

+5
source

The JSON object must be an object, not an array. You better do something like that.

 $jsonObj = {array: jsonObj}; $jsonObj = JSON.stringify(jsonObj); 
0
source

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


All Articles