JavaScript, Ajax ,php parsererror, and How get post Json? - javascript

I got this code in game.php to refresh .refre, but I always get "parsererror". jsonString is from jsonString= JSON.stringify(object);
<div class="refre"></div>..
<script>...
jsonString ={"right":0,"arrayQ":[{"0":"10","idQ":"19"},
{"0":"34","idQ":"20"},{"0":"89","idQ":"14"}],"lives":40};
$.ajax({
type: 'POST',
data: jsonString,
dataType: 'json',
url: 'Q.php',
contentType : 'application/json; charset=utf-8'
}).done( function (data, status) {
$('.refre').load('Q.php');
alert('Right');
})
.fail( function (data, status) {
alert("Wrong: "+status);
});
...</script>
The other file is Q.php, this read the POST and send some HTML, Now It is just for check the information of the POST.
<?php
$value = json_decode($_POST);
$categories = json_decode(file_get_contents('php://input'));
print_r($value);
print_r($categories);
?>
What's wrong with the ajax?? how I get the POST in Q.php? how can I get 'lives' from the JSON in Q.php?

Try this,
<div class="refre"></div>..
<script>...
jsonString =[{"right":0,"arrayQ":[{"0":"10","idQ":"19"},
{"0":"34","idQ":"20"},{"0":"89","idQ":"14"}],"lives":40}];
$.ajax({
type: 'POST',
data: jsonString,
dataType: 'html',
url: 'Q.php',
contentType : 'application/json; charset=utf-8'
}).done( function (data, status) {
$('.refre').html(data);
alert('Right');
})
.fail( function (data, status) {
alert("Wrong: "+status);
});
...</script>
<?php
$value = json_decode($_POST);
$categories = json_decode(file_get_contents('php://input'));
print_r($value);
print_r($categories);
?>

What you call jsonString is not JSON, it is a javscript object.
When you pass an object to data of $.ajax , jQuery will form encode that data.
In php you would retrieve lives using $_POST['lives']. It is not being sent as JSON
Think of the keys in the object as name of a form input.
As for your output, you can only ever return one JSON string from server. The JSON must have one set of open/close braces so it can be turned into one array or object

<div class="refre"></div>
<script>
jsonString =[{"right":0,"arrayQ":[{"0":"10","idQ":"19"},{"0":"34","idQ":"20"},{"0":"89","idQ":"14"}],"lives":40}];
$.ajax({
type: 'POST',
data: jsonString,
url: 'Q.php',
}).done( function (data, status) {
$('.refre').html(data);
alert('Right');
})
.fail( function (data, status) {
alert("Wrong: "+status);
});
</script>
Q.php:
print_r($_POST);
This is OK. The 'data' will not be send as json. $_POST is an array in Q.php, you don't need to json_decode it.

Related

No data response when sending ajax request to php

