jQuery: post a multidimensional array - php

I am learning how to use jQuery, $.post and php. (I am not a pro like you guys)
I want to send a multidimensional array to php.
My array looks something like this:
var item= new Array();
item[0] = ["Object", "Value"];
item[1] = ["id", "x"];
item[2] = ["status", "y"];
item[3] = ["date", "z"];
etc...
This is my jQuery code:
//AJAX
$("#add").click(function()
{
$.post( 'ajax_new.php' ,
{
item : item
},
function(data)
{
alert( data );
} //end: if:else
); //END:$.post
}); //END:ajax
Also, after posting the array, how do I handle it in php?
Like this?:
<?
$id = $_POST['item'][1][1];
echo $id;
?>

I use to convert collected data to JSON before send it to the server.
http://api.jquery.com/serializeArray/

I would definitely convert it to JSON object or either use JSON object instead of an array.

Related

Get response array from jquery ajax to php

I am trying to populate a table from mysql based on a select box option using jquery ajax, so far this is my jquery code. I can show the result on the alert box but i dont know how to send it to php so that i can loop thru the array and create the table.
// selector de campaƱa en reporte de clientes mas activos
$(document).ready(function(){
$('.selector-camp').change(function(){
var campaing = $('.selector-camp').val();
$.post( "../campanas/test", { 'camp': campaing },
function( data ) {
alert( data.result );
}, "json");
});
});
As I use JavaScript more than jquery, I'll write it in JavaScript and I am sure you can do that in Jquery too, but in JavaScript it's also easy to do
function( data )
{
createTable(data.result); //pass your json array to JS function
}, "json");
//here i create js function
function createTable(array)
{
var array = JSON.parse(array); //decoding from json format
//So if i have numbers in array like [1, 2, 3, 4] and want
//to create row with them something like this should be done
var table = document.createElement("table"); //create table
var tr = document.createElement("tr"); //create row
for(var i=0; i<array.length; i++)
{
var td = document.createElement("td");
td.innerHTML = array[i];
tr.appendChild(td);
//for each array element creates cell and appends to row
}
table.appendChild(tr);
//Then you can have some empty div and append table to it
var div = //your empty div
div.appendChild(table);
}
Please check below php prototype code as per your requirement.
From ajax please make a call to this file it will return you a json response since I have used json_encode() function, you can directly return array as well but I would not suggest that, also you can edit this code for further mysql query.
<?php
test();
function test(){
$camp = htmlspecialchars($_POST['camp']);
isset($camp)&&!empty($camp)?
$data = array('test_key'=>'test_value');
echo json_encode($data);
}
?>

How to create multidimensial arrays with PHP and access with jQuery?

So I have got to a stage in my website where I need to pack a lot of information into a single json array like object, so in order to do this I need to pack a list of array information under a certain key name, then another set of data under another key name.
So for example:
$array = array();
foreach(action goes here)
{
$array['data1'] = array('information' => data, 'more_information' => more_data)
}
$array['data2'] = array("more data");
This basically illustrates what I am trying to do, I am able to partially do this, however naming the key for the new data set only replaces each data, instead of adding into it in the foreach loops.
Now if this part isn't too confusing, I need some help with this. Then in addition to this, once this is sorted out, I need to be able to use the data in my jQuery response, so I need to be able to access each set of data something like: json.data1[i++].data, which would ideally return "more_information".
You need an incremental number in that loop and make the results available as a json object...
$array = array();
$i = 0;
foreach(action goes here)
{
$array['data'.$i] = array('information' => data, 'more_information' => more_data)
$i++;
}
$array['data2'] = array("more data");
$data = json_encode($array);
Then in php you might set a js var like so:
<script type="text/javascript">
var data = <?php echo $data; ?>;
</script>
which could then be accessed in js easily:
alert(data.data1.information);
If I understand your question correctly you expect to get this object as a response to something? Like a jQuery .ajax call?
http://api.jquery.com/jQuery.ajax/
This link illustrates how to use it pretty clearly. You would want to make sure to specify dataType = "json" and then place your data handling in the success call:
$.ajax({
url: 'some url string',
type: "GET",
dataType: "json",
success: function(data)
{
$.each(data, function(i, v){
console.log(data[i]);
});
},
error: function()
{
//error handling
}
});
This is relatively untested, but the concept is what I am trying to convey. You basically make your multi-dimensional array in php and json_encode it. Either of these methods will allow you to parse the json.

Parsing PHP/JSON data in Javascript

