Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unable to send json data via ajax [closed]

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.

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

like image 223
oyshee Avatar asked Dec 15 '14 02:12

oyshee


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

like image 116
ianaya89 Avatar answered Oct 14 '22 23:10

ianaya89