php variable anomalous behaviour - php

I'm trying to increment the value of the java script variable and php variable simultaneously , so in my java script i do :
<script>
<?php $i=1;?>
for(var i=1;i<=5;i++){
var abc = $('<input>').attr('name','demo'+i).attr('value','<?php echo set_value('demo'.$i++));
<?php echo $i; ?>
}
</script>
However ,every time the value of $i echo`ed is 2 , logically it should increment number of times the java script loop iterates and echo 5 but its not , what am i doing wrong ?

The PHP code doesn't run at the same time as the Javascript code.
The PHP code runs on the server, before the client receives the page. The Javascript code runs on the client, after the client has received the page.
You'll need to write a loop in your PHP code that provides the full data to your Javascript code.
One common way of doing it would to put it into an array and encode it as JSON serverside, then feed the JSON to your Javascript for further processing. Note, no extra parsing of the data is needed on the Javascript side, if you just assign it to a variable - JSON is valid Javascript.
Further reading
JSON in PHP
JSON in Javascript

There is no loop inside this code! (If you ask the PHP interpreter).
It is simply a PHP script which outputs a few lines of text (that happen to be Javascript code, which happens to contain a Javascript loop).

You can try understanding this code:
<script>
<?php
echo "var data = [";
for ($i = 1; $i <= 5; $i++) {
echo "'".set_value('demo'.$i)."'";
}
echo "];";
?>
for (var i = 1; i <= 5; i++) {
var abc = $('<input>').attr('name', 'demo' + i).attr('value', data[i]);
}
</script>
What actually happens is, once you run this php file, the php block generate output something like:
var data = ['demo1 value', 'demo2 value', 'demo3 value','demo4 value','demo5 value',];
this is an array in javascript, that you can use in the javascript code below the php block.

Related

How to create a loop counter while loop is runing?

I want to create a counter. I have a foreach loop value. I want show the count while the script is running. How can set a counter while the script is running?
foreach ($_productCollection as $_product){
$attrapivalue = $_product->getAttributeText('apivalue');
$prosku = $_product->getSku();
if (!in_array($prosku, $array) && $attrapivalue=="No"){
echo "<p class='count'>";
$i++;
echo "</p>";
}
}
echo "<p class='test'>Total Matched : </p>";
echo "<br>";
echo "Not Found : " .$k;
This question is (or at least should be) entirely unrelated to PHP. Use PHP to output your data, including the total count. Then, use javascript/jQuery to create a visual effect of counting from 0 to the total number, for example on document ready.
<p class='test'>Total Matched : <span>888</span></p>
Javascript
$(function(){
var item = $('.test > span');
var total = parseInt(num.text());
var counter = 0;
var timer = setInterval(function(){
counter ++;
item.text(counter);
if(counter >= total) clearInterval(timer);
}, 10);
});
`
This won't work. The output is only shown after the PHP has finished executing.
PHP stands for: "PHP: Hypertext Preprocessor", notice the "Preprocessor" part, it preprocesses the page and creates the HTML, it cannot modify the HTML once it's ran.
You Can't show php's foreach's count while the script is running.
PHP doesn't work that way. PHP is a preprocessor for HTML. It converts the dynamic code into plain html at server side as a whole, and then it sends the whole HTML file to browser.
Thus, you don't have option to show php loop's counter value to the user side.
You Can alternatively use Ajax. But again, PHP will send whole ajax response at once only after php script finishes execution. You have to implement some javascript loop mechanism at client side to show the counter value one by one as suncat100 suggested.
If you want to show value updating animation to user you can try this,
PHP
$i=0;
foreach ($_productCollection as $_product){
$attrapivalue = $_product->getAttributeText('apivalue');
$prosku = $_product->getSku();
if (!in_array($prosku, $array) && $attrapivalue=="No"){
echo "<p class='count'>";
$i++;
echo "</p>";
}
}
HTML (JS)
<script>
$(function(){
var item = $('.test > span');
var total = <?php echo $i?>;
var counter = 0;
var timer = setInterval(function(){
counter ++;
item.text(counter);
if(counter >= total) clearInterval(timer);
}, 10);
});
</script>
</body>
Use the both php and JS code in same page. put the JS code part just before ending </body>.

How to use outputs of php that is called by ajax in our file

I have an app that sends latitude, longitude values to my postgresql database. And i want to plot the updated points accordingly on my OpenLayers map using jquery,ajax. But here is where i am stuck at: When I click the button, the php file with database connection and saving the last entry of the table in an array is happening.
But when i try using the outputs in markers, nothing is happening.
How to use the output values of the php in my function?
Here is the code that i am trying to use.
php file:
<?php
$conn = pg_connect("host=xxx port=xxx dbname=xx user=postgres password=xxx");
$result = pg_exec($conn,"Query goes here");
$numrows = pg_numrows($result);
for($ri = 0; $ri < $numrows; $ri++)
{
$row = pg_fetch_array($result, $ri);
$data = array(); // create a variable to hold the information
$lat_latest[] = $row["latitude"];
$long_latest[] = $row["longitude"]; // add the row in to the results (data) array
}
pg_close($conn);
$js_lat = json_encode($lat_latest);
echo "var javascript_lat1 = ". $js_lat . ";\n";
$js_long = json_encode($long_latest);
echo "var javascript_long1 = ". $js_long . ";\n";
?>
My page code is :
function init(){
//openlayers map code is here.
$("button").click(function(){
$.get("dataconn.php",function(data,status){
alert("Data:"+data+"Status:" +status);
var extra_point = new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.Point(parseFloat(javascript_long1[0]),parseFloat(javascript_lat1[0])),
{some:'data'},
{externalGraphic: 'images1/marker-gold.png', graphicHeight: 16, graphicWidth: 16});
vectorLayer1.addFeatures([extra_point]);
});
});
}
</script>
</head>
<body onload='init();'>
<div id="map" style = 'width: 1075px; height: 485px'>
<button> Update </button>
</div>
and the alert i am getting when clicking update button is
Data:
var javascript_lat1 = ["output of the query"];
var javascript_long1 = ["output of the query"];
Status : success
Is the way i am trying to access the values of query output correct? Please help.
Sorry if this is a dumb question. I am new to jquery.
When your php script sends a string like:
'var javascript_lat1 = ["output of the query"];'
back to your code, that does not mean that your code has a variable called javascript_lat1 in it.
Your php script is sending strings back to your javascript code from which you must extract the information that you want to use in your code. It is up to your javascript code to know what format the strings are in. But since you wrote the php script you can send the strings back in any format you want. Then your javascript code can dissect the strings with regexes, split(), etc. to extract the parts of the strings that you want to use in your code. A very simple format that your php code could use is:
"output of query 1, output of query 2"
Then you can split() on the comma to separate the two pieces of data e.g.:
var pieces = data.split(', ');
Then you can use pieces[0] and pieces[1] in your javascript code.
Another option is to send a request to your php script using the $.getJSON() function. If you do that, your php script should send back a json formatted string, e.g.:
"{lat1: 'blah blah blah', long1: 'foo bar foo bar'}"
Then the $.getJSON() function will automatically convert the string into a javascript object and pass the js object to your callback function. Inside the callback function you can access the data using:
some_func(data.lat1, data.long1);

