Here is a partial example of what I am trying to achieve.
I am trying to retrieve a value from ajax but the javascript result.success variable is undefined. I have the following:
PHP:
$result = array ("success" => null, "html" => "");
$result['success'] = true;
$result['html'] = "test";
echo json_encode($result);
Javascript/jQuery:
var ID = 1
$.ajax({
type: 'POST',
url: '/ajax/load.php',
contentType: "application/json; charset=utf-8",
datatype: 'json',
data: {ID: ID},
beforeSend: function(xhrObj) {
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Accept","application/json");
},
success: function(result) {
if (result.success) {
// do something
}
});
The response I am getting from ajax (retrieved from chrome dev tools) is {"success":true,"html":"Test"}
This looks fine to me however in the JavaScript result.success is undefined. I believe this will be simple I just can't see where the issue lies..
Your error is here:
datatype: 'json',
Javascript is case sensitive and the property is dataType:
dataType: 'json',
Because of that, jQuery is not being told to automatically parse the JSON, so the result is just treated as html or plain text.
You also need to remove the content-type header because that specifies the content type for the request not response. You are sending form/url encoded in the request, not JSON.
$.ajax({
type: 'POST',
url: '/ajax/load.php',
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: {ID: ID},
beforeSend: function(xhrObj) {
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Accept","application/json");
},
success: function(result) {
if (result.success) {
// do something
}
} // Maybe your forgot this
});
in other words - Basic Debugging
in your PHP page put this on top of the page (you are accepting only json response but probably your response headers content type is text/html
header('Content-type: application/json');
Related
I would like to post Json to a web service on the same server. But I don't know how to post Json using JQuery. I have tried with this code:
$.ajax({
type: 'POST',
url: '/form/',
data: {"name":"jonas"},
success: function(data) { alert('data: ' + data); },
contentType: "application/json",
dataType: 'json'
});
But using this JQuery code the data is not received as Json on the server. This is the expected data at the server: {"name":"jonas"} but using JQuery the server receive name=jonas. Or in other words, it's "urlencoded" data and not Json.
Is there any way to post the data in Json format instead of urlencoded data using JQuery? Or do I have to use a manual ajax request?
You're passing an object, not a JSON string. When you pass an object, jQuery uses $.param to serialize the object into name-value pairs.
If you pass the data as a string, it won't be serialized:
$.ajax({
type: 'POST',
url: '/form/',
data: '{"name":"jonas"}', // or JSON.stringify ({name: 'jonas'}),
success: function(data) { alert('data: ' + data); },
contentType: "application/json",
dataType: 'json'
});
Base on lonesomeday's answer, I create a jpost that wraps certain parameters.
$.extend({
jpost: function(url, body) {
return $.ajax({
type: 'POST',
url: url,
data: JSON.stringify(body),
contentType: "application/json",
dataType: 'json'
});
}
});
Usage:
$.jpost('/form/', { name: 'Jonh' }).then(res => {
console.log(res);
});
you can post data using ajax as :
$.ajax({
url: "url",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ name: 'value1', email: 'value2' }),
success: function (result) {
// when call is sucessfull
},
error: function (err) {
// check the err for error details
}
}); // ajax call closing
I tried Ninh Pham's solution but it didn't work for me until I tweaked it - see below. Remove contentType and don't encode your json data
$.fn.postJSON = function(url, data) {
return $.ajax({
type: 'POST',
url: url,
data: data,
dataType: 'json'
});
The top answer worked fine but I suggest saving your JSON data into a variable before posting it is a little bit cleaner when sending a long form or dealing with large data in general.
var Data = {
"name":"jonsa",
"e-mail":"qwerty#gmail.com",
"phone":1223456789
};
$.ajax({
type: 'POST',
url: '/form/',
data: Data,
success: function(data) { alert('data: ' + data); },
contentType: "application/json",
dataType: 'json'
});
Using Promise and checking if the body object is a valid JSON. If not a Promise reject will be returned.
var DoPost = function(url, body) {
try {
body = JSON.stringify(body);
} catch (error) {
return reject(error);
}
return new Promise((resolve, reject) => {
$.ajax({
type: 'POST',
url: url,
data: body,
contentType: "application/json",
dataType: 'json'
})
.done(function(data) {
return resolve(data);
})
.fail(function(error) {
console.error(error);
return reject(error);
})
.always(function() {
// called after done or fail
});
});
}
I have the following code:
var arr = {City:'Moscow', Age:25};
$.ajax({
url: "<? echo $this->createUrl('cities/index');?>",
type: "POST",
data: JSON.stringify(arr),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function(data){
alert(data);
}
});
The result is null. In the PHP side I have:
echo json_encode($_POST);
and
print_r($_POST);
But both are giving empty results (checked Firebug also).
You can also set the dataType in Ajax to specify the content type as follows.
var city='city name';
var age=10;
$.ajax({
url: "<? echo $this->createUrl('cities/index');?>",
type: "POST",
data:"City="+city+"&Age="+age,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function(data){
alert(data);
}
});
and in cities/index.php you can get this data by follows
if($_POST){
$city=$_POST['City'];
$age=$_POST['Age'];
// and do with $city and $age what you want.
//for return anything thing to `json` use follows we pass $age back to ajax
echo json_encode($age);
}
I guess you don't need to stringyfy the data because data should be PlainObject or String but in your case you can simply write like below
var arr = {City:'Moscow', Age:25};
$.ajax({
url: "<? echo $this->createUrl('cities/index');?>",
type: "POST",
data: arr,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function(data){
alert(data);
}
});
as documented in jquery official site https://api.jquery.com/jQuery.ajax/
data
Type: PlainObject or String
Data to be sent to the server. It is converted to a query string, if
not already a string. It's appended to the url for GET-requests. See
processData option to prevent this automatic processing. Object must
be Key/Value pairs. If value is an Array, jQuery serializes multiple
values with same key based on the value of the traditional setting
(described below).
The data option passed to $.ajax() must be either a simple object, that jQuery will transform into a string of the formatkey1=value1&key2=value2.. OR it should be a string of the form key1=value1&key2=value2...
In your case, it can be solved by passing the object itself and letting jQuery do the query string formatting:
$.ajax({
...
data: arr,
...
});
try this
var arr = {City:'Moscow', Age:25};
$.ajax({
url: "<? echo $this->createUrl('cities/index');?>",
type: "POST",
data: arr,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function(data){
alert(data);
}
});
We want to post a json object to PHP, this is what we currently have:
var sitePersonel = {};
var userData = [];
sitePersonel.userData = userData;
var userData = {
"userId": username,
"name": name,
"artists": artistNames
};
sitePersonel.userData.push(userData);
console.log(sitePersonel);
var jsonpArray = JSON.stringify(sitePersonel);
function phpCallback() {
}
$.ajax({
type: "POST",
dataType: "jsonp",
url: "http://student.cmd.hro.nl/0879644/spotify/data.php",
data: { myData: jsonpArray },
success: function (data) {
alert('Items added');
},
jsonpCallback: phpCallback(),
error: function (e) {
console.log(e.message);
}
We are getting an error, on loading this jQuery. We have tried debugging, but onfortunately, we aren't getting far. Our console gives the following error:
Resource interpreted as Script but transferred with MIME type text/html
We do land into the phpCallback(); but the console is giving us errors and PHP isn't working either.
We want to send the JSON object to PHP to save into a database. We are working on a Spotify App.
Try changing content type to text/javascript
JSONP request: "Resource interpreted as Script but transferred with MIME type text/html"
Hope this solves your problem.
plain example, modify to your own case (i.e. dataType from json to jsonp)
jQuery.ajax({
url: url,
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: data,
success: callback
});
Add content-type in your ajax
contentType: "application/json",
By default it is 'application/x-www-form-urlencoded; charset=UTF-8'
My jQuery ajax posting is not working. Here is the javascript
function SocialButtons() {
var $buttonWrapper = jQuery('.WrapperDiv');
if ($buttonWrapper.length){
var postData = $buttonWrapper.html();
jQuery.ajax({
type: 'POST',
url: 'http://www.wordpress-site.com/wp-contents/themes/theme-name/post.php',
data: postData,
cache: false,
success: function(data) {
console.log(data);
},
contentType: "application/json",
dataType: 'json'
});
}
}
I am saving the data to be posted inside a hidden div like
<div class='WrapperDiv hidden'>{"post_id":392,"url":"http:\/\/www.wordpress-site\/post\/post-title\/","title":"SEO Friendly title"}</div>
All I am getting in return from the post.php page is an empty array. Here is my code for post.php
<?php
if(isset($_POST)){
print_r($_POST);
} else {
echo "0";
}
?>
Any Idea whats wrong?
EDIT : Its working after I removed
contentType: "application/json",
dataType: 'json'
What about something like this:
var postData = "data=" + encodeURCIComponent($buttonWrapper.html());
Than in PHP:
echo $_POST["data"];
Than parse it or something....
Couple of things to try,
Try to pass the data directly in to the data object first. If it
works then you can debug and see why it's not ready your hidden div.
instead of $buttonWrapper.html try $buttonWrapper.text();
function SocialButtons() {
var $buttonWrapper = jQuery('.WrapperDiv');
if ($buttonWrapper.length){
var postData = $buttonWrapper.**text**();
jQuery.ajax({
type: 'POST',
url: 'http://www.wordpress-site.com/wp-contents/themes/theme-name/post.php',
data: **{'id':1}**,
cache: false,
success: function(data) {
console.log(data);
},
contentType: "application/json",
dataType: 'json'
});
}
}
Inside your jQuery ajax call, your data is not set to $_POST variable names. Hence why nothing is showing
Try changing your function to this:
function SocialButtons() {
var buttonWrapper = jQuery('.WrapperDiv');
if (buttonWrapper.length){
var postData = buttonWrapper.html();
jQuery.ajax({
type: 'POST',
url: 'http://www.wordpress-site.com/wp-contents/themes/theme-name/post.php',
data: {postData: postData},
cache: false,
success: function(data) {
console.log(data);
},
contentType: "application/json",
dataType: 'json'
});
}
}
Then you should have a $_POST['postData'] variable on your print_r or var_dump of $_POST.
Its working after I removed
contentType: "application/json",
dataType: 'json'
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);