无法通过ajax发送json数据

时间:2023-01-03 18:13:29

I'm creating a json data with a click event. then i am trying to send the json data to my php script via ajax and alert a response. But i'm unable to send the json data to my php script. its returning NUll.

我正在创建一个带有单击事件的json数据。然后,我尝试通过ajax将json数据发送到php脚本并发出响应。但是我无法将json数据发送到php脚本。它返回NUll。

jquery script:

jquery脚本:

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脚本

<?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 use data on php script and the php returning NULL reponse

无法在php脚本和php返回空响应中获取数据。

2 个解决方案

#1


5  

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 in your PHP side you could get the value writing: $obj = $_POST['data'];

然后在PHP端,您可以得到这样的值:$obj = $_POST['data'];

#2


0  

JSON object should be an object, not array. You better do something like this.

JSON对象应该是对象,而不是数组。你最好这样做。

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

#1


5  

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 in your PHP side you could get the value writing: $obj = $_POST['data'];

然后在PHP端,您可以得到这样的值:$obj = $_POST['data'];

#2


0  

JSON object should be an object, not array. You better do something like this.

JSON对象应该是对象,而不是数组。你最好这样做。

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