Jquery Post method and JSON issue - javascript

I'm using jquery and jason sending data to another contoller, but when I send the data, I check it in fire bug and it's fine, It sends it correctly but in the target page, when I var_dump the $_REQUEST or $_POST is returns null.
I'm using codeigniter by the way.
This my jquery code:
<script type="text/javascript">
function GetMovieLanguageCategory(Language)
{
$.ajax({
type: "POST",
contentType: "application/json",
url: "/admin/movie/get_language_category",
data: JSON.stringify({"Language":Language}),
success: function(Data)
{
alert(Data);
},
failure: function(ErrorMsg) {
alert(ErrorMsg);
},
});
}
</script>
And in my Controller:
var_dump($_REQUEST);
//var_dump(json_decode($_POST['Language']));
And it returns:
array(0) {}
Am I wrong somewhere?

You are sending JSON data, but marking it as application/x-www-form-urlencoded data and you are trying to parse it as application/x-www-form-urlencoded data.
Change:
data: JSON.stringify({"Language":Language}),
to
data:{"Language":Language},
and let jQuery encode it properly for you.
If you want to encode it yourself (don't!):
data: "Language=" + encodeURIComponent(Language);
If you really want to send JSON:
contentType: "application/json",
data: JSON.stringify({"Language":Language}),
then, in the PHP, get the body of the request and run it through json_decode.

Related

PHP $_POST empty during AJAX post request

Goal: Serialize data, send them in HTTP POST request using AJAX, proceed data in PHP (and answer)
Problem: PHP $_POST variable seems to be empty
JS/AJAX
var postData = [cmd, data];
alert(postData = JSON.stringify(postData));
$.ajax({
url: "./backendTag.php",
type: "post",
data: postData,
dataType: 'json',
success: function (response) {
alert(response); // Empty
//logToServerConsole(JSON.parse(response));
},
error: function(jqXHR, textStatus, errorThrown) {
logToServerConsole("E3"); // Communication Error
console.log(textStatus, errorThrown);
}
});
PHP
<?php echo json_encode($_POST);
The reason for the same is probably because you are not posting properly in javascript. Before i add the codes, let me add a couple of tips on how to debug in these situations.
First is, you check if the request is properly formed. Inspect the network in browser dev tools.
Second method could be to use var_dump on $_POST to list out all the post parameters and check if they have been recieved in PHP
Now as far as the code goes
here is the javascript
$.ajax({
method: "POST",
url: "url.php",
data: { name: "John Doe", age: "19" }
}).done(function( msg ) {
alert(msg);
});
and in php you can simply check using
<?php
print $_POST["name"];
?>
which would work perfectly. Notice how the data in javascript is a list, while from what you wrote seems to be json string
Apparently we can't pass an array directly after serializing him. The following code resolved the problem. (Split array)
data = JSON.stringify(data);
var JSONdata = {"cmd" : cmd, "data" : data};
$.ajax({
url: "./backendTag.php",
type: "post",
data: JSONata,
dataType: 'json',
/* Handlers hidden*/
});
JSON content won't be parsed to the $_POST globals. If you want to reach them, try to get from php://input with:
file_get_contents('php://input')
And I suggest giving the content-type during the ajax request:
contentType: 'application/json',
If it's not working, try to set the data as a string, with JSON.Stringify, like the following:
data: JSON.stringify(postData)

Can't send JSON as string via AJAX

So I'm trying to send a JSON as a string.
Then I have a PHP back-end that retrieves this JSON string and parses it using json_decode.
Unfortunately, I can't get to send this JSON as a string.
Here's the jQuery Ajax script I used:
var jsonString = JSON.stringify(checkables);
console.log(jsonString);
$.ajax({
url: $url,
type: 'POST',
data: {ajaxidate: JSON.stringify(jsonString)},
contentType: "application/json; charset=UTF-8",
success: function (data)
{
// just successful callback
},
error: function ()
{
// just error callback
}
});
Variable checkables contains raw form as JSON data:
After applying JSON.stringify(), this is now how it looks:
[{"name":"name","type":"multialphanumslug","value":"AD"},{"name":"server","type":"host","value":"10.1.1.1"},{"name":"port","type":"number","value":"8080"},{"name":"authid","type":"username","value":"barryallen"}]
At the back-end, I have this PHP script:
<?php
var_dump($_POST);
die();
?>
Now I suppose $_POST at back-end should now contain this:
array(
'ajaxidate' => "[{\"name\":\"name\",\"type\":\"multialphanumslug\",\"value\":\"AD\"},{\"name\":\"server\",\"type\":\"host\",\"value\":\"10.1.1.1\"},{\"name\":\"port\",\"type\":\"number\",\"value\":\"8080\"},{\"name\":\"authid\",\"type\":\"username\",\"value\":\"barryallen\"}]"
);
But it didn't receive anything. Here's the captured request:
The response from back-end?
I tried with POSTMan and I received an expected correct output:
Now that was ridiculous.
I'm stuck at this for 2 days trying to figure out what's going on or what did I miss. Any help will be greatly appreciated.
You need to parse the data on the server:
$myArray = json_decode($_POST['ajaxidate']);
var_dump($myArray);
Consider this:
<?php
$a = '[{"a": 1}]';
$b = json_decode($a);
var_dump($a);
var_dump($b);
?>
Output:
string(10) "[{"a": 1}]"
array(1) {
[0]=>
object(stdClass)#1 (1) {
["a"]=>
int(1)
}
}
dataType: 'json', tldr: Use It!
When setting dataType = json you tell jQuery that the response from the server should be interpreted as JSON and it will therefore parse it for you and give the parsed object / array as first argument to the success callback:
$.ajax({
// ...
dataType: 'json',
success: function(myJson) {
console.log(myJson); // this will be a JSON object/array...
}
});
As you mention dataType: json in your ajax call data need to be in json formate but using JSON.stringify convert Json object to json String that with make problem for you need to change
`var jsonString = JSON.stringify(checkables);`
to
var jsonString = checkables;
JSON.stringify()
Solved my own problem. Having #Munna suggested to use $.post() made me figure out to eliminate the unnecessary. From that case, the unnecessary is contentType option from $.ajax().
This is the updated working solution:
$.ajax({
url: $url,
type: 'POST',
data: {ajaxidate: JSON.stringify(jsonString)},
success: function (data)
{
// just successful callback
},
error: function ()
{
// just error callback
}
});
Thanks everyone who helped. Have a good day

