ajax post method not getting data in PHP page - php

I am trying to get some data sent to a PHP page to update PHP Session variables. I have tried several different examples that I found here but just can't seem to get any to work. The data is never received on the PHP page.
Here is my Javascript/jQuery:
var str, ProductID, sessionValues= [];
ProductID = "1";
str = {"ProductID": ProductID, "State": "UNCHECKED"};
sessionValues.push(str);
ProductID = "2";
str = {"ProductID": ProductID, "State": "CHECKED"};
sessionValues.push(str);
var postObj = {"sessionData": sessionValues};
console.log(postObj);
$.ajax({
type: 'POST',
contentType : 'application/json',
data: {'data': JSON.stringify(postObj)},
url: 'setSession.php'
}).done(function(response){
console.log(response);
}).fail(function(jqXHR, textStatus, errorThrown){
alert('FAILED! ERROR: ' + errorThrown);
});
This is what my data object looks like:
Then on the PHP side all I get is an error that I supplied an invalid argument to foreach. No matter how many times I repeat the sessionValues.push(str) my browser always reports 528 bytes sent.
<?php
$data = json_decode($_POST['data']);
print_r($data);
foreach ($data->sessionData as $key => $value) {
echo "$key => $value";
}
?>

You need to remove contentType : 'application/json', because that is not what you are sending.
When you do send as application/json properly ... stringifying the whole object , not just parts of it, then $_POST will be empty and you have to access the data using json_decode(file_get_contents('php://input'))
There is also no need to stringify your other object...jQuery will form encode it for you and you can access it as array
Try
JS
$.ajax({
type: 'POST',
data: {'data': postObj},
url: 'setSession.php'
}).done(function(response){
PHP
<?php
$data = $_POST['data'];
foreach ($data['sessionData'] as $key => $value) {
echo "$key => $value";
}
?>

Since some browsers caches the ajax requests, it doesn't responds as expected. So explicitly disabling the cache for the particular ajax request helped to make it work. Try to modify charlietfl's request as below:
$.ajax({
type: 'POST',
data: {'data': postValue},
cache: false,
url: 'postAjaxHandling.php'
}).done(function(response){
});

Related

Ajax / PHP : pass variables

When I'm passing the two variables to my php I get Notice: Undefined index : name & Notice: Undefined index : parsed.
When I'm adding an echo for each variable, I get nothing.
Nothing is added in my database.
name = "myName";
parsed = someCode.toJSON();
parsed = JSON.stringify(parsed, null, '\t');
parsed = parsed.replace(/[\n\t]+([\d\.e\-\[\]]+)/g, '$1');
$.ajax({
url: 'js/function/scriptSave.php',
type: 'POST',
dataType: 'JSON',
data: {name : name, parsed : parsed},
success: function(result) {
alert("Success");
},
error: function(err){
alert('Error'+err);
}
});
The Ajax always returns me the error case : Error [object Object]
When I'm replacing my variables with text, everything works:
data: {name : 'name', parsed : 'parsed'}
And when I remove the json variable only it works.
I really don't understand what happens here..
[EDIT]
The variable containing the name is ok. But when I only put the variable containing the json, it doesn't work. But what is the problem with this variable ?
So far, I have tried:
var obj = {}; obj.name = 'myName'; obj.parsed = someCode.toJSON();
{data : JSON.stringify(obj)}
///////
{'name' : name, 'parsed' : parsed}
///////
{parsed : JSON.stringify(parsed)}
Here's my php:
<?php
if (!#mysql_connect('localhost', 'user', 'pwd')) {
die("Error");
} else {
mysql_select_db('database');
}
$parsed = $_POST["parsed"];
$name = $_POST["name"];
mysql_query("INSERT INTO object(name, parsed) VALUES ('".$name."', '".$parsed."')");
?>
[EDIT 2]
When I'm changing dataType from JSON to TEXT the ajax is in success case, but nothing is inserted in DB...
When I'm looking in my devTools in chrome everything semm to be ok :
General
Request Method :POST
Status Code: 200 OK
Response Headers
Content-Type: text/html
Request Headers
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Form Data
name : myName
parsed : {"another" : "value"}
[EDIT 3]
The problem seems to come from the json size... When I'm excluding some fields, everything seems to work. The problem is that in my databse, my field which will contain my JSON, is a LongText... The JSON size doesn't have to be the problem..
obj should be send as string, when calling the Ajax POST method.
So, combine the data into one Object and stringify it with JSON.stringify() method.
var obj = {};
obj.name = "your name";
obj.parsed = { "another" : "value" };
$.ajax({
url: 'js/function/scriptSave.php',
type: 'POST',
dataType: 'JSON',
data: JSON.stringify(obj),
success: function(result) {
alert("Success");
},
error: function(err){
alert('Error'+err);
}
});
Just remove the JSON.stringify().

JSON Post and Decode array to PHP

I'm tring to post an array to PHP file using JSON. It does not work. The problem is nothing happens. If I decomment datatype:"json" then I get the alert (but without data).
This is my jquery code
var arr = new Array();
arr.push('1','Brussels|25');
arr.push('2','Antwerp|40');
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "jsondecode.php",
data: JSON.stringify(arr),
dataType: "json",
success: function(data){alert(data);},
failure: function(errMsg) {
alert(errMsg);
}
});
And this is my PHP code (jsondecode.php);
<?php
$array = json_decode($_POST["arr"]);
foreach($array as $el){
$el_array=explode('|',$el);
echo"City=".$el_array[0]." And Age = ".$el_array[1]."";
}
?>
Does somebody know a useful tutorial on this?
You have to post the data in this format to retrieve like $_POST["arr"]
data: { arr : JSON.stringify(arr) },
What the heck are you trying?
It looks as if you are trying to put key-value-pairs to the JavaScript-Array with arr.push('1', 'Brussels|25'); expecting an array containing "Brussels|25" under the key "1" - but watch out, you are creating this array: ["1", "Brussels|25", "2", "Antwerp|40"].
If you want to send json, send json-data:
var arr= [{
"city" : "Brussels",
"age" : 25
},{
"city" : "Antwerp",
"age" : 40
}];
then your ajax call:
$.ajax({
type: "POST",
url: "jsondecode.php",
data: {arr: JSON.stringify(arr)},
success: function(data){
console.log("success:",data);},
failure: function(errMsg) {
console.error("error:",errMsg);
}
});
So you don't need to explode the data server-sided.
The server-sided script:
<?php
$data = json_decode($_POST["arr"]);
// will echo the JSON.stringified - string:
echo $_POST["arr"];
// will echo the json_decode'd object
var_dump($data);
//traversing the whole object and accessing properties:
foreach($data as $cityObject){
echo "City: " . $cityObject->city . ", Age: " . $cityObject->age . "<br/>";
}
?>
Hope, this helps you now.
#edit: By the way, use console.log() or console.error() instead of alert. Alert will cause scripts to pause until you click on ok and you cannot see objects in an alert.
#2nd edit: the script is now tested, I removed unnecessary code and added the server-sided code
Replace :
$array = json_decode($_POST["arr"]);
By:
$array = json_decode($_POST["arr"], true);
Worked for me:
JS:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "jsondecode.php",
data: JSON.stringify({"1": "Brussels", "2": "Antwerp"}),
success: function(data){alert(data);},
failure: function(errMsg) {
alert(errMsg);
}
});
PHP:
<?php
$p = file_get_contents('php://input');
$x = json_decode($p, true);
echo $x["1"];
?>

