That is my function, for exp.:
adId = 1, adTitle = test
function deleteAd(adId, adTitle) {
$.ajax({
dataType: 'json',
url: 'ajax.php',
type: 'POST',
data: {
adId : adId,
adTitle: adTitle
},
success: function(data) {
alert(data);
}
});
That is ajax.php:
echo $_POST['adId']; echo $_POST['adTitle'];
But echo only adId, don't have adTitle.
I try this:
data: {
adId : adId,
adTitle: "test"
},
And don't have result too. With HttpFox I found this post and postdata is: adId=1&&adTitle=test
If your variable test === undefined then it will not get posted to your PHP script therefore you will not see it on the server side.
If test is an empty string than you just might not be seeing it on the client due to it not having any visible length.
Try doing: var_dump($_POST['adTitle']);
Related
I Am trying to send value from ajax to php and retrieve it just to test that everything is work, when i click in a button to test i got error and alert('Failed') Appears , how can i fix it in order to get success? thanks
Ajax :
var a = "test";
$.ajax({
url: "search.php",
dataType: "json",
data: a ,
success: function(data) {
alert('Successfully');
},
error: function(data) {
alert('Failed');
}
})
PHP :
<?php
$pictures = "img1";
echo json_encode($pictures);
?>
I refined your code slightly and it works.
var a = "test";
$.ajax({
type: 'POST',
url: 'search.php',
data: 'a=' + a,
dataType: 'json',
cache: false,
success: function (result) {
alert('Successful');
},
error: function (result) {
alert('Failed');
}
});
If you're requesting a JSON, use the $.getJSON from jQuery, it's aready parse the JSON into a JSON object for you.
Seems that you're not return an actual JSON from server, maybe this is what is causing the error.
If you're seeing the 'Failed' message probably the problem is a 500 error which is a server error.
Try this code above.
Javascript:
var a = "test";
$.getJSON("search.php", {
a: a
}, function (json) {
console.log(json);
});
PHP:
<?php
$pictures = ["img1"];
echo json_encode($pictures);
The only way to this not work, is if you have a huge mistake on you webserver configuration.
Your ajax is wrong, it should be:
var a = "test";
$.ajax({
type: "POST",
url: "search.php",
dataType: "json",
data: {a:a},
success: function(data) {
alert('Successfully');
},
error: function(data) {
alert('Failed');
}
});
I have the following Jquery code that sends a ajax request to add-to-cart.php.
var productData = {
"product_id": s_product_id,
"product_opties": s_product_opties,
"product_aantal": s_product_aantal
}
productData = JSON.stringify(productData);
$.ajax({
url: 'inc/add-to-cart.php',
dataType: "json",
contentType: "application/json; charset=utf-8",
data: productData,
type: 'POST',
success: function(response) {
alert(response.d);
},
error: function(e){
console.log(e);
}
});
Add-to-cart.php:
<?php
print $_POST['product_id'];
?>
I am having two problems, the first one is that the $_POST['product_id'] does not exists when i ask for it and secondly when the ajax response returns it goes directly to the error: function and not succes function
The console log says:
[object Object]{readyState: 4, responseText: "<br /> <b>N...", status: 200, statusText: "OK"}
If the status is OK why does it jump to the error: part?
Thanks!
Try with:
...
var productData = {
'product_id': s_product_id,
'product_opties': product_opties,
'product_aantal': product_aantal,
}
$.ajax({
url: 'inc/add-to-cart.php',
dataType: 'json',
data: productData,
type: 'POST',
success: function(response) {
console.log(response.d);
},
error: function(e){
console.log(e);
}
});
...
Omitting the AJAX contentType parameter and the part where you stringify your JSON, that's already ready to be sent to your url, so, isn't needed.
Remove the line
productData = JSON.stringify(productData);
Then do not return HTML <br> ... from add_to_cart.php, you need to return a JSON string created by the PHP function json_encode and NOTHING ELSE.
Like in:
<?php echo json_encode(array('d' => 'value of d'));
First: status Code from the Webserver is 200 cause he deliverd an existing site.
Second: You dont need to stringify the json object by urself
Im submitting Data to a php file via AJAX using POST.
It worked fine with just submitting strings, but now I wanted to submit my JS Object with JSON and decode it on PHP side.
In the console I can see, that my data is submitted correctly but on PHP side json_decode returns NULL.
I've tried the following:
this.getAbsence = function()
{
alert(JSON.stringify(this));
jQuery.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ajax/selectSingle.php?m=getAbsence",
data: JSON.stringify(this),
success : function(data){
alert(data);
}
});
}
PHP:
echo $_POST['data'];
echo json_decode($_POST['data']);
echo var_dump(json_decode($_POST['data']));
And:
this.getAbsence = function()
{
alert(JSON.stringify(this));
jQuery.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ajax/selectSingle.php?m=getAbsence",
data: {'Absence' : JSON.stringify(this)},
success : function(data){
alert(data);
}
});
}
PHP:
echo $_POST['Absence'];
echo json_decode($_POST['Absence']);
echo var_dump(json_decode($_POST['Absence']));
The alert was just to check everything is alright...
And yea usual string were echoed correctly :-)
Where you went wrong in your code in the first code is that you must have used this:
var_dump(json_decode(file_get_contents("php://input"))); //and not $_POST['data']
Quoting from PHP Manual
php://input is a read-only stream that allows you to read raw data from the request body.
Since in your case, you are submitting a JSON in the body, you have to read it from this stream. Usual method of $_POST['field_name'] wont work, because the post body is not in an URLencoded format.
In the second part, you must have used this:
contentType: "application/json; charset=utf-8",
url: "ajax/selectSingle.php?m=getAbsence",
data: JSON.stringify({'Absence' : JSON.stringify(this)}),
UPDATE:
When request has a content type application/json, PHP wont parse the request and give you the JSON object in $_POST, you must parse it yourself from the raw HTTP body. The JSON string is retrieved using file_get_contents("php://input");.
If you must get that using $_POSTyou would make it:
data: {"data":JSON.stringify({'Absence' : JSON.stringify(this)})},
And then in PHP do:
$json = json_decode($_POST['data']);
Single quotes are not valid for php's json_encode, use the double quotes for both field names and values.
To me, it looks like you should reformat your AJAX object. The url-property should only be the URL for the target php-file and any data that needs to be posted should be in the form of a query-string in the data-property.
The following should work as you expected:
this.getAbsence = function() {
var strJSONData = JSON.stringify(this);
alert(strJSONData);
jQuery.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: 'ajax/selectSingle.php',
data: 'm=getAbsence&Absence=' + strJSONData,
success: function(data) {
alert(data);
}
});
}
try this
var vThis = this;
this.getAbsence = function()
{
alert(JSON.stringify(vThis));
jQuery.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ajax/selectSingle.php?m=getAbsence",
data: JSON.stringify(vThis),
success : function(data){
alert(data);
}
});
}
EDIT
I think we can also do this!
var vThis = this;
this.getAbsence = function()
{
alert(JSON.stringify(vThis));
jQuery.ajax({
type: "POST",
dataType: "json",
url: "ajax/selectSingle.php?m=getAbsence",
data: vThis,
success : function(data){
alert(data);
}
});
}
and in PHP
print_r($_POST);
On PHP side try this:
$sectionValue = htmlspecialchars($_POST['sectionValue'], ENT_QUOTES);
$dataToWrite = json_decode(html_entity_decode($sectionValue, ENT_QUOTES, "utf-8" ), true);
Okay so here is my problem. I have a simple jQuery Ajax request and I can't get is work when I set the DataType to "JSON".
var form_data = { "id": msg, "token": token };
$.ajax({
type: 'POST',
url: "ajax.php",
data: form_data,
dataType: 'json',
beforeSend:function(){
// this is where we append a loading image
},
success: function(data) {
var thing = JSON.parse(data);
$('.body-item').html(thing.b);
},
error: function() {
alert('error');
}
});
This is my ajax file actually. The ajax.php looks like this:
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
$foo = json_encode($arr);
echo $foo;
When I run the jQuery script, I got a 200:OK response with Firebug, and when I take a look at the response I got the following: {"a":1,"b":2,"c":3,"d":4,"e":5}
However I do NOT get anything showed in the .body-item div, nor if I try with alert().
Also if I run the same code WITHOUT the: dataType: 'json' part, I get everything outputted correctly.
What could be the issue here?
When you use dataType: 'json', jQuery calls JSON.parse() and puts the result in data. You shouldn't call it yourself, since data is not a JSON string, it's the parsed object. So just do:
$('body-item').html(data.b);
From the documentation:
"json": Evaluates the response as JSON and returns a JavaScript object.
I have a simple php file that decode my json string, passed with ajax, and stamp the result, but I can't keep the $_POST variable, why???
I try to inspect with fireBug and I can see that the POST request is sent correctly, when the php script is called, he respond Noooooooob to me, it seem any POST variable is set.
All I want is to have my array =)
JSON String generated by JSON.stringify:
[
{
"id":21,
"children":[
{
"id":196
},
{
"id":195
},
{
"id":49
},
{
"id":194
}
]
},
{
"id":29,
"children":[
{
"id":184
},
{
"id":152
}
]
},
...
]
JavaScript
$('#save').click(function() {
var tmp = JSON.stringify($('.dd').nestable('serialize'));
// tmp value: [{"id":21,"children":[{"id":196},{"id":195},{"id":49},{"id":194}]},{"id":29,"children":[{"id":184},{"id":152}]},...]
$.ajax({
type: 'POST',
url: 'save_categories.php',
dataType: 'json',
data: {'categories': tmp},
success: function(msg) {
alert(msg);
}
});
});
save_categories.php
<?php
if(isset($_POST['categories'])) {
$json = $_POST['categories'];
var_dump(json_decode($json, true));
} else {
echo "Noooooooob";
}
?>
Your code works if you remove dataType: 'json', just tested it.
$('#save').click(function() {
var tmp = JSON.stringify($('.dd').nestable('serialize'));
// tmp value: [{"id":21,"children":[{"id":196},{"id":195},{"id":49},{"id":194}]},{"id":29,"children":[{"id":184},{"id":152}]},...]
$.ajax({
type: 'POST',
url: 'save_categories.php',
data: {'categories': tmp},
success: function(msg) {
alert(msg);
}
});
});
it's work for me you can try this.
JavaScript
$('#save').click(function() {
$.ajax({
type: 'POST',
contentType: 'application/json',
url: 'save_categories.php',
dataType: 'json',
data: JSON.stringify({'categories': $('.dd').nestable('serialize')}),
success: function(msg) {
alert(msg);
}
});
});
you need to write the below code on save_categories.php
$_POST is pre-populated with form data.
To get JSON data (or any raw input), use php://input.
$json = json_decode(file_get_contents("php://input"));
$categories = $json->categories;
dataType is json, so jQuery posts this:
{"categories":"[{\"id\":21,\"children\":[{\"id\":196},{\"id\":195},{\"id\":49},{\"id\":194}]},{\"id\":29,\"children\":[{\"id\":184},{\"id\":152}]},...]"}
This is not standard urlencoded, so $_POST is empty.
You can set data to your complex structure, and jQuery will correctly encode it:
$('#save').click(function() {
$.ajax({
type: 'POST',
url: 'save_categories.php',
dataType: 'json',
data: $('.dd').nestable('serialize'),
success: function(msg) {
alert(msg);
}
});
});
And in php: $categories = json_decode(file_get_contents('php://stdin'));
Try this:
$('#save').click(function() {
var tmp = JSON.stringify($('.dd').nestable('serialize'));
// tmp value: [{"id":21,"children":[{"id":196},{"id":195},{"id":49},{"id":194}]},{"id":29,"children":[{"id":184},{"id":152}]},...]
$.ajax({
type: 'POST',
url: 'save_categories.php',
dataType: 'json',
data: 'categories=' + encodeURIComponent(tmp),
success: function(msg) {
alert(msg);
}
});
});
I changed just this line:
data: 'categories=' + encodeURIComponent(tmp),
because thats the way, how you have to write data there. I tested it, its working...