using for loop value from javascript with php variable - php

I have this code that executes a for loop in javascript with a php array inside of it. Is there anyway I can use the variable for the loop inside of the php variable for example. This is all inside of php.
echo '<script>
for (var i =0; i<4;i++){
alert("hey"'.$phparr[i].');
}</script>';
I know this will not work because the $phparr is a php variable while the i is a javascript variable is there anyway I can do this?

Try:
<script>
var phparr = <?php echo json_encode($phparr); ?>;
for (i in phparr){
alert("hey" + phparr[i]);
}
</script>
PHP is a server side language which means it executes before it reaches the client (browser).
JavaScript is a client side language which means it is executed in the browser (client side).
The best tool for a new web developer is Google search.
Learn how to search effectively.

You're almost there. In order to access the php array in javascript, you first have to echo out the php array into a javascript array. Try:
$phparr_imploded = implode(',',$phparr);
echo '
<script>
var arr = ['.$phparr_imploded.'];
for (var i =0; i<4;i++){
alert("hey"+arr[i]);
}
</script>
';
If your php array is coming from a database, or contains special characters that javascript may misinterpret, make sure to sanitize before outputting.
Are the objects in your php array strings? If so, you need to surround the objects with escaped quotations BEFORE the implode.
for($i=0; i<count($phparr); $i++){
$phparr[i] = '"'.$phparr[i].'"';
};

How about storing the PHP array in a Javascript variable and looping through as kpotehin suggests?
<script>
var i = 0, name;
var myArr = <?php echo json_encode($my_array); ?>;
while (name = myArr[i++]){
alert("hey " + name);
}
</script>

You should make it this way:
var arr = ["<?php echo implode('","',$array); ?>"];
for (var i =0; i<4;i++){
alert("hey"+ arr[i]);
}

Your basic problem is that you are forgetting that the PHP code and the JavaScript code do not execute at the same time. The PHP runs to completion, outputing HTML and JavaScript. Then the browser runs the JavaScript. If the JavaScript needs dynamic access to data in a PHP variable (including an array), then the PHP needs to generate JavaScript declaring the data in a JavaScript structure. That is what all the other answers are doing.

Related

Solution to use a javascript function with data coming from a database

I was wondering if there is a solution to use a javascript function with PHP variables which i'm getting from a database. I know that PHP is a server language and javascript, a client language but i'm actually facing that problem. Maybe somebody can help me ?
I have points' GPS coordinates : "latitude" and "longitude" saved in my database and I get them by a function in PHP which returns me a PHP tab with th data in it.
Then I would like to insert the different points in a Google map with this javascript function :
function afficherPoint(latitude, longitude) {
var point = new google.maps.LatLng(latitude,longitude);
var optionsMarqueur = { position: point, map: map, title: "test" }
var marqueur = new google.maps.Marker(optionsMarqueur);
}
Thanks in advance
You can post the variables directly onto JavaScript (not the other way around), such as:
<?php
$name = "John";
?>
<script>alert("My name is <?php echo $name; ?>");</script>
Or if it's a dynamic thing, you can use AJAX.
If you are using jQuery, check this documentation: jQuery AJAX
You can call out to a PHP Script, and get new variables and do anything with them.
Just output the variable with PHP.
<?php
$myVar = 'I am a variable';
echo '<script>
var stuff = "'.$myVar.'"
</script>';
Then you can use the variable in javascript
You could render your javascript using PHP.
You could have php define global JS variables, and you can then access them using javascript in a seperate file,
You could have your javascript asyncronously load the data from your webserver
Yes, you can use php in javascript functions. A very basic example
var aVar = "<?php echo $aVar; ?>"
you can use ajax to this project :
This tutorial from google
you can try
https://developers.google.com/maps/articles/phpsqlinfo_v3

Passing value to PHP variable inside script

I have some PHP code inside the script so I need
the JavaScript value as a PHP variable, as follows:
<script>
;
var js_var = 123;
var php_var = <?php js_var ?>;
alert(php_var);
;
</script>
Using jQuery to send the value to a PHP page will return the value but not as a PHP variable:
$.get("page.php", {js_var_name: js_var}, function(data) {alert(data)});
I tried also all jQuery AJAX functions: load(), post() and the ajax() method, none of them pass back the value of PHP as above requested.
Is it possible to implement the above with jQuery?
Likely you have a syntax issue with :
var php_var = <?php js_var ?>;
Unless you used define() your php variable should start with $ and you need to echo it so that it gets printed to the page
var php_var = <?php echo $js_var ?>;
If you are assuming that php will read the prior javascript js_var=123 it won't. Javscript is a client side language and php is server side.
You cannot simply mix PHP and JavaScript. The former is executed on the server, the latter on the client, namely in the user's browser. In order to hand a value from PHP to JavaScript you need to output JavaScript code via PHP or do a AJAX-Request to a PHP-Script, as you tried. When using AJAX, it is the easiest solutions to have PHP script that returns a JSON string. When calling this script using $.get() the result will be stored in a JavaScript variable and you can access all the values from there.
Take a moment and a deep breath...and then start thinking about your scopes again.

