I use the following to send the data:
$(".save_post").on("click", function() {
var saveId = $(".my_post_id").attr("data-id");
console.log(saveId);
$.ajax({
url: "save.php",
data :saveId,
type: 'POST',
success: function(json_object) {
console.log(json_object);
$(".save_post").text("Data has been saved.");
},
error: function(json_object) {
console.log(json_object);
$(".save_post").text("Failed to save data !");
}
});
});
Console value when I do console.log(saveId); is 248
And when I click the button to send the data, its text says: Data has been saved.
But when I open save.php i get an empty page.
PHP code:
<?php
$post_data = $_POST['data'];
echo $post_data;
?>
All I am trying to do is to save a javascript variable in order to be able to retrieve it later on.
You forgot to send a key with the value:
data: { data: saveId }
You should also use the data() method to get data-* attributes, not attr(). Here's a full example:
$(".save_post").on("click", function() {
$.ajax({
url: "save.php",
data: { data: $(".my_post_id").data("id") },
type: 'POST',
success: function(response) {
console.log(response);
$(".save_post").text("Data has been saved.");
},
error: function(x, s, e) {
$(".save_post").text("Failed to save data !");
}
});
});
Note that this is assuming you have only a single .my_post_id element. If you have multiple then data-id will only be read from the first one found in the DOM.
Also, there's no such thing as a 'JSON object'. The argument provided to the success handler is an object (or array) which has been deserialised from the JSON formatted string in the response.
Similarly, the error handler doesn't accept an argument which contains JSON, so that signature is incorrect. I'd suggest checking the jQuery $.ajax() documentation if you are unsure on what arguments are available to which jQuery AJAX handlers.
You need to send JSON data so that php can retrive the same data using key
$(".save_post").on("click", function() {
var saveId = $(".my_post_id").attr("data-id");
console.log(saveId);
$.ajax({
url: "save.php",
data : {'data':saveId}, // Add object
type: 'POST',
success: function(json_object) {
console.log(json_object);
$(".save_post").text("Data has been saved.");
},
error: function(json_object) {
console.log(json_object);
$(".save_post").text("Failed to save data !");
}
});
});
try this :
$post_data = $_POST;
echo $post_data;
It will works for you.
Related
I am using this javascript function to send data to my php script (via POST) I am then using this information to retrieve data from my database and I would like to reuse the information retrieved in my JavaScript code.
Here is my code :
$(document).on("click", "#validerChoixDeCours", function() {
jQuery.ajax({
type: "POST",
url: 'myFunctions.php',
dataType: 'json',
data: {
functionname: 'proposePA',
arguments: clickedButtons
},
success: function() {
// HERE I would like to inctercept the data that my php script put in myFunctions.php produces and use it to generate content;
}
});
});
So basically, when clicking on the button #validerChoixDeCours, my code sends some data to myFunctions.php which generates a response stored in a php variable and I want to use that response in my JS code.
Thank you in advance for your help :)
Its actually quite easy!
$(document).on("click", "#validerChoixDeCours", function() {
jQuery.ajax({
type: "POST",
url: 'myFunctions.php',
dataType: 'json',
data: {
functionname: 'proposePA',
arguments: clickedButtons
},
success: function(e) {
e contains the response from the php script
}
});
});
The first parameter of success contains the response from the request. so, in this case, the 'e' variable contains the output which you can use.
Add data variable
$(document).on("click", "#validerChoixDeCours", function() {
jQuery.ajax({
type: "POST",
url: 'myFunctions.php',
dataType: 'json',
data: {
functionname: 'proposePA',
arguments: clickedButtons
},
success: function(data) {
alert(data);
}
});
});
make sure your server side code look like this
<?php
$output = "Any String or Array";
echo json_encode($output);
?>
function getReportedInfo(id) {
$.ajax({
url: 'includes/get_data.php',
type: 'POST',
data: {id:id},
dataType: 'json',
success: function(data) {
console.log(data);
}
});
};
The JSON object returned from the get_data.php script is:
{
id: 5,
username: "Anthony",
status: "accupied"
}
I am able to the length of the data object if I do console.log(data.length). However, I can see the object when I console.log(data) in the success property.
I am not able to access the elements of the data obejct if I do console.log(data.username), doing this displays undefined in the console.
I created a variable, data1, outside the scope of the function getReportedInfo and assigned the data retrieved via the success property to
this variable after I tried to display the constents of data1 outside the function.
Sounds like data is a string not an object. You can convert this to an object by using JSON.parse. Try the following code.
function getReportedInfo(id) {
$.ajax({
url: 'includes/get_data.php',
type: 'POST',
data: {id:id},
dataType: 'json',
success: function(data) {
var dataObject = JSON.parse(data);
console.log(dataObject.username);
}
});
};
Edit
After discussing with OP in comments below, it was determined the object returned data was in a structure like the following, and is already in an object form (not a string)
{
"0": {
id: 5,
username: "Anthony",
status: "accupied"
}
}
Therefor the following code should work.
function getReportedInfo(id) {
$.ajax({
url: 'includes/get_data.php',
type: 'POST',
data: {id:id},
dataType: 'json',
success: function(data) {
console.log(data["0"].username);
}
});
};
If in php your return like this way
<?php
echo json_encode($array);
// or
return json_encode($array);
In JavaScript you can use it as you try to use, now, apparently you are not returning a JSON even though you are indicating it in the request, in this case it uses parse:
function getReportedInfo(id) {
$.ajax({
url: 'includes/get_data.php',
type: 'POST',
data: { id:id },
success: function(data) {
var response = JSON.parse(data);
console.log(response.id); // return 5
}
});
};
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
I have My jquery function that is returning me data of the formatt:
{"Suggestions":[{"name":"RR Restaurant","category_id":"166","locality":"Gayathri Nagar","listing_info":"listing","random_id":"1ll0f0wJ"},{"name":"Oko Restaurant","category_id":"166","locality":"Kumara Krupa","listing_info":"listing","random_id":"0F7ZGV9p"},{"name":"H2O Restaurant","category_id":"166","locality":"Maratha Halli","listing_info":"listing","random_id":"0JNPOyuP"},{"name":"Taj Restaurant","category_id":"166","locality":"Shivaji Nagar","listing_info":"listing","random_id":"7GeA0Kfq"},{"name":"PSR Restaurant","category_id":"166","locality":"Peenya Industrial Area","listing_info":"listing","random_id":"cRvJCwQ3"},{"name":"ac restaurant","category_id":"166","listing_info":"keyword"},{"name":"Indian Restaurant","category_id":"166","listing_info":"keyword"},{"name":"goan restaurant","category_id":"166","listing_info":"keyword"},{"name":"thai restaurant","category_id":"166","listing_info":"keyword"},{"name":"andhra restaurant","category_id":"166","listing_info":"keyword"}],"ImpressionID":"test"}
I wish to parse the same to get multiple variables with The field "Name" and "Random Id" in different js variables
$("#what").on("keypress", function() {
$.ajax({
type: "GET",
cache: false,
url: "/AutoComplete.do",
data: {
query: 'Pest',
city: 'Bangalore'
}, // multiple data sent using ajax
success: function(data) {
alert();
}
});
});
My JSON object seems to be nested with "Suggestions" as the parent. Please help.
If you add a property to $.ajax function you be ensure that is json parsing:
dataType: 'json'
EDIT
To iterate above the string you can use for(in) or each() jquery
json = "[{'key':'value'},{'key':'value']";
for(var i in json) {
console.log(json[i]);
//if you see in console [OBJECT Object] you are
//in a new object you must to iterate nested of this.
}
$("#what").on("keypress", function() {
$.ajax({
type: "GET",
dataType: "JSON", //You need this to be inserted in your ajax call.
cache: false,
url: "/AutoComplete.do",
data: {
query: 'Pest',
city: 'Bangalore'
}, // multiple data sent using ajax
success: function(data) {
alert();
}
});
});
After insert dataType you can probably do this.
console.log(data.Suggestions);
Also take a look at the API Doc at below url regardless of dataType.
http://api.jquery.com/jquery.ajax/
The data object you are specifying is what will be sent as the arguments to your success method, if you use the GET method.
$("#what).on("keypress", function() {
$.get("/AutoComplete.do", function(response) {
var data = JSON.parse(response);
//data.suggestions = [lots of objects];
//data.suggestions[0].locality = "Gayathri Nagar"
});
});
I need to call an asp.net page from javascript with queryString having Arabic text. It shows me an error when goes online but works smoothly on the local server. When arabic value is small then it works smoothly problem arises when arabic text is in multiple lines.
$.ajax({
url: "Empty/emptyGovt2.aspx",
data: "arKeyword="+encodeURIComponent($("#txt_arKeywords").val(),
success: function(data) {
diaL("Details Updated Successfully");
},
error: function(){
diaL('Error Occurred');
}
});
Dont use get with long and complex datas use post
$.ajax({
url: "Empty/emptyGovt2.aspx",
type:"POST",
data: {
"arKeyword" :$("#txt_arKeywords").val(),
"OrgId" : newParentOfficeID
// etc
},
success: function(data) {
diaL("Details Updated Successfully");
},
error: function(){
diaL('Error Occurred');
}
});
And on the php you can access the values as $_POST['OrgId'] etc
I would suggest you to use POST and dataType:'json' or 'text':
$.ajax({
url: "Empty/emptyGovt2.aspx",
type: 'POST',
data: {"arKeyword" : $("#txt_arKeywords").val()}, //<----json objects
dataType: 'json', //<----dataType
success: function(data) {
// retriev json response
var respData = $.parseJSON(data);
$.each(respData, function(i, item){
console.log(item);
});
diaL("Details Updated Successfully");
},
error: function(){
diaL('Error Occurred');
}
});
and make sure to return json from 'Empty/emptyGovt2.aspx'