json data by ajax request is not been sent - php

I want to send json data to php file. when i send it as querystring it ,half of the data is sent and when i send it in the following way then nothing is sent at all
Ext.Ajax.request({
url: 'GetData.php',
params: {
data:document.getElementById("jsonData").value
},
method: "POST",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(xhr) {
console.log(xhr)
}
});
i have modified my ajax call in different ways but it always send null. I have checked that my hiddenfield 'jsonData' has data in it before making ajax request. please help
here is json data--
{"items":[{"text":"Table of Contents","items":[{"text":"Cover","source":"book/00__Cover.html","leaf":true,"items":"[]"},
{"text":"Introduction","source":"book/Introduction.html","leaf":true,"items":"[{\"text\":\"Me maps\",\"source\":\"book/Introduction.html#c000030\\\"\",\"leaf\":true},{\"text\":\"Spatial perspective\",\"source\":\"book/Introduction.html#c000031\\\"\",\"leaf\":true}]"},{"text":"Index","source":"book/Index.html","leaf":true,"items":"[]"}]},{"text":"My Study Guide","source":"studyguide.js","leaf":true},{"text":"Shared","source":"shared.js","leaf":true}]}

headers: { 'Content-Type': 'application/json' },
jsonData: {
document.getElementById("jsonData").value
},
That should work if you change those but perhaps remove
dataType: 'json',
aswell. Ive never used that and do not know if it exsists
Also you cannot set charset it sends it as utf-8 reguardless of what you do
edit also log jsondata.val like the man above me said just to make sure
edit2
Ext.Ajax.request({
url: 'GetData.php',
headers: { 'Content-Type': 'application/json' },
jsonData: {
document.getElementById("jsonData").value
},
method: "POST",
dataType: 'json',
success: function(xhr) {
console.log(xhr);
}
});
did you change your code to read like this? Also have you tried logging your failure error? if so what does it say. And you were missing a ; in your success function

I think you need to change your ajax call to this (asuming ("jsonData").value does contain a json object):
Ext.Ajax.request({
url: 'GetData.php',
jsonData: Ext.util.JSON.encode(document.getElementById("jsonData").value)
method: "POST",
success: function(xhr) {
console.log(xhr)
}
});
Read more here: http://joekuan.wordpress.com/2010/12/06/posting-json-data-from-ext-js-to-php/

Related

$.ajax $_POST to php returns empty array [duplicate]

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
});
});
}

$.ajax and method post not work correctly

I have a simple code-form like this:
$.ajax({
url: "http://myurl/test.php",
type: "POST",
dataType: "html",
data: {
action: "login"
},
success: function (data) {
console.log(data)
}
});
When on PHP server page, I try to print $_POST["action"] yet this field is blank. Why does it work fine if I use $.post(url,data,function)?
$.ajax({
url: "http://myurl/test.php",
type: "POST",
dataType: "html",
data: {
method: "login"
},
success: function (data) {
console.log(data);
}
});
login is a php function
You may use method instead of type.
$.ajax({
url: "http://myurl/test.php",
method: "POST", // <-- Use method, not type
dataType: "html",
data: {
action: "login"
},
success: function (data) {
console.log(data)
}
});
Problem is solved.....
There is a problem with the callback on success event...and yesterday I focused my attention only on the request php in the developers tool....when I used Curl (with the right request) all work correctly and I forgot to check client code in success callback....
Never use post method with developers console,it's very easy to lose more time :=)

AJAX request returning error

I have an AJAX request that is throwing an error.
It's part of a larger system that I've inherited, so I can't post the files in their entirety, but I've tried to isolate the relevant code:
$.ajax(
{
url: ajax_url, // Valid URL
data: jsonData, // Valid JSON
dataType: 'json',
contentType: 'application/json',
type: POST,
async:true,
success: function(data)
{
console.log(data);
parsedData = JSON.parse(data);
console.log(parsedData);
// Here I am trying to log successful output
},
error: function(jsonData)
{
console.log("error");
console.log(jsonData);
}
});
In the PHP, values are added to an array and returned:
$data['status']=200;
$data['new_id']=$insert_id;
return json_encode($data);
All I am logging at the moment is 'error'. Apologies again for incomplete code, I have tried to supply the code where I think the error is caused.

Post json data to PHP

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'

Jquery ajax response error

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');

Categories