Post value via ajax to php

I trying to post some value via ajax to php then php print send back js console.log, have problem:
build array( I'm doubt below I made is array??)
$('.eachcontainer').each(function(){
var arr = $(this).find('img').map(function(){
return $(this).attr('src');
});
console.log(arr);
// result:
// ["16.png", "17.png", "19.png", "18.png"]
// ["0.png"]
// ["0.png"]
// []
// []
$.ajax({
type: "POST", url: "update.php",
data: arr
}).done(function(msg){
console.log(msg);
});
});
php
print_r($_POST);
js come back console.log
Array
(
[undefined] =>
)
Array
(
)
Array
(
)
Array
(
[undefined] =>
)
Why this does not work? How can i fix it?
Also, I tried to change the syntax in my ajax function data: {arr: arr} but this didn't work either.
Error message:
TypeError: Type error jquery-1.10.1.min.js:6
Found error line in jquery-1.10.1.min.js:6:
t = x.isFunction(t) ? t() : null == t ? "" : t, i[i.length] = encodeURIComponent(e) + "=" + encodeURIComponent(t)
you haven't constructed proper key&value pair using your data, if you want to pass a raw stream of data then set processData: false and capture with php://input
var arr = $(this).find('img').map(function(){
return $(this).attr('src');
});
$.ajax({
type: "POST", url: "update.php",
data: arr,
processData: false,
}).done(function(msg){
console.log(msg);
});
on the php side
$data = file_get_contents("php://input");
You first need to call arr.get() to get the jquery.map result back as a regular javascript array. Then you can pass it to the ajax data paramter as:
data: { "images" : arr.get() }
So the full ajax call would look like this:
$.ajax({
type: "POST", url: "update.php",
data: { "images" : arr.get() }
}).done(function(msg){
console.log(msg);
});
You can then read the array back in php as:
$images = $_POST['images'];

Posting form data with .serialize() PHP error

I'm posting form data that includes some checkboxes and other input to a PHP script with jQuery's .serialize().
post.js:
$(function(){
$("#button").click(function(){
$.ajax({
type: "POST",
url: "post.php",
data: $("form#input").serialize(),
success: function(data){
$.getJSON('post.php', function(data) {
$.each(data, function(key, val) {
})
})
}
})
})
})
post.php:
$tags = array();
foreach($_POST['checkboxes'] as $key => $value){
$tags[] = "$value";
}
$json = array(
array(
"tags" => $tags,
),
);
echo json_encode($json);
If I point the getJSON to post.php I get a PHP warning in my error log that says "PHP Warning: Invalid argument supplied for foreach()" and this causes the data from the input form to not be properly passed (i.e. a fwrite after the foreach doesn't write anything). If I reference another file for the getJSON, say data.php, or if I don't include it at all, the post works fine. Why is this happening? I could just store the data and make a second script to return the JSON data but it would be easier to do it all in one script.
Here's the deal:
success: function(data){
In the above piece, the data you are recieving is the returned json_encoded string containing key:value pairs of $tags, as you defined.
$.getJSON('post.php', function(data) {
Now, in your getJSON request you are passing over no values, and your foreach statement expects you to post the values of checkboxes so they can be parsed, and the tags be made. I'm not really sure I understand why you would want to do this, as the success: function(data) will natively parse the JSON being returned from the server and will be ready for you.
$.each(data, function(key, val) {
If you just simply lose the $.getJSON request, and use the each function, you will be iterating over the tags that you return from the server. I believe this is the intended functionality you want.
your code is breaking when checkboxes are not posted
$tags = array();
if( array_key_exists('checkboxes', $_POST) && is_array($_POST['checkboxes']) ) {
$tags = array_values($_POST['checkboxes']);
}
$json = array(
array(
"tags" => $tags,
),
);
echo json_encode($json);
You're getting Invalid argument supplied for foreach because it expects a value in $_POST['checkboxes'] which you're not sending in your $.getJSON call.
$.getJSON sends another AJAX call, a GET request to get a JSON file. You already sent a POST request to post.php, you don't need to send another call.
Add dataType: 'json' to your 1st call, and the JSON response will be parsed for you.
$.ajax({
type: "POST",
url: "post.php",
data: $("form#input").serialize(),
dataType: 'json',
success: function (data) {
$.each(data, function (key, val) {
// code here
});
}
});
you don't have to invoke "getJSON" because you already have what you want. Everything you need is in data. So your "success" callback should look something like this:
function(data){
var jsonData = $.parseJSON(data);
$.each(jsonData, function(key, val) {
})
}

Sending JSON to server, using jQuery

I am trying to send simple data to theservre, and I need a "rough and ready" way to do this.
This is what I have so far:
var emails = ['a#123.com', 'b#123.com', 'c#123.com'];
var ruff_json = "{ 'emails': [";
for (i in emails)
ruff_json += ((i == 0) ? '' : ', ') + '\''+emails[i]+'\'';
ruff_json += '] }';
jQuery.ajax({
type: 'POST',
url: '1.php',
data: ruff_json,
dataType: "json",
timeout: 2000,
success: function(result){
//do something
},
error: function (xhr, ajaxOptions, thrownError){
//do something
}
});
Using Firebug, I can see that the data is POSTed to the server - however, at the server, there is no data ($_POST is empty) - what am I doing wrong?
We post all of our data with json.
var myobj = { this: 'that' };
$.ajax({
url: "my.php",
data: JSON.stringify(myobj),
processData: false,
dataType: "json",
success:function(a) { },
error:function() {}
});
then in php we do
<?php
$json = json_decode(file_get_contents("php://input"), true);
// Access your $json['this']
// then when you are done
header("Content-type: application/json");
print json_encode(array(
"passed" => "back"
));
?>
This way we don't even mess with the post variables, and in general, its faster than having jQuery process them.
Your data field should contain an object with key-value pairs, because it gets encoded as POST key-values pairs.
data = {my_json: encoded_string};
Then on the PHP side you can access the data as:
$data = json_decode($_POST['my_json']);
PHP populates $_POST by parsing the data received. However, it only knows form-encoded data, JSON data cannot be parsed automatically. So $_POST will be useless in this case. You need to get the raw post data and parse it with json_decode.

Categories