pareser error while sending data as json to php script using jquery ajax

I'm sending some data to my sever at localhost using jquery's $.ajax.
The data is JSON object.
as follows:
javascript
var jso={
"data": {
"Game_name": "Road Rash",
"cheat": "xyzzyspoon!",
"effects": [
{
"nitro": true
},
{
"chain": false
}
]
}
};
function sendData(){
var queryString=JSON.stringify(jso);
$.ajax({
type: "POST",
url: "/gamers_cheats.php",
contentType: "application/json; charset=utf-8",
traditional: true,
dataType: 'json',
data: queryString,
success: function(data){
console.log(data);
},
error: function(data,textStatus,jqXHR){
alert("Unknown Error occured :- \n "+textStatus+"\n error");
console.log("Unknown Error occured :- \n "+textStatus+"\n error");
}
});
}
sendData();
and handling data in my php file as:
gamers_cheats.php:
<?php
var_dump($_POST);
echo"\n Count:- ".count($_POST);
// This is Just a demo file
?>
But the problem is $.ajax alerts the error: part with textStatus as parsererror. Also same is happening even if I didn't use JSON.stringify.
and if The lines:
contentType: "application/json; charset=utf-8",
traditional: true,
dataType: 'json',
were removed then the request is sent to the sever but that isn't a valid request as it adds extra slashes (\) to every (") in JSON object.
like:
\"data\": {
\"Game_name\": \"Road Rash\",
\"cheat\": \"xyzzyspoon!\",
\"effects\": [
{
\"nitro\": true
},
{
\"chain\": false
}
]
}
So that gives error while processing it on server side. Is there any way to properly send POST JSON data using jquery ajax and to properly handle it on server?
and one more question, can i add extra $_POST parameters which are not in JSON format to my queryString as data: queryString +"&&navigator="+navigator.userAgent+"" ? but that also ain't working (This is not important though, Just curious about it).
FYI I'm running IIS 7 server with php 5.2 and JQuery version 1.7.2 with JSON2.js .
Hope experts here will help me.
Removing the line 'var queryString=JSON.stringify(jso);' and passing object jso as data may help. Try once.