Return an Array in PHP and Javascript AJAX

Section 1
I'm trying to return an Array from PHP (after having created the file using fwrite)
I include that file on my next .load method (inside a Div) the new PHP file contains an include 'somefile.php'; there is my array ... and I would simply try to collect from PHP and use it the array with JS....
I once saw something like this ...
$(function(){
alert('<?php for_each($array as $key => $value){
echo $value; // Just an example
}
?>')
});
I wrote this piece of code on the fly so there might be a few sytax errors;
This works fine using PHP inside JS ...
I'm not sure if I heard PHP loads first and then JS ? or was it the other way around ?
Section 2
How about using JS inside PHP ?
for example ....
<?php
echo "var myArray = New Array();"
echo "myArray = ('Apple','Banana','Orange','Kiwis');"
echo "return myArray";
?>
and then being able to fetch the data strait with JS ?
<script type="text/javascript">
for(i=0;i<myArray.length;i++){
alert(myArray[i]);
</script>
So how easy can I manipulate both languages in regards to RETURNING the array for example so it could be used in the global scope?
PHP runs first, so you can use it to write JavaScript code, that will get run once the page has been processed by the browser.
This would build JavaScript code with an array from PHP:
<script>
var myArray = <?php echo json_encode(array('apple', 'orange', 'kiwi'); ?>;
myArray.forEach(alert)
</script>
The other way around, passing data from JavaScript to PHP, can only be accomplished with some form of AJAX.
using PHP in JS : In short, you can echo the values in JS codes, e.g.
window.location = '<?php echo $url; ?>';
using JS in PHP : You can use AJAX . post the values to a PHP script
The PHP runs on the server, so from Javascript's point-of-view (running in the client's browser) it's like the PHP was never even there.
You can easily pass the PHP array to Javascript using PHP's json_encode() function:
$yourPHPArray = array("blah","blah","blah");
echo "var theArray=" . json_encode($yourPHPArray) . ";";
echo "for(var i=0;i<theArray.length;i++)";
echo "{";
echo " window.alert(theArray[i]);";
echo "}";

Pass Arrays from PHP file to JS file

I would like to pass an array I have in my PHP file to another file that is written in java script.
This is my array:
$pictures = array(
"1" => array("caption" => "1920x1200px", "tag" => "wallpaper", "link" => "#"),
);
And in my java script file this is the place where I want to call the array:
(At the place where they shall be in the code I wrote TAG, LINK and CAPTION.
Sry if this is a stupid question, but as you see, I have no idea about PHP and java script)
F.helpers.title = {
beforeShow: function (opts) {
var text = F.current.title,
type = opts.type,
title,
target;
if (!isString(text) || $.trim(text) === '') {
return;
}
title = $('<div class="fancybox-title fancybox-title-' + type + '-wrap"><h1>' + text + '</h1><p>CAPTION</p></div><div class="fancybox-title fancydownload" ><img src="../../../slider/img/download.png" alt=""/></div><div class="fancybox-title fancytag"><h2>TAG</h2></div>');
switch (type) {
case 'inside':
target = F.skin;
break;
case 'outside':
target = F.wrap;
break;
case 'over':
target = F.inner;
break;
default: // 'float'
target = F.skin;
title
.appendTo('body')
.width(title.width()) //This helps for some browsers
.wrapInner('<span class="child"></span>');
//Increase bottom margin so this title will also fit into viewport
F.current.margin[2] += Math.abs( getScalar(title.css('margin-bottom')) );
break;
}
if (opts.position === 'top') {
title.prependTo(target);
} else {
title.appendTo(target);
}
}
};
Try it using JSON. There are quite a few JSON parsers available
Encode it as JSON to convert it into a JavaScript literal, then access the resultant value as normal.
var data = <?php echo json_encode(array('foo' => 'bar')); ?>;
console.log(data['foo']);
The lifecycle of your PHP script (on the server side) is different from that of JS (on the client side). If you want to pass some information from PHP to client side, you can do one of the following:
You should print this information into the HTML file on the server side itself using your template engine.
You should return this information through another API by converting it into JSON format that is easy to browse through on the javascript side, and call your API using AJAX.
use an ajax call, something like $.post to get the array as a json array,
add an echo json_encode($picture) at the end of your PHP script.
PHP just generates files which then you send to the client. JavaScript is executed on the client side. So you should generate in php something like
var pictures = {'1': {caption: '1920x1200px', tag: 'wallpaper', link: '#'}};
and place it in html in script tag for example.
As a variant you may do it this way:
var pictures = <?= json_encode($pictures); ?>;

Use php to populate javascript array

All,
I have the following bit of code:
function addPoints() {
newpoints[0] = new Array(41.45998, 87.59643, icon0, 'Place', 'Content to open');
for(var i = 0; i < newpoints.length; i++) {
var point = new GPoint(newpoints[i][1],newpoints[i][0]);
var popuphtml = newpoints[i][4] ;
var marker = createMarker(point,newpoints[i][2],popuphtml);
map.addOverlay(marker);
}
}
There is other code around this to display the marker on my map. However this value is hardcoded. I have a PHP/mySQL database that has lat/long coordinates along with some other values. Say I have like three entries that I want to create markers for. How would I pass the addPoints function the lat/long that I got from my database so I can use it in this function correctly?
I updated my code to look like the following for the addPoints:
function addPoints(num, lat, long) {
newpoints[num] = new Array(lat, long, icon0, 'Place', 'Stuff name');
alert("The newpoints length is: "+newpoints.length);
for(var i = 1; i < newpoints.length; i++) {
var point = new GPoint(newpoints[i][1],newpoints[i][0]);
var popuphtml = newpoints[i][4] ;
var marker = createMarker(point,newpoints[i][2],popuphtml);
map.addOverlay(marker);
}
}
I call this function by doing this:
<script>
addPoints('<?php echo json_encode($num_coordinates); ?>','<?php echo json_encode($lat_coordinates); ?>', '<?php echo json_encode($long_coordinates); ?>');
</script>
It doesn't work though. When I try not to pass it to javascript and just output the lat coordinates for example. I get the following output:
{"1":"40.59479899","2":"41.4599860"}
Which are the correct coordinates in my array. No markers get created though. Any ideas on what to do next or what I'm doing wrong?
An easy and clean way to pass an array from PHP to JavaScript is to simply echo the json_encode version of the array.
$array = array(1,2,3,4,5,6);
echo 'var values = '.json_encode($array).';';
PHP executes on the server before getting sent to the the client. Therefor, if you can do things like this:
newpoints[0] = new Array(<?php echo $lattitude;?>, <?php echo $longitude;?>, icon0, 'Place', 'Content to open');
Where $lattitude and $longitude are values that you pulled out of you database with PHP.
When this page is requested by the client, your php code executes, real values get plugged in where those php tags are making it look like the example you provided, and then it gets sent to the client.
If you want to change these values using JS on the client, or fetch new ones from the server, let me know and I'll add an example of that.
EDIT:
Okay, in light of your comments, it sounds like you've got a few options. Here's one:
When the user selects a category (restaurants, bars, etc) you pass that category as a url parameter and reload either the whole page, or just the map part of it (depends on your set up but might be worth investigating). Your link would look something like this:
http://www.your-domain-here.com/maps.php?category=bars
Maps.php is ready to catch the category using the $_GET array:
$category = $_GET['category']; //'bars'
Your php then grabs the appropriate location data from the database (I'll leave that part to you) and sticks it in a variable that your JS-controlled map will be able to use:
//JS in maps.php - you could add this var to the window object
// if you have separated js files...
var locationCoords = <?php echo json_encode($arrayOfCoordinatesFromDB);?>;
When you page loads on the client machine, it now has an array of coordinates to use for the map ready to go in the locationCoords variable.
Then, depending on which coordinates you need to display on the map, you pass them as arguments to your addPoints() using standard Javascript (nothing tricky here).
That's how I'd do it. Hope that helps!
It is as simple as echoing the php values.
new Array(<?php echo $php_lat;?>, <?php echo $php_long;?>, icon0 etc...
I made a dynamic banner with this javascript array initialization. It works fine when the javascript is embedded in php.
<?php
// This is our php array with URLs obtained from the server
$urlsPHP = ["img/img01.jpg","img/img02.jpg","img/img03.jpg"];
return = "
//...Some HTML...
<script type='text/javascript'>
// Now we use this inside the javascript
var urlsJavaScript = ".stripslashes(json_encode($urlsPHP)).";
//...Some javascript style to animate the banner...
</script>
";
// if we print this:
echo stripslashes(json_encode($urlsPHP));
// We obtain:
// ["img/banner/bak01.jpg","img/banner/bak02.jpg","img/banner/bak03.jpg"]
// This is a good syntax to initialize our javascript array
// if we print this:
echo json_encode($urlsPHP);
// We obtain:
// ["img\/banner\/bak01.jpg","img\/banner\/bak02.jpg","img\/banner\/bak03.jpg"]
// This is not a good syntax to initialize our javascript URLs array
?>

Categories