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
Related
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>
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.
Hi in my view I am creating a two dimentional array in javascript and passting it to the update controller as follows :
Array in Javascript
item[0][0] = null;
item[0][1] = 1;
item[1][0] = 2;
item[1][0] = 3;
alert (item); will show ,1,2,3
Passing it to Zend controller as :
$.ajax({
type: "POST",
url: "admin/navigation/update",
data: item,
success: function(data) {
alert(data);
},
error: function() {
alert("failure");
}
});
return false;
}
How can I receive this from update controller and assign to it a php array as
public function updateAction() {
$data = $this->_request->getPost();
//Code should come here
array(
item1(
array(
value1 = item[0][0] //From javascript array
value2 = item[0][1]
)
)
item2(
array(
value1 = item[1][0]
value2 = item[1][0]
)
)
)
}
I'm a n00b in Zend and any help would be much appriciated :)
Instead of the below code:
$data = $this->_request->getPost();
Use the following code:
$data = $this->_request->getParams();
print_r($data);
This will give you the array as you are sending from javascript.
In your javascript file declare your array:
var item = [[1,2],[3,4]];
Then in your ajax call you should modify the data sent to be JSON. Replace the line
data: item
with
data: {data: JSON.stringify(item)}
Then, in your controller you can decode the data send to get your array:
$data = json_decode($this->getRequest()->getPost("data"));
and you have your array.
I created a php script that generates the json response
this is the example of the output:
[[],{"idgps_unit":"2","lat":"40","lon":"40","name":"ML350","notes":"Andrew","dt":"2012-10-29 19:43:09","serial":"3602152","speed":"44","odometer":"208.49"},{"idgps_unit":"1","lat":"42","lon":"39","name":"unit1","notes":"fake unit 1","dt":"2012-10-18 18:16:37","serial":"12345","speed":"0","odometer":"0.16"}]
This is how I form the response in PHP:
$data[] = array();
foreach ($list->arrayList as $key => $value) {
$unit = new Unit();
$unit = $value;
//create array for json output
$data[] = array('idgps_unit' => $unit->idgps_unit, 'lat' => $unit->lat,
'lon' => $unit->lon, 'name' => $unit->name, 'notes' => $unit->notes,
'dt' => $unit->dt, 'serial' => $unit->serial, 'speed' => $unit->speed,
'odometer' => $unit->odometer);
}
echo json_encode($data);
Now, in JS I did this:
function getCheckedUnits() {
jQuery(function($) {
$.ajax( {
url : "json.php?action=get",
type : "GET",
success : function(data) {
var jsonData = JSON.parse(data);
///PARSE VALUES AND SUBMIT TO A FUNCTION :: START
var C_longitude = 0;
var C_name = 0;
var C_idgps_unit = 0;
var C_serial = 0;
var C_speed= 0;
var C_notes= 0;
var C_dt = 0;
var C_time = 0;
var C_odometer = 0;
initialize(C_longitude,C_name,C_idgps_unit, C_serial,C_speed, C_notes, C_dt, C_time, C_odometer);
///PARSE VALUES AND SUBMIT TO A FUNCTION :: END
}
});
});
}
I need to parse the json reponce into values
Assuming that JSON.parse(data) only gets the associative array in the JSON response, you should be able to get the values in the JSON data like so:
var i = 1;
var C_longitude = jsonData[i]["lon"];
var C_name = jsonData[i]["name"];
Assuming that the first empty array is not removed by JSON.parse(), i = 1 would get the first batch of data and i = 2 would get the second.
The parsed JSON behaves the same way as if it was defined in JavaScript
If you put dataType: "json" in the ajax settings it will return you a json object than you don't need to parse it again. So this would look like:
function getCheckedUnits() {
jQuery(function($) {
$.ajax( {
url : "json.php?action=get",
type : "GET",
dataType: "json"
success : function(data) {
}
});
});
}
However you could also use your own option but than just use the parseJSON function so var jsonData = jQuery.parseJSON(data);
I am returning array as
$array = array {
'id' => 1,
'name'=>krishna,
}
echo json_encode($array);
exit;
from an ajax call
How can I convert this json value to java script array?
This is my actual data
var data = [{
"candidate_notes_id":"1",
"candidate_id":"38",
"subject":"test",
"description":"t‌estestsete\netestes\n\n\nsteetet",
"private":"0",
"created_date":"2012-09-14 11:55:13",
"updated_date":"2012-09-14 11:55:13",
"updated_by":"admin"
}]
var newArray = jQuery.parseJSON(data);
alert(newArray);
return false;
result :
var newArray = JSON.stringify(data);
var date_split = newArray.substr(1,newArray.length-2);
var newData = date_split.replace('\n','<br>');
var newArray = $.parseJSON(newData);
alert(newArray.candidate_notes_id);
alert(newArray.candidate_id);
alert(newArray.subject);
alert(newArray.description);
If you are using jQuery then you can use jQuery.parseJSON(YOUR_AJAX_RESPONSE_DATA); which will convert json to JS object
Link: http://api.jquery.com/jQuery.parseJSON/
Please look at an answered question ...
You will find how to convert a json to an array.
JSON to javaScript array
var array = [];
$.each(JSONObject, function(i, obj) {
array.push([obj.id.value, obj.name.value]);
});
You can parse it using
obj = JSON.parse(responseData); // replace `responseData` with your XHR response variable name
in your success callback function. Then convert it an array as follows
var myArray=[];
myArray[0]=obj.id;
myArray[1]=obj.name;
but first of all your
$array = array {
'id' => 1,
'name'=>krishna,
};
should be
$array = array (
'id' => 1,
'name'=>'krishna'
);
DEMO.