How to combine PHP and Javascript together?

I have a function in my Javascript script that needs to talk with the PHP to get the data in my database. But I'm having a small problem because I start the PHP in the for loop in Javascript, and then inside that for loop I get the data in my database. But the pointer in the for loop inside the PHP code is not working.. I guess the problem is in escaping? Or maybe it's not possible at all.
Here's my code:
(function() {
var data = [];
for(var i = 0; i < 25; i++) {
data[i] = {
data1: "<a href='<?= $latest[?>i<?=]->file; ?>'><?= $latest[?>i<?=]->title; ?></a>", // The problems
data2: ....
};
};
});
I think you are confused, you are trying to use a variable of javascript in php.
You cannot do this:
<?= $latest[?>i<?=]->file; ?>'
Which expands to:
<?php
$latest[
?>
i
<?php
]->file;
?>
how can you possibly know the value of i, if i is a variable generated in the client side?, do not mix the ideas, i is defined in the browser and the php code is on the server.
You may want to consider using PHP to output the JavaScript file, that way the PHP variables will be available wherever you want them.
The following links better explain this.
http://www.givegoodweb.com/post/71/javascript-php
http://www.dynamicdrive.com/forums/showthread.php?t=21617
1.Pass the javascript variable to the URL to another php page.
window.open("<yourPhpScript>.php?jsvariable="+yourJSVariable);
2.Then you can use this variable using $_GET in the php script.
$jsVaribleInPhp=$GET['jsvariable'];
//do some operation
$yourPhpResult;
3.Perform any server side operation in the Php and pass this result.
header("Location:<your starting page>?result=".$yourPhpResult);
4.Redirect back to the page you started from thus passing the result of PHP.
Php and Javascript have different roles in web development.
This task can also be performed if there's a php script and js in the same page. But that I leave for the readers to work it out.
Hope this helps!!

increment php variable in javascript function

Can anyone tell me how to increment a php variable inside a javascript function.I have a javascript function which is called for every 3 seconds inside this function i need to increment the php variable.
<? php $k =0?>
function slide()
{
//increment $k
var j =<? php echo $k++; ?>//when I do this k is not incremented
}
Can anyone tell me where I went wrong?Is their any other alternative to do this?
Thanks,
Shruti
Short answer: you don't.
Longer answer: PHP runs and only when the page is first loaded. This code is executed on the server.
Javascript on the other hand is executed after the page has finished loading, inside the browser on the client's computer.
Maybe someone can give some advice if you tell us what exactly are you trying to accomplish.
PHP is run on the Server, Javascript is client side. What I think you want is a way to increment the JS value using Javascript not PHP.
The users never see php, so there is no incrementation happening.
You need to have a javascript function (clock) that keeps track of your 3 seconds, and then increase the value of your javascript var j every elapsed period (if I understood your questions correctly).
PHP is serverside, Javascript is clientside. You can't mix apples and oranges and expect bananas. Two things work in a different way. Use JS if you need JS variable incremented.
You need to increment the variable before you print it:
<?php echo ++$k; ?>
You can return k from php and increment it in Javascript. Have your code like this:
<script>
<?php $k=5; echo "var k=$k;\n";?>
function slide()
{
//increment k
var j = k++; //k is incremented ONLY in javascript and j get's the k's value
}
</script>
//You can do something like this:
<?php
$options= array('option1', 'option2','option3','option4');
?>
/* in the same file you can convert an array php into an array javascript with json_encode() php function*/
<script>
/*In this way you can read all the javascript array from php array*/
var options_javascript =<?php echo json_encode($options); ?>;
/*And you can increase javascript variables. For example:*/
for(var i =0; i<options_javascript.length; i++ ){
options_javascript[i];
}
</script>

JSON use in Javascript