i want to send a json data to my php but there is no response when i access it to my php.
this is my ajax request
var project = {project:"A"};
var dataPost = JSON.stringify(project);
$.ajax({
url: 'fetchDate.php',
data: {myData: dataPost},
type: 'POST',
datatype:'json',
contentType: "application/json",
success: function(data) {
alert(JSON.stringify(data));
}
});
});
and this is my php where i process the request and return back the data to test
<?php header("Content-Type: application/json; charset=UTF-8");
$objProject = json_decode($_GET["myData"]);
echo json_encode($objProject->project); ?>
i'm new to ajax so please i need your help
you don't need to add the content type on your ajax since you're not actually sending json to the server.
$.ajax({
url: 'fetchDate.php',
data: {myData: project},
type: 'POST',
datatype:'json',
// contentType: "application/json",
success: function(data, status, jqXHR) {
console.log(data,status,jqXHR);
alert(JSON.stringify(data));
}
});
no need to stringify project object,
in your php just encode it to json
<?php header("Content-Type: application/json; charset=UTF-8");
$obj = $_POST['myData'];
echo json_encode($obj); ?>
you should get json string on alert
Please try change
$objProject = json_decode($_GET["myData"]);
to
$objProject = json_decode($_POST["myData"]);
because ajax type : 'POST'
$.ajax({
url: 'fetchDate.php',
data: {myData: dataPost},
type: 'POST',
datatype:'json',
contentType: "application/json",
success: function(data) {
alert(JSON.stringify(data));
}

checking JSON data with jQuery

I have written a php script:
cch.php:
$stmtcheck = $mysqli->prepare("SELECT id,email,location FROM members WHERE email=? AND unlock_code=?");
$stmtcheck->bind_param("si", $_SESSION['unlockemail'], $_POST['code']);
$stmtcheck->execute();
$stmtcheck->bind_result($id,$email,$location);
$stmtcheck->fetch();
$array=array($id,$email,$location);
json_encode($array);
$stmtcheck->close();
And jquery for submitting form is
recover.php:
$("#formUnlock").submit(function(e)
{
e.preventDefault();
$.ajax(
{
url: '../scripts/cch.php',
method: 'POST',
data: $(#formUnlock).serialize(),
dataType: 'JSON',
success: function()
{
}
});
});
The script is returning more than one variable and the returned data should be in JSON format.
How do I read the data in jQuery?
$("#formUnlock").submit(function(e)
{
e.preventDefault();
$.ajax(
{
url: '../scripts/cch.php',
method: 'POST',
data: $(#formUnlock).serialize(),
dataType: 'JSON',
success: function(data) //parameter missing
{
var json = $.parseJSON(data);
console.log(json);
//in console you will get the result response
}
});
});
Hello your php code should echo the JSON output like this:
<?php
$stmtcheck = $mysqli->prepare("SELECT id,email,location FROM members WHERE email=? AND unlock_code=?");
$stmtcheck->bind_param("si", $_SESSION['unlockemail'], $_POST['code']);
$stmtcheck->execute();
$stmtcheck->bind_result($id,$email,$location);
$stmtcheck->fetch();
$array=array($id,$email,$location);
$stmtcheck->close();
echo json_encode($array);
?>
Now, in your javascript, you can use JSON.parse method to get the JSON.
Also, specifying your response type as JSON will automatically return a JSON object.
$("#formUnlock").submit(function (e) {
e.preventDefault();
$.ajax({
url: '../scripts/cch.php',
method: 'POST',
data: $('#formUnlock').serialize(),
dataType: 'JSON',
success: function (json_string) {
var res = JSON.parse(json_string);
console.log(res);//This should output your JSON in console..
}
});
});

data is empty from ajax request in whcms

I am trying to send a post request using ajax in whcms, but it seems that the data from the ajax request is null.
This is the ajax request:
function send_request(ticket_or_credit){
if(ticket_or_credit == 'ticket'){
var url = $("#ticket_action").val();
var ticket = $("#ticket_ticket").val();
var solution = $("#ticket_solution").val();
whmcs_data={ request_type:ticket, solution:solution };
jQuery.ajax({
type: 'POST',
url: url,
data: JSON.stringify(whmcs_data),
contentType:"application/json; charset=utf-8",
dataType: 'json',
success: function(results){
console.log(results);
console.log(whmcs_data);
},
error( xhr, ajaxOptions, thrownError ){
console.log( thrownError );
}
});
}
}
and in my php file:
$json = array("result" => "success", "message" => "Method is post", "data" => $_POST);
echo json_encode($json);
The $_POST is null.
Please help me, I haven't solve this problem for how many days :(
I removed the contentType and dataType of the ajax code just to make it default application/x-www-form-urlencoded; charset=UTF-8') and properly serialized whmcs_data variable. The output of your JSON.stringify is not properly serialized so I manually serialized it. for more information on ajax go to this : http://api.jquery.com/jquery.ajax/ and for JSON.stringify - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
try to replace variable whmcs_data declaration and ajax code with this:
whmcs_data = {
"request_type": ticket,
"solution": solution
};
$.ajax({
type: 'POST',
url: url,
data: whmcs_data,
success: function(results){
console.log(results);
console.log(whmcs_data);
},
error( xhr, ajaxOptions, thrownError ){
console.log( thrownError );
}
});

Use JSON result when ajax success

I have this code:
function openIzmeni(value) {
$.ajax({
url: "getRzaizmenu.php",
type: "POST",
async: true,
data: { vrednostid:value}, //your form data to post goes here as a json object
dataType: "html",
success: function(data) {
console.log(data);
$('#brojracuna1').val(data[0].br);
console.log(data[0].br);
console.log(data.br);
so as you can see I call getRzaizmenu.php to get JSON output.
getRzaizmenu.php code is:
try {
$result = $db->prepare("SELECT * FROM racuni WHERE ID=:id AND user_id=:user_id");
$result->execute(array(':id' => $_POST['vrednostid'], ':user_id' => $user_id));
$result = $result->fetchAll();
$r= json_encode($result);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
echo $r;
and this php return me output:
[{"ID":"22","0":"22","prefiks":"","1":"","br":"14321","2":"14321","sufiks":"993.67","3":"993.67","kupac":"Pavle Aleksov","4":"Pavle Aleksov","adresa":"Desanka Maksimovic 6\/a","5":"Desanka Maksimovic 6\/a","grad":"18320 Dimitrovgrad","6":"18320 Dimitrovgrad","pib":"567890","7":"567890","total":"1200.00","8":"1200.00","valuta":"Din","9":"Din","nacin":"gotovinsko","10":"gotovinsko","datum":"2015-05-25","11":"2015-05-25","rok":"2015-05-25","12":"2015-05-25","isporuka":"2015-05-25","13":"2015-05-25","naplaceno":"0000-00-00","14":"0000-00-00","napomene":"","15":"","interne":"","16":"","jezik":"","17":"","status":"","18":"","sifra":"yyx5y","19":"yyx5y","user_id":"1","20":"1"}]
So this code return me "0":22 and "ID":22 but its the same column.
and you can see I try to use this data into ajax success function like this:
success: function(data) {
console.log(data);
$('#brojracuna1').val(data[0].br);
console.log(data[0].br);
console.log(data.br);
but I get undefined.
How I can use data in success?
Change
dataType: "html",
to
dataType: "json",
And try again.
you have encoded the data, that's ok.
But while parsing you are not decoding the data. So you have to decode the data using JSON.parse() and parse function.
You need to parse the JSON, try like this
success: function(data) {
$.each(data, function(index, element) {
console.log(index);
console.log(element);
});
});

Sending Multidimentional array data, with ajax, to a php script

I have two simple scripts. One client-side jquery that has multidim array & a server-side php script. in php $data stays empty.
jquery
console.log("IN JQUERY");
console.log(inps);
$.ajax({
type: 'post',
cache: false,
url: './gen.php',
data: inps,
success: function(response){
console.log("RESPONSE");
console.log(response);
}
});
gen.php
<?php
$data = file_get_contents('php://input');
$data = json_decode($data, true);
print_r($data);
?>
firefox console output
>POST ..././gen.php [HTTP/1.1 200 OK 1ms]
>"IN JQUERY"
>{isbranch: "1", ismanager: "0", isdept: "1"}
>"RESPONSE"
>""
Is there a way to send Multi Dimensional array to the php with ajax without spliting array?
You should use JSON.stringify to encode your data before send it, also better to add correct contentType to it:
$.ajax({
type: 'post',
cache: false,
url: '/gen.php',
data: JSON.stringify(inps),
contentType: 'application/json',
success: function(response){
console.log("RESPONSE");
console.log(response);
}
});
The key-value pairs should already exist in your $_POST
$isbranch = $_POST['isbranch'];
$ismanager = $_POST['ismanager'];
$isdept = $_POST['isdept'];

Categories

Resources