How to transfer json string to another page using jquery's ajax method?

I have a JSON string (stringified array of objects in javascript) which i intend to post to another page and then retrieve it from the $_POST variable. I used json =JSON.stringify(array).
The result gave me the following string
json = [{"keycodec":68,"eventc":"keydown","timec":1392849542994}
{"keycodec":65,"eventc":"keydown","timec":1392849543063},
{"keycodec":87,"eventc":"keydown","timec":1392849543084}]
Now I use
$( "#other").click(function() {
$.ajax({
url: 'some.php',
type: 'POST',
data: { kite : json}
});
On the page some.php I use
$kite=json_decode($_POST['kite'],true);
print_r($kite)
But nothing shows up. I have read many links on this topic and tried adding ContentType,dataType,processData parameters to the $.ajax() function but nothing helped.
What about this:
$( "#other").click(function() {
var json = [{"keycodec":68,"eventc":"keydown","timec":1392849542994}
,{"keycodec":65,"eventc":"keydown","timec":1392849543063},
{"keycodec":87,"eventc":"keydown","timec":1392849543084}];
$.ajax({
url: 'test.php',
type: 'POST',
data: "kite=" + JSON.stringify({ kite : json }),
success: function(msg){
alert(msg);
},
failure: function(errMsg) {
alert(errMsg);
}
});
});
And on your php code:
<?php
$obj=json_decode($_POST['kite']);
print_r($obj->{'kite'});
?>
Not in an elegant way on passing the json..
but this way you can still capture "kite" as post variable and decode your desired json string.

jquery not properly serializing json in ajax call

Let me start by saying I am not extremely familiar with Javascript and I cannot figure out what is going on here.
I have the following function:
self.search = function () {
var searchTerms = {
"City": this.cityName,
"State": this.stateName,
"StoreNumber": this.storeNumber,
};
$.ajax("/api/SearchApi", {
data: searchTerms,
type: "POST", contentType: "application/json",
success: function (result) {
alert(result);
}
}
});
When I submit, what happens is that instead of submitting a nice JSON object as expected, it submits a JSON objected formatted as so: "City=testing&State=AL&StoreNumber=test "
Ideally I would like to use a GET method that passes the object to my server so that I can return the results, but when I use a get method, it simply appends the above to the API call url resulting in a URL request formed as so: http://localhost:57175/api/SearchApi?City=testing&State=AL&StoreNumber=test
Any help would be appreciated.
Make sure you add the dataType of JSON to your $.ajax({ }); object. That should solve the problem!
$.ajax({
// ...
data : JSON.stringify( searchTerms ), // Encode it properly like so
dataType : "json",
// ...
});
2 Things
Add the json content type(not the data type) to your ajax object important to note is the charset your server is using in this case utf-8.
Use the Json2 Library to stringify and parse Json when sending and retrieving it can be found here : https://github.com/douglascrockford/JSON-js/blob/master/json2.js
$.ajax({
url: URL,
type: "POST",
//Stringify the data you send to make shure its properly encoded
data: JSON.stringify(DATA),
//This is the type for the data that gets sent
contentType: 'application/json; charset=utf-8',
//This is for the data you receive
dataType: "json"
}).done(function(data) {
var dataYouGet = JSON.parse(data);
}).fail(function(xhr, ajaxOptions, thrownError) {
}).always(function(data) {
});

Categories