I am using ajax to post data to a php script for work to be done... Basically, I'm taking all the form variabes, and creating json... Then taking this json and sending it to the controller script:
function createJSON() {
jsonObj = [];
$("input[class=form-control]").each(function() {
var id = $(this).attr("id");
var value = $(this).val();
item = {}
item [id] = value;
jsonObj.push(item);
});
jsonData = JSON.stringify(jsonObj);
var request = $.ajax({
url: "../../../../ajax/signupController.php",
type: "POST",
data: jsonData,
dataType: "html"
});
request.done(function( msg ) {
console.log(msg);
});
request.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
}
My code gets to the php script fine, and when I use "print_r" in php to print the output, I get this:
Array
(
[0] => stdClass Object
(
[mail-firstname] => FName
)
[1] => stdClass Object
(
[mail-lastname] => Lname
)
)
My problem is, I can't GET AT the elements... I have tried:
$data = json_decode(file_get_contents('php://input'));
foreach ($data as $key => $value) {
print "<p>$key | $value</p>";
}
but I can't get at the array elements... I get an error... What am I missing about accessing the array after decoding the file contents?
Thanks.
Update:
Modified foreach:
foreach($data as $key=>$value){
print $value->ccyear;//now I can get at individual elements
}
BUT ANY VALUE THAT HAS A DASH IS CAUSING THE SCRIPT TO FAIL... For example, if the name is "mail-firstname" PHP thinks it's mail AND firstname...
The problem is that your values are nested an extra level in your data. And they each have different keys, so it's hard to get at them. It would be better if you use the id as the keys of the top-level array, rather than nesting them:
jsonObj = {};
$("input[class=form-control]").each(function() {
var id = this.id
var value = this.value;
jsonObj[id] = value;
});
Then you should change your PHP to use the second argument to json_decode(), so you get an associative array instead of a stdClass object:
$data = json_decode(file_get_contents('php://input', true));
I'm not really sure why you need to send JSON. Why not just use:
data: jsonObj;
Then you can access the inputs as $_POST['mail-firstname'], etc.
Related
I am making post request with ajax and sending data with json format.Then I am fetching json with php and decode it into an array.When I print out whole array there is no problem. I can see the key value pairs.But when I try to print out this array's one of index value it returns null.What could be the problem?Here is my ajax request
$(function() {
$("#del").click(function() {
var file_id = 32
var file_update = 1321321
var obj = {
file_id: file_id,
file_update: file_update
};
$.ajax({
type: "post",
url: "config/ajax.php",
data: {
"file_update": JSON.stringify(obj)
},
success: function(response) {
alert(response);
}
})
})
})
Here is my php code
if (isset($_POST["file_update"])) {
$file_update = json_decode($_POST["file_update"], true);
$x = $file_update[0];
var_dump($x);
var_dump($file_update);
}
The $file_update array is associative, therefore it doesn't have integer keys, its keys are strings.
$file_update[0] does not exist and this statement should throw an error given you have proper error reporting configured.
If you want to access specific array values use:
$file_update['file_id'];
$file_update['file_update'];
If you want to access the first element of an associative array you can use the following:
$key = array_keys($file_update)[0];
$value = $file_update[$key];
I have this jQuery code that adds to an array inside an $each loop:
new_edit = {};
new_edit['file_id'] = $file_id;
new_edit['file_realname'] = $new_file_realname;
new_edit['file_folder'] = $new_file_folder;
new_file_edits.push(JSON.stringify(new_edit));
jQuery new_file_edits array output
{"file_id":"1857","file_realname":"dddd[1].mp4","file_folder":"/"},
{"file_id":"1856","file_realname":"aaaa[1].jpg","file_folder":"/"},
{"file_id":"1855","file_realname":"ssss[1].jpg","file_folder":"/"}
and im trying to post it to call.php like this:
$.ajax({
type: "POST",
url: "/call.php",
data: "edit_files="+ arrayVarHere,
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
success: function(msg){
alert(+msg);
}
});
In the PHP file call.php i have this code:
if(isset($_POST['edit_files'])){
$edit_array = $_POST['edit_files'];
$file_array = array();
foreach($edit_array as $key => $value){
$file_array[$key] = $value;
}
print_r($file_array);
die();
}
but i get this error and i cant figure out how to fix it, been googling it for a while now...
error:
Warning: Invalid argument supplied for foreach() in /home2/dddd/public_html/call.php on line 237
Line 237: foreach($edit_array as $key => $value){
Any help is much appreciated!
-Morten
EDIT 1:
I changed $edit_array = $_POST['edit_files']; to $edit_array = array($_POST['edit_files']);
And now it outputs:
{"file_id":"1857","file_realname":"dddd[1].mp4","file_folder":"/"},
{"file_id":"1856","file_realname":"aaaa[1].jpg","file_folder":"/"},
{"file_id":"1855","file_realname":"ssss[1].jpg","file_folder":"/"}
How do i go from here with the foreach($edit_array as $key => $value){ part?
Edit 2:
i build my arrayVarHere like this:
$.each( $selected_files_array, function( index, value ){
//i get $file_id, $new_file_realname and $new_file_folder with some code here
new_edit = {};
new_edit['file_id'] = $file_id;
new_edit['file_realname'] = $new_file_realname;
new_edit['file_folder'] = $new_file_folder;
arrayVarHere.push(JSON.stringify(new_edit));
});
change your code like this:
data: "edit_files="+ arrayVarHere,
call json data by json_decode in call.php
if(isset($_POST['edit_files'])){
$edit_array = json_decode($_POST['edit_files'],true); //return array
$file_array = array();
foreach($edit_array as $key => $value){
$file_array[$key] = $value;
}
print_r($file_array);
die();
}
in your ajax alert should be
success: function(msg){
alert(msg); //remove plus sign ,this can output `NaN`
}
check edit_array is array print_r($edit_array);
check contentType is used form data then correct otherwise used json type
if form data then check data: edit_files[]: arrayVarHere,
It returns this array
Array ( [0] => [{"file_id":"1857","file_realname":"aq53pop_460sv[1].mp4","file_folder":"/"},{"file_id":"1859","file_realname":"aKqbD8Q_460sv[1].mp4","file_folder":"/"},{"file_id":"1856","file_realname":"aDopymK_700b[1].jpg","file_folder":"/"}] )
how can i loop the array and access file_id value etc?
The way you are passing Data to PHP may not be that ideal. Here is what might get you started:
PHP: call.php
<?php
$data0 = isset($_POST['data_0']) ? json_decode($_POST['data_0'], true) : null;
$data1 = isset($_POST['data_1']) ? json_decode($_POST['data_1'], true) : null;
$data2 = isset($_POST['data_2']) ? json_decode($_POST['data_2'], true) : null;
$arrData = array(
'data0' => $data0,
'data1' => $data1,
'data2' => $data2,
);
foreach($arrData as $dataKey=>$dataObject){
$tempFileID = $dataObject->file_id;
$tempFileName = $dataObject->file_realname;
$tempFileFolder = $dataObject->file_folder;
// DO SOMETHING WITH THESE DATA AND THEN BUILD UP A RESPONSE FOR AJAX + SEND IT...
// UNCOMMENT TO SEE THE DATA IN YOUR NETWORKS CONSOLE BUT
// IF YOU DO THIS (SINCE YOU EXPECT JSON RESPONSE) YOUR AJAX WILL RESPOND WITH AN ERROR...
// var_dump($dataObject);
}
// RESPOND WITH THE SAME DATA YOU RECEIVED FROM AJAX: JUST FOR TESTING PURPOSES...
die( json_encode($arrData));
?>
JAVASCRIPT: BUILDING THE DATA FOR PHP
<script type="text/javascript">
var dataForPHP = {};
var iCount = 0;
$.each( $selected_files_array, function( index, value ){
var keyName = "data_" + iCount;
new_edit = {};
new_edit['file_id'] = $file_id;
new_edit['file_realname'] = $new_file_realname;
new_edit['file_folder'] = $new_file_folder;
dataForPHP[keyName] = new_edit;
iCount++;
});
</script>
JAVASCRIPT: AJAX REQUEST
<script type="text/javascript">
$.ajax({
type : "POST",
url : "/call.php",
datatype : "JSON",
data : dataForPHP,
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
success: function(msg){
if(msg){
alert("Ajax Succeeded");
console.log(msg);
}
}
});
</script>
Im currently trying to do the follow:
Request a PHP file from my image.js code
In the request call - query out data from my mysql database and save
it in a PHP array
Return the array to image.js as a JSON object.
I got nr 1 + nr 3 covered - what im strugling with is how to save my database attributes correctly into the PHP array and afterwards iterate through each record from the json callback.
Database attribute example:
player_id (unique key) || player_name || player_country || player_image || player_league ||
Question/Challenge 1: Saving the Array (this is what im not sure of)
while ($row = mysql_fetch_assoc($res))
{
$myCallbackArray[] = array($row['player_id'], $row['player_name'], $row['player_country'], $row['player_image']);
}
- The following array, will just be one "flat-array" with no dimension based on saving all corresponding attributes under seperate player_id's?
To give some some context - and assuming the array is fine, we then in a 'next-step' send it back to JS
$callback = $myCallbackArray;
echo json_encode(array('returned_val' => $callback));
Question/Challenge 2: Accessing the array values in JS (this is what im not sure of)
//Save the data
var url = "request.php"; //
var request = $.ajax({
type: "POST",
url: url,
dataType: 'json',
data: { user_id: id},
success: function(data)
{
//HERE WE HANDLE THE RETURNED ARRAY
if(data.returned_val) {
for( var i = 0; i < data.returned_val.length; i++ ){
//HERE I WOULD LIKE TO MAKE THE DIFFERENT ATTRIBUTES ACCESSABLE
}
},
error:function() {
//FAILURE
}
});
return false;
-So in this part im not sure how to actually handle the multi-dimensional array from PHP. I assume we need to save it out in a Javascript array and then we can probably iterate / access each value through an foreach loop - but yet again,- how im not entirely sure?
I'll suggest to use json_encode:
$myCallbackArray []= (object) array(
"player_id" => '...',
"player_name" => '...',
"player_country" => '...',
"player_image" => '...',
"player_league" => '...'
);
$json = json_encode($myCallbackArray);
$json is actually the following:
[{"player_id":"...","player_name":"...","player_country":"...","player_image":"...","player_league":"..."}]
which is valid JSON and you could easily use it in javascript.
I think your accessing the data wrong in your success function, the data comes back as an array. Here is an example:
var request = $.ajax({
type: "POST",
url: url,
dataType: 'json',
data: {user_id: id},
success: function(data){
var myval = data["returned_val"];
alert(myval);
},
error:function() {
//FAILURE
}
});
I am finding difficulty in accessing elements in an array from php file. The array is passed through an ajax call. Please find below the ajax call.
var data = ['test1', 'test2', 'test3'];
$(document).ready(function () {
$("button").click(function () {
$.ajax({
type: "POST",
url: "getResult.php",
data: {
testData: data
},
success: function (data, status) {
alert("Data: " + data + "\nStatus: " + status);
}
});
return false;
});
});
The server side [PHP] code is
$myArray = $_POST["testData"];
echo $myArray;
However $myArray always returns last element[test3 here] in the array. How do I access first [here test1] and other elements?
Pls help.
What you need to do is convert the JavaScript array to JSON and then send over that JSON.
On the PHP side you should decode the JSON back into an array. Finally, you should re-encode the array as JSON before sending it back.
On your client side change one line:
data: {testData : JSON.stringify(data)},
On your server side do:
$myArray = json_decode($_POST["testData"]);
header('Content-Type: application/json');
echo json_encode(array('pheeds' => $pheeds, 'res' => $res));
JS:
JSON.stringify(data)
PHP:
$myArray = json_decode($_POST['data']);
For simple structures you can use jQuery Param
data : $.param({testData:data})
With this you should be able to access your data with
echo $_POST["testData"][0]...[2];
Try this when passing JS vars by ajax.
use Firebug to see on the console what is being poted to the PHP file, this will save you a lot of trouble.
you will see that array is an OBJECT , So you want to send this array as a JSON / STRING to the PHP file.
use :
var data = ['test1','test2','test3'];
data = JSON.stringfy(data);
at the PHP:
$data = var_post('test_data');
$data=json_decode($data);
$print_r($data);
I have a problem with "JSON, JQuery, Ajax, JavaScript and PHP".
I have code to save data. This code send data(JSON) via JQuery Ajax to proses.php. The code for save data shown below :
$("#save").click(function(){
var id_promotion_code = $("#id_promotion_code").val();
var i=0;
var y=0;
var datarule = {
rule: []
};
$('#tablerule tr').each(function() {
if(y!=0)
{
var id_pricing_rule = $(this).find("td").eq(0).html();
var date_book_start = $(this).find("td").eq(3).html();
var date_book_end = $(this).find("td").eq(4).html();
var date_book_no_end = 0;
if(date_book_end=="NO END")
{
date_book_no_end = 1;
date_book_end = $(this).find("td").eq(3).html();
}
var date_reservation_start = $(this).find("td").eq(5).html();
var date_reservation_end = $(this).find("td").eq(6).html();
var date_reservation_no_end = 0;
if(date_reservation_end=="NO END")
{
date_reservation_no_end = 1;
date_reservation_end = $(this).find("td").eq(5).html();
}
datarule.rule.push({
"id_promotion_code" : id_promotion_code,
"id_pricing_rule" : id_pricing_rule,
"date_book_start" : date_book_start,
"date_book_end" : date_book_end,
"date_book_no_end" : date_book_no_end,
"date_reservation_start" : date_reservation_start,
"date_reservation_end" : date_reservation_end,
"date_reservation_no_end" : date_reservation_no_end
});
i++;
}
y++;
});
$.ajax({
type:"POST",
url:"proses.php",
data:"aksi=tambahrule&datarule=" + datarule,
success: function(data){
alert("Sukses " + data);
},
error: function(){
alert("Error" + data);
}
});
});
And the code in proses.php shown below :
if($aksi=='tambahrule'){
$datarule = $_POST['datarule'];
$jsone = json_decode($datarule, true);
print_r($jsone);
}
But i can't get the json data with proses.php code. Please help me how to read json object that send via jquery ajax with php? Actually i want to looping the json for get the data.
------------------------MY NEW EDIT-----------------------------
Thanks for your response...
I already modify my code. And running but not well yet.
This is the response when i check using Firebug :
Array
(
[rule] => Array
(
[0] => Array
(
[id_promotion_code] =>
[id_pricing_rule] => BN2
[date_book_start] => 2012-03-01
[date_book_end] => 2012-03-01
[date_book_no_end] => 1
[date_reservation_start] => 2012-03-09
[date_reservation_end] => 2012-03-09
[date_reservation_no_end] => 1
)
[1] => Array
(
[id_promotion_code] =>
[id_pricing_rule] => EB10%
[date_book_start] => 2012-03-15
[date_book_end] => 2012-03-15
[date_book_no_end] => 1
[date_reservation_start] => 2012-03-31
[date_reservation_end] => 2012-03-31
[date_reservation_no_end] => 1
)
)
)
And this is the PHP code for get the data :
$datarule = $_POST;
$rulenya="";
foreach($datarule->rule as $doc)
{
$rulenya=$rulenya.$doc->id_pricing_rule;
}
print_r($datarule);
But get the error. My question is?
1. The data is in Array, should i change to Object? And how?
2. How can i get that data in PHP?
I think you should send the data in another way:
data: { aksi: "tambahrule", datarule: datarule},
as datarule is a complex object and can't be appended to a querystring. Serverside your code should be ok
Try using dataType: 'json', in your ajax call.
The answer of Nicola Peluchetti is correct, datarule is NOT a querystring, you need to send it as he explained.
Furthermore, having your data as an array is fine. But you need to alter your server code to handle it as such:
$datarule = $_POST['datarule'];
$rulenya = '';
foreach ($datarule['rule'] as $doc) {
$rulenya .= $doc['id_pricing_rule'];
}
or something along those lines...
You don't json_decode. You can try it;
PHP Code:
$datarule = $_POST['datarule'];
$datarule = implode(',', $datarule);
print_r($datarule);
$datarule is a array