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.
Related
I'm trying to send a username from the view to the controller through Ajax like this :
$('#exampleFormControlSelect1').change(function(){
var username =$('#exampleFormControlSelect1').val();
$.ajax({
type: 'POST',
dataType: "json",
url: "Panier/loadPanier",
data: {username: username},
success: function(result){
$("#tbodyid").empty();
var data1 = JSON.parse(result);
console.log(data1) ;
},
});
});
and I try to use the sent value to do some work:
public function loadPanier()
{
$res = [];
$username = $this->input->post('username');
$panier_data = $this->model_panier->getPanierData($username);
foreach ($panier_data as $k => $v) {
$idPiece = $v['idPiece'];
$qte = $v['quantity'];
$piece_data = (array)$this->model_catalogue->getDetail($idPiece);
$price = (int)$piece_data['Unit Price'];
$montant = $qte * $price;
array_push($res, array(
'idPiece' => $idPiece,
'Description' => $piece_data['Description'],
'qte' => $qte,
'prix HT' => round($piece_data['Unit Price'], 3),
'montant' => $montant
));
}
return $res;
}
In my URL I'm getting this error :
Invalid argument supplied for foreach()
but here's what I'm noticing by doing var_dump($username):
C:\wamp64\www\PortalDealer\application\controllers\Panier.php:66:null
So my data is not passing!
Can you help me with this?
EDIT
showcase the result of this part of the code :
var_dump($_REQUEST);
$res = [];
$username = $this->input->post('username');
var_dump($username);
$panier_data = $this->model_panier->getPanierData($username);
var_dump($panier_data);
The below code should send your data to Panier/loadPanier/.
$('#exampleFormControlSelect1').change(function(){
var val1 =$('#exampleFormControlSelect1').val();
$.ajax({
method: "POST",
url: "Panier/loadPanier/",
data: { username: val1}
}).done(function( result ) {
$("#tbodyid").empty();
var data1 = JSON.parse(result);
console.log(data1) ;
});
});
You were seeing null every time you did var_dump() because you were trying to load the page independently. The page will only give you the POST value if you are going to the page thru the form, in this case, the form is javascript. When you load a page with POST method in javascript, the response is sent to the same page with ajax so you can work with your code without having to refresh the page.
Also: You cannot return data to javascript. You have to print it out to client side so that your javascript's JSON parser can read it. Therefore, instead of return $res; :
echo json_encode($res);
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'm creating my project using OOP. I need to pass all the values inserted in the database in the form of array. And it's a multidimensional array. SO when I pass now via ajax as a 'text' datatype it displays array in console.log(). But I'm unsure if this is the correct way and how to display the value in a table form in jquery.
Below are the functions where the values returned to the object in another page.
public function selectType()
{
$sql="SELECT * FROM car_type";
$stmt =connection::$pdo->prepare($sql);
$stmt->execute();
$carType=array();
while($row = $stmt->fetch())
{
array_push($carType,$row['car_type']);
}
return $carType;
}
public function selectMaker()
{
$sql="SELECT * FROM car_maker";
$stmt =connection::$pdo->prepare($sql);
$stmt->execute();
$carMaker=array();
while($row = $stmt->fetch())
{
array_push($carMaker,$row['car_maker']);
}
return $carMaker;
}
ANd this is how I'm fetching the values to be passed to another page to be displayed to the user.
$setting = new setting($car_type,$car_maker,$rental_type,$rental);
//$setting->connection;
$setting->addCarType();
$setting->addCarMaker();
$setting->addRentalBy();
$carType=$setting->selectType();
$carMaker=$setting->selectMaker();
$json=array();
array_push($json,array("type"=>$carType,"maker"=>$carMaker));
echo $json;
Finally ajax to fetch and display data
$("#submit").on("click",function()
{
$("#set_setting").submit(function(){
data = $(this).serialize()
$.ajax({
type: "POST",
dataType: "html",
url: "submit_setting.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
//hide the form
$("#set_setting").slideUp("slow");
//show the result
for (i = 0; i < data.length; i++) {
console.log(data);//outputs array
$(".the-return").html(data);
}
}
});
return false;
});
});
You need to pass array as JSON and post it using name value pairs.
var data = {a:{'foo':'bar'},b:{'this':'that'}};
$.ajax({ url : '/',
type : 'POST',
data : {'data':JSON.stringify(data)},
success : function(){ }
});
And in backend (PHP):
$data = json_decode($_POST['data']);
print_r($data);
// Result:
// Array( "a" => Array("foo"=> "bar"), "b" => Array("that" => "this"))
trying to get 2 values from an ajax call, cant seem to breakup the results back form the call
the ajax
$.ajax({
type:'POST',
url: 'inc/getuser.php?q='+boxnum,
success:function(data){
alert(lname);
}
});
the php
$datas = $database->select("Drivers", "*", [
"id" => $q]);
if (count($datas)>0) {
foreach($datas as $data){
$fname=$data['first_name'];
$lname=$data['last_name'];
}
$rdata = array(
'fname'=> $fname,
'lname'=> $lname
);
echo $rdata; //$datas['first_name']
} else {
echo 'no datas';
}
trying to find the lastname only.
thank in advance
Jeff
Change to this:
$.ajax({
type:'POST',
dataType: 'json', // <-- specify that your return type should be JSON
url: 'inc/getuser.php?q='+boxnum,
success:function(data){
if (data.fname && data.lname) {
var firstName = data.fname;
var lastName = data.lname;
}
}
});
when working with arrays you need to use JSON data type.
Your PHP: echo json_encode($rdata);
You can use json_encode() function in your PHP file
echo json_encode($rdata);
Use json_encode() in PHP to serialize your data first as Paramore has explained.
In javascript your success function callback has a parameter of "data", "lname" is not defined in that context so to access fname and lname you need to do like so:
data.lname
data.fname
I want to add elements to arrays within an object that I access like this to retrieve data.
var event_id = events_data.event_id[i]["0"];
var event_title = events_data.event_title[i]["0"];
var selected_source = events_data.selected_source[i]["0"];
var channel_id = events_data.channel_id[i]["0"];
events_data is an object with elements event_id, event_title, ... That object is created in a php function like this.
$return = array();
$return['event_id'] = $event_id;
$return['event_title'] = $event_title;
$return['selected_source'] = $selected_source;
$return['channel_id'] = $channel_id;
$return['channel_name'] = $channel_name;
$return['event_site'] = $event_site;
$return['event_url'] = $event_url;
$return['start_date'] = $start_date;
$return['start_time'] = $start_time;
$return['end_date'] = $end_date;
$return['end_time'] = $end_time;
$return['event_notes'] = $event_notes;
echo json_encode($return);
EDIT - ADDED INFO
The json object looks like this.
{"event_id":[{"0":"e20120319215556"},{"0":"e20120310221512"},{"0":"e20120319151903"},{"0":"e20120309123705"},{"0":"e20120307122044"},{"0":"e20120306182514"},{"0":"e20120309211714"},{"0":"e20120314130727"},{"0":"e20120319150532"},{"0":"e20120319141928"},{"0":"e20120319141201"},{"0":"e20120301193226"},{"0":"e20120301184354"}]}
END INFO ADDED
On the javascript side I get the events_data array like this.
$.ajax({
url: "get_events_data.php",
type: "POST",
dataType : 'json',
data: { },
cache: false,
async: false,
success: function (rdata) {
events_data = rdata;
}
});
To add an element to events_data on the javascript side, I check for the index where to add the new element and then add it with splice. But since the data is retrieved with the ["0"] text key for the associative array, I don't know how to specify the splice parameters.
for ( var n=0; n<events_data.event_id.length; n++ ) {
if ( current_event_id == events_data.event_id[n]["0"] ) {
//splice_index = n;
events_data.event_id.splice(n,0,event_id);
events_data.event_title.splice(n,0,event_title);
events_data.selected_source.splice(n,0,selected_source);
events_data.channel_id.splice(n,0,channel_id);
events_data.channel_name.splice(n,0,channel_text);
events_data.event_site.splice(n,0,event_site);
events_data.event_url.splice(n,0,event_url);
events_data.start_date.splice(n,0,start_date_string);
events_data.start_time.splice(n,0,start_time_string);
events_data.end_date.splice(n,0,end_date_string);
events_data.end_time.splice(n,0,end_time_string);
events_data.event_notes.splice(n,0,event_notes);
break;
}
}
Specifying the splice index "n" doesn't seem to do it. What should I change?
Thanks.
Answer was quite simple:
Adding an object to an array of objects with splice
var add_object = {"0",event_id}; // declare event id as object
events_data.event_id.splice(n,0,add_object); // splice object into object array at index