I am using a hidden field and appending values with the following function.
$( "#invite_suggestion" ).autocomplete({
source: BASEURL + 'index.php/search_contacts_suggestion/',
select: function( event, ui )
{
$('#invite_id').val($('#invite_id').val()+ui.item.friend_id);
}
});
In the PHP side
$_POST['invite_id']=(isset($_POST['invite_id']))?json_encode(array($_POST['invite_id'])):json_encode(NULL);
But Actually the final output of this is string ["4565"] and what i actually need is to JSON encode of individual values in field ["45","65"]
seperate the values by a comma in your js:
$('#invite_id').val($('#invite_id').val()+','+ui.item.friend_id);
then explode on the comma in php to create the array:
(isset($_POST['invite_id']))?json_encode(explode(',',$_POST['invite_id'])):json_encode(NULL);
on the PHP side I expect you'll want to do an 'explode' on the $_POST['invide_id'] to get an array of elements. $_POST['BLAH'] will only return a string.
e.g. something like...
$_POST['invite_id']=(isset($_POST['invite_id']))?json_encode(explode($_POST[',', 'invite_id']))):json_encode(NULL);
Related
I have an associative array I got from my database.
I would like to open a new window with that associated array posted to it.
I did manage to post it in ajax post, But it's not what I need because I want a new window!
Using a form is impossible because you cannot put that kind of data in an hidden input.
So how do I do it?
I think you are looking for JSON
Php example:
echo json_encode( array('int'=>123, 'char'=>'abc', 'array'=>array(1,2,3)) );
The javascript:
$.getJSON( "ajax/test.php", function( data ) {
console.log( data ); // data is a json-object
data.each(function(item){
console.log( typeof item.int ) // Number, value 123
console.log( typeof item.char ) // String, value '123'
console.log( typeof item.array ) // array/object, values 1,2,3
});
});
edit: the names int, char and array are choosen as example. One might want to avoid the usage of reserved names as variable names
edit: misread, changed to better answer
I used session as suggested by #CodeBird.
$_SESSION['temp_info'] = $array;
Then I just <a href> to another page.
Where I used the following code:
$array = $_SESSION['temp_info'];
So i have this piece of javascript, it posts to foo.php with value val, gets back data, empties the container and call function graph which will fill the container with a new chart.
$.post("foo.php", {val: val}, function(data){
if(data.length >0) {
$('#container').html('');
graph(data);
}
});
in foo.php, how do I make it pass back an array instead of string? at the moment I just have an echo in foo.php that echos the data delimited by a comma, ie: 1,2,3,4,5. then in the graph function I have a split(',' data) that creates an array for later use.
I mean, all this works fine, I'm just wondering if I can avoid the split step and have foo.php return an array directly.
thanks!
That's what json_encode is for:
echo json_encode( $array );
Just remember to set JSON headers, so that jQuery will know to parse the returned data as JSON. If you don't, you'll have to specify that in your jQuery AJAX call as follows:
$.post("foo.php", {val: val}, function(data){
if (data.length > 0) {
$('#container').html('');
graph(data);
}
}, 'json'); // <-- Here you're specifying that it'll return JSON
json_encode your array in PHP and jquery can easily parse your JSON encoded data.
I've a php script which loads basically just one csv via:
echo json_encode(file(csvfile.csv, FILE_IGNORE_NEW_LINES));
The output is something like this:
["foo,bar,baz","foo, foo,bar","bla,bla,blubb"]
In my basic html file I load it in this way:
<script>
$(document).ready(function(){
$.getJSON("myphpscript.php", function(data) {
filltable(data);
})
});
function filltable(jqxhr){
var table_obj = $('table');
$.each(jqxhr, function(index, item){
table_obj.append($('<tr id="'+item.id+'"><td>'+item.data+'</td></tr>'));
}).insertAfter('.table');
}
</script>
which fills my <table id="table"></table> just with undefined.
My goal is it to get a table with 1 column containing:
foo,bar,baz
foo, foo,bar
bla,bla,blubb
After specify a delimiter my js-function should explode each line and more columns.
This is my first attempt with javascript and json. Thank you very much
Edit: Fixed function call (Thanks VisioN) . object.length is now ok, but the table is still undefinied
I think you might want to use
table_obj.append($('<tr id="'+index+'"><td>'+item+'</td></tr>'));
instead of
table_obj.append($('<tr id="'+item.id+'"><td>'+item.data+'</td></tr>'));
Your data structure doesn't match the jQuery object parsing schema
You are trying to parse an object that would look like:
[{"id":"foo","data":"foo,bar,baz"}]
For one column You just want
table_obj.append($('<tr id="'+item+'</td></tr>'));
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.
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.