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.
Related
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.
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!
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.
I have an array in Javascript that i am trying to pass to php. my array looks like this.
Array[0]
"empNo" : "1347"
"empName" : "John Doe"
I am building this array from this javascript:
$('input[type=text]').each(function()
{
if ($(this).attr("value").length>0)
{
param[$(this).attr("id")]=$(this).attr("value");
}
});
Then I pass the array to php using
$.post("example.php",param)
Then in php when I try to interact with the post like this:
$emp=$_POST['empNo'];
$name=$_POST['empName'];
echo ($_GET[0]);//this is for testing
It throws an error saying that The Indexes of empNo and empName are not Defined.
It also says that 0 is an undefined offset.
Thanks for the help
Instead of looping through and manually building your data to pass just do this for the whole form.
var data = $('form').serialize();
$.post("example.php", data);
Then you should have access as you expect in your php script.
BUT make sure you're using the <input name="exampleName" /> attribute and then try to access them like this...
$value = $_POST['exampleName'];
while right now, it looks like you're trying to use the id instead of name
My first guess would be that $_POST has an array whose members are the values you are sending.
So, I think the values are in $_POST[1], $_POST[2], etc...
Try to print_r($_POST) and see where your variables went to.
Response to your comment:
I would tidy up things a bit, just a suggestion - especially the attr('value') part.
$('input[type=text]').each(function() {
if ( $(this).val() ) {
param[$(this).attr('id')] = $(this).val();
}
});
Try this
var param = $('form').serialize();
$.post("example.php", param);
I am using jQuery, AJAX and PHP to update the contents of a drop down box on an event. My code currently triggers the event and uses AJAX to call a PHP function which goes to the database and gets the records associated with each member of the drop down.
I can currently return this 2-dimensional array (an array of records with an array of columns in each one) back to my jQuery function but I am at a loss as to how to convert the array into something which I can use.
jQuery code to call AJAX:
var element= $('select[name=elementName]');
var data = 'inData=' + element.val();
// Call AJAX to get the info we need to fill the drop downs by passing in the new ID
$.ajax(
{
type: "POST",
url: "ops.php",
data: "op=getInfo&" + data,
success:
function(outData)
{
// WHAT DO I DO HERE TO CONVERT 'outData' INTO A 2-DIMENSIONAL jQUERY ARRAY??
},
error:
function()
{
}
});
PHP code:
$sqlResults= mysql_query("SELECT data FROM table WHERE id='".$_POST['inData']."'");
$outData = array();
// Fill the data array with the results
while ($outData[]= mysql_fetch_array($sqlResults));
// echo the data to return it for use in the jQuery file
echo $outData;
The code posted is working fine - I just don't know how to read 'outData' in jQuery.
Thanks in advance for any help!!
Have you looked at json_encode?
echo json_encode($outData);
This will convert it into a json object that can be read by jQuery.
your looking for json
//php
echo json_encode($outData);
//javascript
$.ajax({
type: "POST",
url: "ops.php",
data: "op=getInfo&" + data,
dataType: "json",
success: function(outData) {
console.log(outData); //this will be an object just like
//your php associative array
},
error: function() {
}
});
JSON can do the trick, but why not look at it from another angle?
If you're pinging PHP to get updated info, just have PHP output the option values you want in your select box. Then use the HTML return of jQuery AJAX to .html() the result into your select element.
There's a couple of different ways to skin a cat, and I would submit that this much easier approach is going to gain you extra time to do more jQuery wizardry.
jQuery can not read the echo of a PHP array. Use json_encode before you output it:
echo json_encode($outData);
That's a format jQuery actually can parse as the response.