how to pass a php array to javascript array using jquery ajax? - php

I followed other reslted question but still unable to solve this problem. I want to store the values of an array from php into an array of js. I tried myself butr getting indefined value in all the cases i tried
Plese anyone let me know where i am wrong
my Php code
<?php
$var=5;
$myArray = array();
while($var<10){
$myArray[]=$var;
$var++;
}
echo json_encode($myArray);
?>
and the js code
jQuery(document).ready(function(){
jQuery("#previous").click(function(){
var res = new Array(); var i= 0;
jQuery.getJSON("phparray.php", function(data) {
while(i<5){
res[i]=data.i;
i++;
}
});
});
jQuery("#result").html(res[0]);
});
also treid this js
jQuery(document).ready(function(){
jQuery("#previous").click(function(){
var res = new Array();
var i= 0;
jQuery.getJSON("phparray.php", function(data) {
jQuery(data).each(function(key, value) {
res[i]=value;
i++;
});
});
jQuery("#result").html(res[0]);
});

Try below code
<?php
$var=5;
$myArray = array();
while($var<10){
$myArray[]=$var;
$var++;
}
$dataarray=array("myarray"=>$myArray);
echo json_encode($dataarray);
?>
Jquery
jQuery(document).ready(function(){
jQuery("#previous").click(function(){
var res = new Array();
jQuery.getJSON("phparray.php", function(data) {
var i= 0;
while(i<data.myarray.length){
res[i]=data.myarray[i];
i++;
}
jQuery("#result").html(res[0]);
});
});
});

The problem with your code is you are updating the result before the JSON has been loaded. There is also no reason to copy every item in the array in this case just set res = data (although the above example of sending back an associative array or JS object is good practice).
PHP
<?php
for($var=5; $var<10; $var++){
$myArray[]=$var;
}
echo json_encode($myArray);
JavaScript
$(document).ready(function() {
var res;
$("#result").bind('update', function() {
$("#result").html(res[0]);
});
$("#previous").click(function(){
$.getJSON("phparray.php", function(data) {
res = data;
$("#result").trigger('update');
});
});
});

Related

Parsing JSON Values Through jQuery is eliminating 1st value

I am storing a PHP array variable in Jquery variable.
Following is the code that I am using:
<script>
var tagger = '<?php echo json_encode($tags); ?>';
var obj = jQuery.parseJSON(tagger);
$.each(obj, function(key,value)
{
$("#post_tags").tagging("add", value);
});
</script>
In tagger variable, I am getting this below data.
var tagger = '["sdf"," da"," adf"," ad"]';
But when I am running the loop it is showing values from the second index, the first index value is being eliminated.
Only these values are visible in the field : '[" da"," adf"," ad"]'.
The sdf value is not displayed.
May I know that where is it being wrong, as far as I am concerned the code is good to go. But still, want to confirm that is there anything missing.
<script>
// try this
var obj = <?php echo json_encode($tags); ?>;
//var obj = jQuery.parseJSON(tagger);
$.each(obj, function(key,value)
{
$("#post_tags").tagging("add", value);
});
</script>
You don't have to parse the tagger because it already in json format:
<script>
var tagger = <?php echo json_encode((array)$tags);?>;
$.each(tagger, function(key,value)
{
$("#post_tags").tagging("add", value);
});
</script>

How to use loop for multiple arrays imported from Database

In server side I give table data from MySql and I send it with json_encode to JQuery:
<?php
include 'DB.php';
$result20 = mysql_query("SELECT * FROM Gallery WHERE Section = 'Chosen' AND ID = 19");
$array20 = mysql_fetch_row($result20);
$result19 = mysql_query("SELECT * FROM Gallery WHERE Section = 'Chosen' AND ID = 19");
$array19 = mysql_fetch_row($result19);
$data = array();
$data['Div20'] = $array20;
$data['Div19'] = $array19;
echo json_encode($data);
?>
json_encode export this arrays: {"Div20":["Image20","20.jpg"],"Div19":["Image19","19.jpg"]}
but, in client side I need use a loop for use all arrays in events. When I use for, it's not work with multiple arrays, how to do it?
$(function() {
$.get('data.php' ,function(response)
{
var data = jQuery.parseJSON(response);
var array;
for(array in data)
{
var ImageID = data.array[0];
var ImageSrc = data.array[1];
$('#'+ImageID ).click(function(){
//some codes
})
}
})
})
Try this
$(function() {
$.get('data.php' ,function(response) {
var data = jQuery.parseJSON(response);
$.each( data, function( key, value) {
var ImageID = value[0];
var ImageSrc = value[1];
$("#"+ImageID ).click(function(){
//some codes
})
})
})
It will work if you add # to your imageid like,
$('#'+ImageID ).click(function(){
//some codes
});
I've tried some code for you,
var json={"Div20":["Image20","20.jpg"],"Div19":["Image19","19.jpg"]};
for(div in json){
ImageID=json[div][0];
ImageSRC=json[div][1];
$('#'+ImageID)
.attr('src',ImageSRC)
.click(function(){
alert(this.src);
});
}
Demo
Replace .array with [array] in your for loop:
for(array in data)
{
var ImageID = data[array][0];
var ImageSrc = data[array][1];
}
"array" is not an attribute of your json object, it's just an argument of your for ... in loop. So you must use it as a dynamic value. Moreover you missed using a # to target properly the element id.
var data = {"Div20":["Image20","20.jpg"],"Div19":["Image19","19.jpg"]};
for(array in data)
{
var ImageID = "#"+data[array][0];
var ImageSrc = data[array][1];
$(ImageID).on("click",function(){
//some codes
});
};
Avoid using $.each() loop as someone recommended above, jQuery loops are usually slower than native loops.
Try this..
$(function() {
$.get('data.php' ,function(response)
{
var data = jQuery.parseJSON(response);
$.each(data,function(k, v){
var ImageID = v[0];
var ImageSrc = v[1];
$('#'+ImageID ).click(function(){
//some codes`enter code here`
})
})
})

Passing a js array to PHP

Why can't I access my array through $_POST in PHP? I'm trying to use the jQuery $.post method. Here is the corrected code with your suggestions:
My javascript:
<script type="text/javascript">
var selectedValues;
var serializedValues;
$("td").click(function() {
$(this).toggleClass('selectedBox');
// map text of tds to selectedValues
selectedValues = $.map($("td.selectedBox"), function(obj) {
return $(obj).text();
});
serializedValues = JSON.stringify(selectedValues);
// $.post('/url/to/page', {'someKeyName': variableName}); //exemple
$.post('handler.php',
{'serializedValues' : serializedValues},
function(data) {
//debug
}
);
});
</script>
My php:
<?php
if(isset($_POST['serializedValues'])) {
var_dump($_POST['serializedValues']);
$originalValues = json_decode($_POST['serializedValues'], 1);
print_r($originalValues);
}
?>
You should serialize your array into json string:
serializedValues = JSON.stringify(selectedValues)
And pass it to php. And then decode with json_decode:
$originalValues = json_decode($_POST['serializedValues'], 1);
http://php.net/manual/ru/function.json-decode.php
On a side note; your javascript could be refactored into something a bit more simple
$("td").click(function() {
$(this).toggleClass('selectedBox');
// map text of tds to selectedValues
var selectedValues = $.map($("td.selectedBox"), function(obj) {
return $(obj).text();
});
// $.post('/url/to/page', {'someKeyName': variableName}); //exemple
$.post('handler.php',
{'serializedValues' : JSON.stringify(serializedValues)},
function(data) {
//debug
}
);
});

Passing js array to PHP [duplicate]

Why can't I access my array through $_POST in PHP? I'm trying to use the jQuery $.post method. Here is the corrected code with your suggestions:
My javascript:
<script type="text/javascript">
var selectedValues;
var serializedValues;
$("td").click(function() {
$(this).toggleClass('selectedBox');
// map text of tds to selectedValues
selectedValues = $.map($("td.selectedBox"), function(obj) {
return $(obj).text();
});
serializedValues = JSON.stringify(selectedValues);
// $.post('/url/to/page', {'someKeyName': variableName}); //exemple
$.post('handler.php',
{'serializedValues' : serializedValues},
function(data) {
//debug
}
);
});
</script>
My php:
<?php
if(isset($_POST['serializedValues'])) {
var_dump($_POST['serializedValues']);
$originalValues = json_decode($_POST['serializedValues'], 1);
print_r($originalValues);
}
?>
You should serialize your array into json string:
serializedValues = JSON.stringify(selectedValues)
And pass it to php. And then decode with json_decode:
$originalValues = json_decode($_POST['serializedValues'], 1);
http://php.net/manual/ru/function.json-decode.php
On a side note; your javascript could be refactored into something a bit more simple
$("td").click(function() {
$(this).toggleClass('selectedBox');
// map text of tds to selectedValues
var selectedValues = $.map($("td.selectedBox"), function(obj) {
return $(obj).text();
});
// $.post('/url/to/page', {'someKeyName': variableName}); //exemple
$.post('handler.php',
{'serializedValues' : JSON.stringify(serializedValues)},
function(data) {
//debug
}
);
});

pass php array to jquery function

I got a page with a form to fill it with custormers info. I got previous custormers data stored in a php array. With a dropdownlist users can fill the form with my stored data.
what i have is a jquery function that triggers when the value changes and inside that function i whould like to update the form values with my stored data (in my php array).
Problem is that i dont know how to pass my php array to the jquery function, any idea ??
this is how i fill the array:
$contador_acompanantes = 0;
foreach ($acompanantes->Persona as $acomp)
{
$numero = $acomp->Numero;
$apellidos = $acomp->Apellidos;
$nombre = $acomp->Nombre;
$ACOMPANANTES[$contador_acompanantes] = $ficha_acomp;
$contador_acompanantes++;
}
got my select object:
<select name="acompanante_anterior" id="acompanante_anterior">
<option value="1" selected>AcompaƱante</option>
<option value="2">acompanante1</option>
<option value="2">acompanante2</option>
</select>
and this is my code for the jquery function (it is in the same .php page)
<script type="text/javascript">
$(document).ready(function()
{
$('#acompanante_anterior').on('change', function()
{
});
});
</script>
var arrayFromPHP = <?php echo json_encode($phpArray); ?>;
$.each(arrayFromPHP, function (i, elem) {
// do your stuff
});
You'll likely want to use json_encode, embed the JSON in the page, and parse it with JSON-js. Using this method, you should be aware of escaping </script>, quotes, and other entities. Also, standard security concerns apply. Demo here: http://jsfiddle.net/imsky/fjEgj/
HTML:
<select><option>---</option><option>Hello</option><option>World</option></select>
<script type="text/javascript">
var encoded_json_from_php = '{"Hello":[1,2,3], "World":[4,5,6]}';
var json = JSON.parse(encoded_json_from_php);
</script>
jQuery:
$(function() {
$("select").change(function() {
$(this).unbind("change");
var val = json[$(this).val()];
var select = $(this);
$(this).empty();
$.each(val, function(i, v) {
select.append("<option>" + v + "</option>");
});
});
});
try this one..
<script type="text/javascript">
$(document).ready(function()
{
$('#acompanante_anterior').on('change', function()
{
my_array = new Array();
<?php foreach($array as $key->val)?>
my_array['<?php echo $key?>'] = '<?php echo $val;?>';
<?php endif; ?>
});
});
</script>

Categories