How do I submit an array from dojo to php.
I'm submitting these values:
["a", "b", "c"]
Here's what I got so far:
btn_send.onclick(function(){
var name_array = name_looper();
console.log(name_array);
dojo.xhrPost({
url: "dojo_phpform.php",
content: {names: name_array},
load: function(result) {
var x = dojo.byId('results');
x.innerHTML = result;
}
});
});
function name_looper(){
var names = dojo.query('input[type=text]');
var name_array = [];
names.forEach(function(element, index, array){
name_array[index] = dojo.attr(element, 'value');
});
return name_array;
}
I tried to echo $_POST['names'] from the php file(dojo_phpform.php) and it didn't return any errors. It seems like the array isn't actually submitted. The only thing that's returned is the last item in the array. What do I do?Please help, Thanks in advance!
I just tested this with grails and php. In grails I have no problem getting an array submitted through a dojo xhrPost : I retrieve the array properly parsed with all its values as expected.
If I post :
dojo.xhrPost({
content : {
names : ['foo', 'bar']
},
url : "mygrailscontroller"
});
I get an array param on the other side. Which proves the problem hasn't to be solved on the dojo side, but on the php side.
In php, if a form input has a variable of type array, its name parameter has to be set with square brackets, like : "names[]" rather than "names".
So... in your case the solution is not to flatten the array into a string (sorry), but to name your array argument with brackets. So it would be :
dojo.xhrPost({
content : {
"names[]" : ['foo', 'bar']
},
url : "myphpcontroller"
});
As far as I've been able to see, dojo's xhr functions don't support it. I'm using a helper function to "flatten" parameters myself.
_flattenXhrParams: function(params)
{
var newParams = {};
for(var key in params)
{
if(dojo.isObject(params[key]))
{
for(var innerKey in params[key])
{
newParams[key + "[" + innerKey + "]"] =
params[key][innerKey];
}
}
else if(dojo.isArray(params[key]))
{
for(var i = 0, l = params[key].length; i < l; i++)
{
newParams[key + "[]"] = params[key][i];
}
}
else
{
newParams[key] = params[key];
}
}
return newParams;
}
It's butt ugly, I know, and obviously only works on one dimensional arrays/objects. In your case, you'd do:
dojo.xhrPost({
url: "dojo_phpform.php",
content: _flattenXhrParams({names: name_array}),
load: function(result) {
var x = dojo.byId('results');
x.innerHTML = result;
}
});
.. and you'd get POST parameters like names[]=a&names[]=b&names[]=c. For objects, you'd get names[somekey]=a&names[otherKey]=b etc. PHP handles both nicely.
I'm pretty sure the values of the content object only take strings. If you want to submit an array, you'd have to turn it into JSON and then json_decode it on the server.
Related
I am using the following code to send to a php script which adds to mysql database. The php code is working fine and set up to receive two variables but I am unsure how to change the ajax code to pass over 2 (or more) variables rather than 1 to the php script.
I have named the variable that is passed 'taskA' and want to add a 'taskB'
function add_task() {
$('.add-new-task').submit(function(){
var new_taskA = $('.add-new-task select[name=new-taskA]').val();
if(new_taskA != ''){
$.post('add-task.php', { taskA: new_taskA }, function( data ) {
$('.add-new-taskA select[name=new-taskA]').val('');
$(data).appendTo('.task-list ul').hide().fadeIn();
delete_task();
});
}
return false;
});
}
function delete_task() {
$('.delete-button').click(function(){
var current_element = $(this);
var id = $(this).attr('id');
$.post('delete-task.php', { task_id: id }, function() {
current_element.parent().fadeOut("fast", function() { $(this).remove(); });
});
});
}
Many thanks in advance
{ taskA : new_taskA } is one variable (one object). But an object can have many key/value pairs : { taskA: new_taskA , taskB : new_taskB} is still one object you pass, but contains more stuff. You can pass as much data as you want this way : strings, numbers, objects, whatever.
Server-side, get this data back using :
$taskA = $_POST['taskA'];
$taskB = $_POST['taskB'];
Or even a generic loop to convert all your POST variables to PHP variables :
foreach ($_POST as $var => $value) $$var = $value;
This will automatically set the $taskA, $taskB, $taskWhatever variables with corresponding values. Mind security though, and don't forget to sanitize the content.
you can pass mulple value via , symbol
{ taskA: new_taskA ,taskB:new_taskB}
How about:
$.post('add-task.php', { taskA: new_taskA, taskB: new_taskB }, function(...
Just add ',' between the variables.
Can be found from the bottom of the jQuery API-page:
http://api.jquery.com/jquery.ajax/
i.e:
$.ajax({
method: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
I'm trying to build an array of data that will then be ajax using post to php - below is my code:
$('#mainBodySaveSubmitButtonProfilePhotoIMG').click(function() {
var profilePhotoArray = [];
$('.mainUnapprovedProfilePhotoWrapperDIV').each(function() {
var action = '';
alert( this.id );
if($('.mainUnapprovedProfilePhotoAttractiveIMG', this).is(':visible')) {
alert('attractive...');
action = 'attractive';
}
else if($('.mainUnapprovedProfilePhotoDeleteIMG', this).is(':visible')) {
alert('delete...');
action = 'delete';
}else{
alert('normal...');
action = 'normal';
}
profilePhotoArray[this.id+'_'+this.id] = action;
});
alert(profilePhotoArray.length);
for (i=0;i<profilePhotoArray.length;i++) {
console.log("Key is "+i+" and Value is "+array[i]);
}
$.post('scripts/ajax/ajax_approval_functions.php', {
'approvalProfilePhotos': '1',
'approvalProfilePhotosData': profilePhotoArray},
function(data) {
alert(data);
});
});
The if, else if, else section works fine as I can see the alerts.
When I try to alert the array length 'profilePhotoArray' it says 0 so I'm not populating the array correctly. Do I need to use .push()? I thought this format was ok?
Also do I need to do anything to the array before sending to php via ajax?
thankyou
** edit - I'm adding "profilePhotoArray[this.id+'_'+this.id] = action;" this.id twice just to prove this words as I will pass a second variable like this... am I better to use JSON for this?
Javascript arrays use numerical index, therefore your storage is failing. Use a javascript Object to store string based keys.
var lang=new Object();
lang["foo"]="Foo";
lang["bar"]="Bar";
I have a table that has sortable rows. The table is generated from a mysql database that has a field called "displayorder" that oders the table. When the user drags and drops rows, I want to use AJAX to submit those changes to the database whenever a user drops a row.
Currently, I can see the console.log() output from the success part of the AJAX call, and when i output the data there (order) it looks great, like this:
["order_1=1", "order_2=2", "order_4=3", "order_3=4"]
But according to Firebug, all that's getting passed in the $_POST is "undeclared".
How do I access that order variable from my indexpage_order.php file?
I have this jquery code:
<script>
$(document).ready(function() {
var fixHelper = function(e, tr) {
var $originals = tr.children();
var $helper = tr.clone();
$helper.children().each(function(index)
{
$(this).width($originals.eq(index).width())
});
return $helper;
};
var sortable = $("#sort tbody").sortable({
helper: fixHelper,
stop: function(event, ui) {
//create an array with the new order
order = $(this).find('input').map(function(index, obj) {
var input = $(obj);
input.val(index + 1);
return input.attr('id') + '=' + (index + 1);
});
$.ajax({
type: 'POST',
url: 'indexpage_order.php',
data: order,
error: function() {
console.log("Theres an error with AJAX");
},
success: function(order) {
console.log("Saved.");
console.log(order);
}
});
return false;
}
});
});
</script>
indexpage_order.php contains:
if(isset($_POST) ) {
while ( list($key, $value) = each($_POST) ) {
$id = trim($key,'order_'); //trim off order_
$sqlCommand =
"UPDATE indexpage
SET displayorder = '".$value."'
WHERE id = '".$id."'";
$query = mysqli_query($myConnection,$sqlCommand) or die (mysqli_error($myConnection));
$row = mysqli_fetch_array($query);
}
}
You can simply rewrite the js code that are generating the data for POST.
order = {}
$(this).find('input').map(function(index, obj)
{
return order[this.id] = index;
}
)
Rest should work in PHP.
Try $_REQUEST instead of $_POST on the PHP file for POST method with ajax.
convert the js array order to json object as ajax data needs to be in json using JSON.stringify. hence, it needs to be data:JSON.stringify(order), in the ajax function.
Or, use json_encode like this data: <?php echo json_encode(order); ?>, in the ajax function
order is an array. Convert the order to query string like this in your ajax script,
data: order.join('&'),
It looks like your sending your order in a JavaScript array
And when it arrives at your PHP, its unreadable.
If its an object look into the json_decode function.
If its an array, serialize the data before it goes, then unserialize on the php side.
PHP is unable to understand JavaScript array or objects unless they are encoded/serialized correctly.
I am using Codeigniter and trying to use the jQuery autocomplete with it. I am also using #Phil Sturgeon client rest library for Codeigniter because I am getting the autocomplete data from netflix. I am return correct JSON and I can access the first element with
response(data.autocomplete.autocomplete_item[0].title.short);
but when I loop through the results
for (var i in data.autocomplete.autocomplete_item) {
response(data.autocomplete.autocomplete_item[i].title.short)
}
it acts like a string. Lets say the result is "Swingers", it will return:
Object.value = s
Object.value = w
Object.value = i
and so on.
the js:
$("#movies").autocomplete({
source: function(request, response) {
$.ajax({
url: "<?php echo site_url();?>/welcome/search",
dataType: "JSON",
type:"POST",
data: {
q: request.term
},
success: function(data) {
for (var i in data.autocomplete.autocomplete_item) {
response(data.autocomplete.autocomplete_item[i].title.short);
}
}
});
}
}).data("autocomplete")._renderItem = function(ul, item) {
//console.log(item);
$(ul).attr('id', 'search-autocomplete');
return $("<li class=\""+item.type+"\"></li>").data( "item.autocomplete", item ).append(""+item.title+"").appendTo(ul);
};
the controller:
public function search(){
$search = $this->input->post('q');
// Run some setup
$this->rest->initialize(array('server' => 'http://api.netflix.com/'));
// set var equal to results
$netflix_query = $this->rest->get('catalog/titles/autocomplete', array('oauth_consumer_key'=>$this->consumer_key,'term'=> $search,'output'=>'json'));
//$this->rest->debug();
//$json_data = $this->load->view('nice',$data,true);
//return $json_data;
echo json_encode($netflix_query);
}
the json return
{"autocomplete":
{"autocomplete_item":[
{"title":{"short":"The Strawberry Shortcake Movie: Sky's the Limit"}},
{"title":{"short":"Futurama the Movie: Bender's Big Score"}},
{"title":{"short":"Daffy Duck's Movie: Fantastic Island"}}
...
any ideas?
thanks.
there are some console logs with the return
the url
in, as you've noticed, doesn't do what you'd like with arrays. Use $.each
As far as I know, for (property in object) means that you want to access each of its properties rather than accessing them via the index. If you want to access them via the index, you probably want to use the standard for loop.
for (i = 0; i <= 10; i++) {
response(data.autocomplete.autocomplete_item[i].title.short);
}
or if you still want to use your code, try this:
for (i in data.autocomplete.autocomplete_item) {
response(i.title.short);
}
I haven't test them yet but I think you have the idea.
ok I figured out the correct format that I need to send to the autocomplete response method:
the view
$("#movies").autocomplete({
minLength: 2,
source: function(request, response) {
$.post("<?php echo base_url();?>welcome/search", {q: request.term},
function(data){
//console.log(data);
response(data);
}, 'json');
}
});
the controller:
$search = $this->input->post('q');
// Run some setup
$this->rest->initialize(array('server' => 'http://api.netflix.com/'));
// Pull in an array
$netflix_query = $this->rest->get('catalog/titles/autocomplete', array('oauth_consumer_key'=>$this->consumer_key,'term'=> $search,'output'=>'json'),'json');
$json = array();
foreach($netflix_query->autocomplete->autocomplete_item as $item){
$temp = array("label" => $item->title->short);
array_push($json,$temp);
}
echo json_encode($json);
what was needed was to send back to the view an array of objects. Thank you guys for all your answers and help!!
I am trying to post a group of arrays using the jQuery post method, but I am having trouble getting the value of the arrays. How can I get the values of the array that I have sent?
If somebody could help me i would be grateful....
Here is what i have done:
$(document).ready( function()
{
$("#submit_info").click (
function()
{
var batchArr= new Array();
batchArr=arrPush('batch');
var facultyArr= new Array();
facultyArr=arrPush('faculty');
var levelArr= new Array();
levelArr=arrPush('level');
var sectionArr= new Array();
sectionArr=arrPush('section');
var shiftArr= new Array();
shiftArr=arrPush('shift');
$.post("server_side/college_info_insert.php",{
batchArr:batchArr,
facultyArr:facultyArr,
levelArr:levelArr,
sectionArr:sectionArr,
shiftArr:shiftArr
}, function(data)
{
alert(data);
});
}
);
function arrPush(opt)
{
var Arr= new Array();
Arr.push($("#"+opt+"_1").val());
var count= $("#"+opt).val();
var i=0;
for(i;i<=count;i++)
{
if(i==0)
{
Arr.push($("#txt"+opt).val());
}
else
{
Arr.push($("#txt"+opt+i).val());
}
}
return Arr;
}
}
);
How can I get the array values in the next page "college_info_insert.php" ??
okay, so this is actually a really common issue. It's unclear that you can't just send an array as-is from javascript to PHP and have it recognized.
The problem is that PHP doesn't know how to read in multiple values from a POST request - typically things like that require the PHP author to use brackets like: varname[].
So, basically you must send variables as strings. Using JSON you can send even complicated objects as strings to PHP using a single variable name. Typically you'd use JSON.stringify or something along those lines - but if you have a simple array you might not even need it.
Here's a full example of the problem/solution, found using jquery and $.post:
Asume you have a file myurl.php:
<?php
print_r($_POST);
?>
And in a separate file (or the console), you try:
var myarray = Array('some','elements','etc');
var mydata = {postvar1: 'string', postvar2: myarray};
$.post('myurl.php', mydata, function(response) {
alert("response: " + response);
});
This doesn't work! The result is that postvar2 only contains "etc".
The solution is force the array into a JSON string that can be decoded from PHP.
var myarray = Array('some','elements','etc');
var json_array = $.map(myarray,function(n) {
return '"'+n+'"';
});
var mydata = {postvar1: 'string', postvar2: '['+json_array+']' };
$.post('myurl.php', mydata, function(response) {
alert("response: " + response);
});
ON the PHP side you now must use: json_decode($_POST['myarray']); to get your results in a proper array.
Note, this example assumes very simple strings or numbers in your array. If you have complex objects, you will need to use a JSON.stringify function which will take care of extra quotes, escaping special characters, etc.
Not sure if i understood the question but wouldn't something like this work
if (isset($_POST['batchArr'])) {
$batchArr = $_POST['batchArr'];
// Then populate your html here e.g
echo $batchArr[0];
}