I'm trying to communicate AJAX, JSON to PHP and then PHP returns some data and I'm trying to parse it with Javascrpt.
From the php, server I return,
echo json_encode($data);
// it outputs ["123","something","and more something"]
and then in client-side,
success : function(data){
//I want the data as following
// data[0] = 123
// data[1] = something
// data[3] = and more something
}
But, it gives as;
data[0] = [
data[1] = "
data[2] = 1
It is reading each character but I want strings from the array, not individual characters. What is happening here? Thanks in advance, I am new to Javascript and JSON, AJAX.
JSON.parse(data) should do the trick.
Set the dataType property of the ajax call to json. Then jQuery will automatically convert your response to object representation.
$.ajax({
url : ...,
data : ...,
dataType : "json",
success : function(json) {
console.log(json);
}
});
Another option is to set headers in PHP so that JQuery understand that you send a JSON object.
header("Content-Type: application/json");
echo json_encode($data);
Check this one... Should Work
success : function(data){
var result = data;
result=result.replace("[","");
result=result.replace("]","");
var arr = new Array();
arr=result.split(",")
alert(arr[0]); //123
alert(arr[1]); //something
alert(arr[2]); //......
}
You did not shown function in which you parse data. But you shoud use
JSON.parse
and if broser does not support JSON then use json polyfill from https://github.com/douglascrockford/JSON-js
dataArray = JSON.parse(dataFomXHR);
I'm not sure if this is what you want but why don't you want php to return it in this format:
{'item1':'123','item2':'something','item3':'and more something'}
Well to achieve this, you'll need to make sure the array you json_encode() is associative.
It should be in the form below
array("item1"=>123,"item2"=>"something","item3"=>"more something");
You could even go ahead to do a stripslashes() in the event that some of the values in the array could be URLs
You could then do a JSON.parse() on the JSON string and access the values
Hop this helps!

Jquery .post() return array

Sorry for the bad title, but I don't know how to name this. My problem is that whenever I pass a value from a select box I trigger this jquery event in order to check on the check boxes. Bassically I echo $res[]; at selecctedgr.php. Do I need to use json? and how can I do this?
Mainpage:
$("#group_name").change(function(){
var groupname = $("#group_name").val();
var selectedGroup = 'gr_name='+ groupname;
$.post("selectedgr.php", {data: selectedGroup}, function(data){
$.each(data, function(){
$("#" + this).attr("checked","checked");
});
},"json");
});
PHP (selectedgr.php):
<?php
include_once '../include/lib.php';
$gr_name=mysql_real_escape_string($_POST['gr_name']);
$sqlgr = "SELECT * FROM PRIVILLAGE WHERE MAINGR_ID=".$gr_name;
$resultgr = sql($sqlgr);
while($rowgr = mysql_fetch_array($resultgr)){
$res[] = $rowgr['ACT_ID'];
}
echo $res[];
?>
Change the last line in your PHP sample (echo $res[];) to:
echo json_encode($res);
json_encode() manual page will tell you more.
Also as #Unicron says you need to validate the $gr_name variable before passing it to your SQL statement.
You could use:
if(isset($_POST['gr_name'])) {
$gr_name = mysql_real_escape_string($_POST['gr_name']);
}
See: http://php.net/manual/en/function.mysql-real-escape-string.php for more information in the PHP manual.
You can use json_encode function to convert arbitrary data into JSON. Assuming that you want to return an array of strings, here is how you will use json_encode:
<?php
include_once '../include/lib.php';
$res = array(); // initialize variables
$sqlgr = sprintf("
SELECT ACT_ID
FROM PRIVILLAGE
WHERE MAINGR_ID=%d
",
$_POST['gr_name']
); // only select those columns that you need
// and do not trust user input
$resultgr = sql($sqlgr);
while($rowgr = mysql_fetch_array($resultgr)){
$res[] = $rowgr['ACT_ID'];
}
echo json_encode($res); // use json_encode to convert the PHP array into a JSON object
// this will output something like ['foo', 'bar', 'blah', 'baz'] as a string
?>
On the client side you can use jQuery.post method, like this:
<script type="text/javascript">
$("#group_name").change(function () {
$.post("selectedgr.php", {
gr_name: $(this).val()
}, function (data) {
// console.log(data);
// jQuery will convert the string "['foo', 'bar', 'blah', 'baz']" into a JavaScript object
// (an array in this case) and pass as the first parameter
for(var i = 0; i < data.length; i++) {
$("#" + data[i]).attr("checked", "checked");
}
}, "json");
});
</script>
If you want to use JSON then just use echo json_encode($res);
But I don't really understand what you'll gain if your code is working now, since you'll still have to do some processing in the Javascript to handle the result.
I found my major problem as below
instead of (before):
$.post("selectedgr.php", {data: selectedGroup}, function(data){
do this (after):
$.post("selectedgr.php", selectedGroup, function(data){
Forgive my bad. Ahh ya guys, regarding the escaping on mysql actually #group_name is not any input field but a select box. Appreciate for every comment, suggestion and guide.
Eric.

How to post a Array using Jquery

hello frieds this is how i usually post a variable using Jquery..
$.post("include/save_legatee.inc.php", { legatee_name: legatee_name_string,
legatee_relationship:legatee_relationship_string,
}, function(response){
alert(response);
});
Can anybody explain how to post an array using Jquery..
var all_legattee_list= new Array();
all_legattee_list[1]="mohit";
all_legattee_list[2]="jain";
this is my array... How can post this using jquery???
$.post(
'include/save_legatee.inc.php',
{ all_legattee_list: ['mohit', 'jain'] },
function(data) {
}
);
Post this as a string separated with some delimiter.
use .join() to join the array
var strJoinedArray = all_legattee_list.join(',');
and in your php code split the string using , and retrieve the values.
you have to use all_legattee_list[] as name of your parameter, something like this:
$.post("...", "all_legattee_list[]=mohit&all_legattee_list[]=jain", ...);
For example, like this: Serializing to JSON in jQuery. Of course the server would have to support JSON deserialization, but many server-side languages already do.

Categories