$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"));
});
Related
I have an array in PHP (it has to be PHP for somewhat complicated reasons that go beyond the scope of this post):
<?php
$arr = array(Div1, Div2);
foreach ($arr as $value) {
print_r($value);
}
?>
I then have some Jquery that I'm attempting to use to hide every element that has a class in that array.
<script>
$(document).ready(function(){
$("."+"<?php echo $value; ?>").hide();
});
</script>
However, this only hides elements whose class is equivalent to the last item in the array. In other words, only items whose class is Div2 hide. How can I make this apply to each item in the array?
you can take the php array and use it in javascript. the easiest way is to use json:
<?php
$arr = array('Div1', 'Div2');
?>
<script>
$(document).ready(function(){
var arr = <?=json_encode($arr);?>;
arr.forEach((className)=>$("."+className).hide());
});
</script>
or you can join the array and let jquery iterate over it:
<script>
$(document).ready(function(){
var arr = <?=json_encode($arr);?>;
$('.'+arr.join(', .')).hide();
});
</script>
after the foreach loop finishes, $value is still bound to the last value of your $arr. either somehow include the js-output into the loop or loop through the array again in your js-php-loop
Replace that JS line with this, it will work as long as $arr is in scope wherever the JS code is (which it should be based on your question).
<?php
foreach($arr as $value) {
echo '$("' . '.' . $value . '").hide();';
}
?>
You were previously just looping over the array and not doing anything with the values (other than using print_r() on them). Therefore when you reached the code in your second snippet, only the last value of $value was usable.
Kindly Replace it with the Below code and give a test.
<script>
$(document).ready(function(){
<?php
$arr = array(Div1, Div2);
foreach ($arr as $value) {
echo '$("."+"'.$value.').hide();';
}
?>
});
</script>
Try this :
<?php
$arr = array(Div1, Div2);
//give us the resulat of this please add to the post
var_dump($arr);
$array_to_object_json = json_encode($arr);
?>
We need to known what return this var_dump
<script>
var global_json_from_php = <?php echo $array_to_object_json; ?>;
$(document).ready(function(){
console.log(global_json_from_php);
for(i in global_json_form_php){
$("."+global_json_from_php[i]).hide();
}
});
</script>
I have an array generated serverside using php eg. array("one", "two", "three") and want to show the results on a page.
Instead of just looping through and printing them, I want to delay printing each one by a second using jquery.
setInterval(function(){
// how do i grab and show php array value?
$('#log').append(ARRAY VALUE);
}, 1000);
<span id=log></span>
Tried searching but couldn't figure out a way to do this
You can simply use like below also.
<div id="log" style="display:none">
// Generate your output with php code
</div>
inside document.ready display after n seconds.
$(document).ready(function(){
setInterval(function(){
$('#log').show();
}, 1000);
});
Let me know if it not works
Depends on how you get the array :)
But you can do this:
php
<?php
$array = [1, 2, 3];
html
<span class="hidden" id="phpArr" data-values="<?php echo json_encode($array); ?>"></span>
js
var array = $('#phpArr').data('values');
array = $.parseJSON(array);
array.each(function(i, v)
{
setTimeout(function() {$('#div').append(i)}, 1000)
})
what this does is looop through the array and append it to a div with id of div with a second delay.
Please follow this code.
Php code:
<?php
$_temparray = ["one", "two", "three"];
?>
HTML code:
<span id=log></span>
Javascript code:
<script>
var temp_data= '<?php echo implode(",",$_temparray); ?>';
var split_data = temp_data.split(',');
for(var i=0;i<split_data.length;i++){
displayMessage(split_data[i]);
}
function displayMessage(val){
setInterval(function(){
$('#log').append(val);
//console.log(val);
},1000);
}
</script>
This thing is not logically possible. Generally this is not advice
able to mix PHP and javascript code.
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
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>
I'm trying to get a PHP array to use in some jquery script using the qTip plugin. This is my array:
$descqtip[ ] = array('name' => ''.$name.'', 'description' => ''.$description.'');
Here is my jquery code:
<script type="text/javascript">
$(document).ready(function() {
var description = <?php echo json_encode($descqtip)?>;
$('#homepage_catgames h2').each(function(i){
$(this).qtip({
content: description
})
});
});
</script>
I know the above doesn't work, but i'm stuck on trying to get the description variable in each part of the array to their own individual tooltip.
Can anyone help me?
Thanks
You have some problems with how you are referencing the array on the Javascript side. I went ahead and made an example of what you wanted to do.
What you need is this:
var rows = <?php echo json_encode($descqtip); ?>;
var index = 0;
$('#sections h2').each(function()
{
$(this).qtip(
{
content: rows[index].description
});
index++;
});
The details are covered in this article I put on my blog http://blake.breakwatersyndicate.com/2011/03/php-array-in-json/
I hope that helps.