I have been misinterpreted. I have created a JSON Object in PHP. I just need access to that object in Javascript. That is all.
I just learned that many of my problems can be solved by using JSON. Now learning how to use JSON is another problem, though. ;-)
Suppose this is the code in PHP:
$row = array()
while ($row = mysql_fetch_object($result)
{
$data[] = $row;
}
$javascriptFriendlyData = json_encode($data);
Now how do I access the $javascriptFriendlyData in javascript.
I tried using JQuery but I can't really figure out much...
If it helps, the JSON Data structure is somewhat like this:
[{"aid":"1","atitle":"Ameya R. Kadam"},{"aid":"2","atitle":"Amritpal Singh"}...
]
Try this:
<script>
<?php
echo 'var data = '.$javascriptFriendlyData;
?>
// now the JSON data is stored in the data variable
console.log(data);
</script>
I'm assuming you are running PHP in the HTML template here:
<html>
<head>
<script><?php echo 'var data = '.$javascriptFriendlyData; ?></script>
<script src="some_js_file.js"></script>
</head>
<body>
etc...
In the some_js_file.js, you can now access the data variable.
If it's an array of simple data as you describe, there is little reason to eval() it, but you might consider it anyway.
From the official JSON documentation:
var myObject = eval('(' + myJSONtext + ')');
Now you can use it like any other Javascript object.
If you are creating the JSON encoded data in your PHP script and echoing in your JavaScript, you don't even have to call eval because it is already in a native JavaScript format.
So taking your code...
$row = array()
while ($row = mysql_fetch_object($result)
{
$data[] = $row;
}
$javascriptFriendlyData = json_encode($data);
Then, in your Javascript code you can do something like...
<script type="text/javascript">
var data = <?php echo $javascriptFriendlyData; ?>;
</script>
Then when the page is rendered, the data is already parsed and ready to use. It is when you are handling AJAX requests that return data that it needs to be evaluated. Otherwise, it is no different then using JavaScript notation inline.
eg:
<script type="text/javascript">
var somevar = [{objVar1:"SomeVal"},{objVal2:"SomeVal2"}];
</script>
If you are trying to have your JavaScript in a separate file, then you will need to set this variable in your JavaScript before you load your JavaScript file or run the JavaScript file through the PHP interpreter.
JSON is just a notation for Javascript data. Which means you can have this kind of JS code :
var data = [{"aid":"1","atitle":"Ameya R. Kadam"},{"aid":"2","atitle":"Amritpal Singh"}];
Which will just put your data in the data Javascript variable.
Considering that [] symbolize an array, and {} symbolize an object, you can use this to access the title property of the first element of the data array :
alert(data[0].atitle);
And you'll get
Ameya R. Kadam
And, to loop over each elements of the data array, you can use something like this :
var i;
for (i=0 ; i<data.length ; i++) {
alert(data[i].aid + ' : ' + data[i].atitle);
}
(Absolutly no need for jQuery for such a task, btw)
If your array is in a variable called data:
$.each(data, function(){
alert(this.aid);
alert(this.atitle);
});
var arr = [{"aid":"1","atitle":"Ameya R. Kadam"},{"aid":"2","atitle":"Amritpal Singh"}];
$.each(arr, function() {
alert(this.aid)
alert(this.atitle)
})
Or
var arr = [{"aid":"1","atitle":"Ameya R. Kadam"},{"aid":"2","atitle":"Amritpal Singh"}];
$.each(arr, function(i,o) {
alert(o.aid)
alert(o.atitle)
})
I have found that the JSON.org Json2.js library to come in handy for going from JSON to JS and back from JS object to JSON. For example, instead of:
var obj = eval('(' + jsonString + ')');
with the JSON.org library you use:
var obj = JSON.parse(jsonString);
You can also specify a second parameter that allows you to work with the results of the JSON being revived as an object.
To go back to a JSON string just call:
var jsonString = JSON.stringify(obj);
This also takes optional arguments to help control JSON string creation.
JSON basicalle represents a Data Structure right, so essentially it's an Object, or instance of a Class, so to use it you do this:
var MyJSonObject = eval("(" + jSonString + ")");
UPDATE
hey Amit, you can't access PHP objects from javascript. What you have to do is somehow construct the JSON string in PHP, but then write it out to the client. I'm not sure how you'd do it in PHP, but this how you'd do it in ASP. The idea is the same, the syntax will be different in PHP.
<html>
<head>
<script type="text/javascript">
var MyObject = eval("(" + <%= Response.Write(strServerSideVariable) %> + ")");
</script>
</head>
<body>
</body>
</html>
Note that in ASP/.NET the tags "<% %>" denote server side, not client side, code. This is what you have to do with PHP amit
It's worth noting that some browsers now provide a set of native functions for JSON decoding and encoding: JSON.parse() and JSON.stringify(). They are safer than using the eval() function and only works if the JSON data is well-formed, whereas eval() would evaluate things like the following:
{
'hello': (undefined
? 'world'
: ('number ' + Math.floor (40.235)))
}
What's wrong with that? The JavaScript value `undefined' is not available in JSON (only true, false, null, strings and numbers are allowed); single quotes are used everywhere when only double quotes are valid in JSON; you can't call JavaScript functions or perform string concatenation in JSON.
Obviously the last one is a big problem because you could receive some malicious JSON, possibly a value from a form input, that attempts to tamper with things. So when possible, use JSON.parse() and JSON.stringify()...because eval() is dangerous.
Edit:
I misread the original post. If you have a JSON object in PHP and you want to use it in JavaScript, you would need to convert the JSON object to a string and pass it on to JavaScript. The only way to do that would be to make your JavaScript code actually ask for the newly created JSON string in the first place. PHP would return a string, JavaScript would use eval() or JSON.parse() on the string, and you'd have your object in JavaScript. I'm not sure if there is a non-AJAX way to do this without making your JavaScript files into PHP files, setting the Content-Type header, etc., but I know that AJAX would work in this situation.

Categories