Jquery Get all the array elements - php

I am programming beginner..
Code
<script type="text/javascript">
$(function() {
var course_category = "<?php echo $_REQUEST['cities'] ?>";
alert(course_category); // alerts as Array
});
when i do print_r in php (print_r($cities);) i get
Array ( [0] => BLR [1] => DEL [2] => HYD [3] => MUM
now i want to print the array in above jquery
try
$.each(course_category, function(key,value){
alert(value);
}};
printns A,r,r,a,y

The correct way is to use JSON:
var list = <?php echo json_encode($_REQUEST['cities']); ?>;

I assume you currently have two problems:
Your PHP array is not encoded in any way, that JavaScript understand. Just use json_encode() here.
If you receive an object (and arrays are just objects for that matter), you can't just output them using alert(), if you really want to see the contents. Again, you may use JSON.stringify() to solve this.
$(function() {
var course_category = "<?php echo json_encode( $_REQUEST['cities'] ); ?>";
alert( JSON.stringify( course_category) );
});
If you want to use the array contents later on, refer to plain for loops or jQuery's each().

<?php
$output = '';
foreach($_REQUEST['cities'] as $city){
$output .= "'$city',";
}
$output = rtrim(",", $output);
?>
var course_category = [<?php echo $output; ?>];

You can use .each in jQuery to iterate an array
$.each(course_category , function(index, item) {
});
Actually i dont know about php.But you can iterate an array using the above code in jQuery

Related

Javascript Convert PHP Json into a javascript array

In php I used json_encode(...) and then got the value in Javascript, looks as the following:
["float","float","float","float"] // PS: This is a string...
And I would like to make this into a normal javascript array, like so:
Arr[0] // Will be float
Arr[1] // Will be float
Arr[2] // Will be float
Arr[3] // Will be float
How is this possible?
It sounds like you're retrieving a JSON string in JavaScript (perhaps via AJAX?). If you need to make this into an actual array value, you'd probably want to use JSON.parse().
var retrievedJSON = '["float","float","float","float"]'; // normally from AJAX
var myArray = JSON.parse(retrievedJSON);
If you're actually writing out a value into the page, rather than using AJAX, then you should be able to simply echo the output of json_encode directly, without quoting; JSON itself is valid JavaScript.
var myArray = <?php echo json_encode($myPhpArray); ?>;
var myArray = <?= json_encode($myPhpArray); ?>;
Pretty simple. ;-)
Example:
<?php
$myPhpArray = array('foo', 'bar', 'baz');
?>
<script type="text/javascript">
var myJsArray = <?= json_encode($myPhpArray); ?>;
</script>
Should output (view-source):
<script type="javascript">
var myJsArray = ["foo","bar","baz"];
</script>
Example
I reccomend using jquery. The php file should look as such ...
//location.php
<?php
$change = array('key1' => $var1, 'key2' => $var2, 'key3' => $var3);
echo json_encode($change);
?>
Then the jquery script ...
<script>
$.get("location.php", function(data){
var duce = jQuery.parseJSON(data);
var art1 = duce.key1;
var art2 = duce.key2;
var art3 = duce.key3;
});
</script>

Passing a php array into javascript using JSON

I have a multidimensional array, here:
$noticeDate = json_encode( $noticesDates );
and I want to pass the array into javascript:
var unavailableDates[] = $noticeDate;
Both variables are in the same php file so there is little point using $.getJSON, which basically looks for the variable in an external file. However, how do I pass the object into the javascript array in the same script.
Cheers
You cant directly assign php variables to js, but you can use something like that:
<script>
var unavailableDates = jQuery.parseJSON('<?php echo json_encode($noticeDates) ?>');
</script>
use this
var array = JSON.parse("<?php echo json_encode($noticesDates) ?>");
Try this one:
$.pareseJSON()
here is example:
var json = "<?php echo json_encode($noticesDates); ?>";
jsArray = jQuery.parseJSON(json);

jQuery: post a multidimensional array

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.

How to get value to array in javascript

$array = array("1" => "box of chocolates", "2" => "mylar balloons", "3" => "stuffed animals");
<?php
$productWithItem = $array;
foreach ($productWithItem as $pwi) {
?>
<?php echo $pwi->name ?></div>
<?php
}
?>
<script type="text/javascript">
jQuery(function(){
var value_array = ?;
});
</script>
I Want get array value from id="product_name", but I don't know get value from on this javascript, you can help me, thank you
If you are intending to keep your <script> in your html code, build your array in php and use echo:
<script type="text/javascript">
jQuery(function(){
var value_array = <?php echo $yourarray ?>;
});
</script>
That's not an elegant solution, though.
Make product_name as id into class . now $('.product_name') this will be automatically array of objects
example markup
aaa</div>
bb</div>
cc</div>
using each you can extract array
$('.product_name').each(function(){
alert($(this).text());
});
Put your array string in the name attribute of the <a>.
Then you can use jQuery to get it back:
jQuery(function(){
var ele= [YOUR ELEMENT]
var value_array = $.parseJSON($(ele).attr("name"));
});

jquery: possible to create GET string with nested arrays using serialize()?

I have a page with 3 forms on it.
To create a valid get(or post) data str with each form as a nested array nested arrays.
psuedo-code for what i want (just don't know how to wrap them in nested arrays..):
var data_str = $('#form1').serialize() + $('#form2').serialize() + $('#form3').serialize();
$.ajax(.....
desired output on processing file:
print_r($_GET);
/*
{
['form1'] => .....nested array here..
['form2'] => .....nested array here..
['form3'] => .....nested array here..
}
*/
$.get({
data:{
form1:$('#form1').serialize(),
form2:$('#form2').serialize(),
form3:$('#form3').serialize()
},
//other options
I'm not a javascript pro but I've built a solution and it works, enjoy:
function mutliple_forms_to_data_str(array_of_form_ids){
var multidim_data = {};
$.each(array_of_form_ids, function(index,id) {
var forms_data = $('#'+id).serializeArray();
var htemp = {};
$.each(forms_data, function(index,val) {
htemp[val.name] = val.value;
});
multidim_data[id] = htemp;
});
return multidim_data;
}
Use array push, to do that
but honestly you best use one form no need for all three of them unless is last resource.
or simply.
var data_str = {
'form1': $('#form1').serialize(),
'form2': $('#form2').serialize(),
'form3': $('#form3').serialize(),
}
PHP would read them fine as a tree like array,
You might have to use serializeArray(); instead

Categories