Pass Arrays from PHP file to JS file - php

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); ?>;

Related

editing an html form with php using ajax

I'm trying to create an update form where the user selects an ID and the rest of the form gets automatically filled with the corresponding data to that ID which would make updating really simple, obviously i'd have to use AJAX but do i really have to write a whole form code inside the PHP and return it in a single statement and then assigning it in a single innerHTML?
Is it possible to run whatever returns from the php file as a javascript, such that i would be able to write a mini scripts to set the innerHTML of each element by itself and without having to reload the whole form's HTML code, just the values inside form elements?
<?php
$myname = "test";
$myage = 22;
echo
'<script>
document.getElementById("name").innerHTML = "$myname";
document.getElementById("age").innerHTML = "$myage";
</script>';
?>
PS i have no experience of AJAX and i can only find the xmlhttp.responseText for returning the output of a PHP script.
It would be better if you return the data structured in some form (e.g.: JSON), then process it with JavaScript.
For example, instead of what you are returning, do something like this:
<?php
$to_return = array(
"name" => "test",
"age" => 22
);
echo json_enconde($to_return);
Then on your page, parse your response, and process it:
data = JSON.parse(response);
document.getElementById("name") = data.name;
document.getElementById("age") = data.age;
If you want to standardize it a little bit more, you could return something like this:
[
{
"target": "name",
"value": "test"
},
{
"target": "age",
"value": 22
}
]
and create a function like this:
function populateForm(data) {
for (var x = 0; x < data.length; x++) {
document.getElementById(data[x].target).innerHTML = data[x].value;
}
}
Then call that function with the JSON response from your PHP.
I would recommand to return an Array in the server side (the php that handles the ajax request). and in the browser side after you get the the respone from the server then you set
document.getElementById("name").innerHTML = $myname;
document.getElementById("age").innerHTML = $myage;

MySQL Query not returning newest results on setInterval

I am having a problem with setInterval in the $(document).ready(function(){}
What I am doing is setting the interval to do is call a PHP script that runs some MySQL queries to check the condition of 4 switches and then updating the screen with the values are in the database like so:
$(document).ready(function(){
setInterval(function(){
<?php require('fetchSwitchStatuses.php'); ?>
$("#switch1").css('background', 'rgb(<?php echo $switchColor1 ?>)');
$("#switch1").html('<?php echo $switchState1 ?>');
$("#switch2").css('background', 'rgb(<?php echo $switchColor2 ?>)');
$("#switch2").html('<?php echo $switchState2 ?>');
$("#switch3").css('background', 'rgb(<?php echo $switchColor3 ?>)');
$("#switch3").html('<?php echo $switchState3 ?>');
$("#switch4").css('background', 'rgb(<?php echo $switchColor4 ?>)');
$("#switch4").html('<?php echo $switchState4 ?>');
},1000);
});
Here is the code for fetchSwitchStatuses.php:
$connect = mysqli_connect("localhost", "root", "root");
mysqli_select_db($connect, "db_name");
$fetch1 = mysqli_query($connect,
"SELECT SwitchStatus FROM Switches WHERE PinNumber = '3'"
);
$fetch2 = mysqli_query($connect,
"SELECT SwitchStatus FROM Switches WHERE PinNumber = '5'"
);
$fetch3 = mysqli_query($connect,
"SELECT SwitchStatus FROM Switches WHERE PinNumber = '6'"
);
$fetch4 = mysqli_query($connect,
"SELECT SwitchStatus FROM Switches WHERE PinNumber = '9'"
);
$i = 1;
while($row = mysqli_fetch_array(${'fetch'.$i}))
{
if($row['SwitchStatus'] == 0)
{
${'switchColor'.$i} = "255, 0, 0";
${'switchState'.$i} = "OFF";
}
else if ($row['SwitchStatus'] == 1){
${'switchColor'.$i} = "0, 255, 0";
${'switchState'.$i} = "ON";
}
else {
${'switchColor'.$i} = "100, 100, 100";
${'switchState'.$i} = "ERROR";
}
$i++;
}
mysqli_close($connect);
When the page is loaded the information is correct, whatever is in the database is what is reflected by the colors on the screen.
When I click on the object to change the value, all of the necessary changes are made and the database is updated. However, the problem arises when the Interval is repeated. The values are switched back to whatever the original values were when the page was loaded. So, although the information is correctly changed in the database, for some reason the colors of the buttons is always reset to the first value read by the queries.
How can I fix this so that the information that is reflected on the screen is accurate?
With AJAX technology you can:
Send a request and get results from server by requesting a page (a .txt .js .html or even php).
So with AJAX you can get result of a page save something to database, get something from data base, you can work with sessions and anything you can do with a php file.
When you send an AJAX request to a see a page(i.e /userData.php?userId=5) the page /userData.php?userId=5 will be executed and its output will be returned.(HTML or just a word ‘yes’ or ‘no’ or ‘you can’t access to this user’s information’).
You can send data to file with POST or GET. But the question is how you can get data from page. Because the result AJAX will give you is what the requested page echoed to page like this
<html>
….
</html>
Or
‘Yes’
Or
<?php echo ‘something’; ?>
So what about getting a row of Date or lots of data? Because the only thing you are getting is a text or maybe a long text.
For that you can use JSON which Is something like nested arrays.
[
{
"term": "BACCHUS",
"part": "n.",
"definition": "A convenient deity invented by the...",
"quote": [
"Is public worship, then, a sin,",
"That for devotions paid to Bacchus",
"The lictors dare to run us in,",
"And resolutely thump and whack us?"
],
"author": "Jorace"
},
…
And this is a string too. But you can get Data in it with $.getJSON in jQuery and you can generate JSON data in server side like this.
<?php
$arr=array(
‘data’=>’ffff’,
‘anotherData’=>array(‘rrrrr’,’sssss’);
);
Echo json_encode($arr);
?>
Json_encode() in PHP gets an array and returns json string of it. And we echo it.
Now we can use jQuery to get Data which will be retrieved from server.
This section if from
Learning jQuery 1.3
Better Interaction Design and Web Development with Simple JavaScript Techniques
Jonathan Chaffer
Karl Swedberg
Global jQuery functions
To this point, all jQuery methods that we've used have been attached to a jQuery object that we've built with the $() factory function. The selectors have allowed us to specify a set of DOM nodes to work with, and the methods have operated on them in some way. This $.getJSON() function, however, is different. There is no logical DOM element to which it could apply; the resulting object has to be provided to the script, not injected into the page. For this reason, getJSON() is defined as a method of the global jQuery object (a single object called jQuery or $ defined once by the jQuery library), rather than of an individual jQuery object instance (the objects we create with the $() function).
If JavaScript had classes like other object-oriented languages, we'd call $.getJSON() a class method. For our purposes, we'll refer to this type of method as a global function; in effect, they are functions that use the jQuery namespace so as not to conflict with other function names.
To use this function, we pass it the file name as before:
$(document).ready(function() {
$('#letter-b a').click(function() {
$.getJSON('b.json');
return false;
});
});
This code has no apparent effect when we click the link. The function call loads the file, but we have not told JavaScript what to do with the resulting data. For this, we need to use a callback function.
The $.getJSON() function takes a second argument, which is a function to be called when the load is complete. As mentioned before, AJAX calls are asynchronous, and the callback provides a way to wait for the data to be transmitted rather than executing code right away. The callback function also takes an argument, which is filled with the resulting data. So, we can write:
$(document).ready(function() {
$('#letter-b a').click(function() {
$.getJSON('b.json', function(data) {
});
return false;
});
});
Here we are using an anonymous function as our callback, as has been common in our jQuery code for brevity. A named function could equally be provided as the callback.
Inside this function, we can use the data variable to traverse the data structure as necessary. We'll need to iterate over the top-level array, building the HTML for each item. We could do this with a standard for loop, but instead we'll introduce another of jQuery's useful global functions, $.each(). We saw its counterpart, the .each() method, in Chapter 5. Instead of operating on a jQuery object, this function takes an array or map as its first parameter and a callback function as its second. Each time through the loop, the current iteration index and the current item in the array or map are passed as two parameters to the callback function.
$(document).ready(function() {
$('#letter-b a').click(function() {
$.getJSON('b.json', function(data) {
$('#dictionary').empty();
$.each(data, function(entryIndex, entry) {
var html = '<div class="entry">';
html += '<h3 class="term">' + entry['term'] + '</h3>';
html += '<div class="part">' + entry['part'] + '</div>';
html += '<div class="definition">';
html += entry['definition'];
html += '</div>';
html += '</div>';
$('#dictionary').append(html);
});
});
return false;
});
});
Before the loop, we empty out so that we can fill it with our newly-constructed HTML. Then we use $.each() to examine each item in turn, building an HTML structure using the contents of the entry map. Finally, we turn this HTML into a DOM tree by appending it to the .
This approach presumes that the data is safe for HTML consumption; it should not contain any stray < characters, for example.

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
?>

Php to return value

EDIT: Check at the end of this for the solution
I am new to php, ajax and all other things :)
My question is: is there a way for a php file to return a value?
I have:
a file "loadImages.php" containing the script to get the paths to images from the database.
an image gallery where I want to load images via ajax.
a database containing the path to the images (/images/image1.jpg, /images/image2.jpg).
4 categories of images.
What i'm trying to do is :
When clicking on a link (example, first category), I want to call via jquery's ajax(), loadImages.php with the category passed via POST (cat0, cat1, cat2, ...)
I want to return the value from this php file for example : <img src="image/image1.jpg" />, so via javascript, I can retrieve this string. Using only return in my php file returns XMLHttpRequest when i'm putting the ajax() function in a variable instead of the string <img>.
Is there a way to do it? Or maybe a better way, as I don't fully understand ajax.
Thank you! Sorry for my bad grammar.
Below is a more precise map of what i'm trying to do.
JavaScript:
var test = $.ajax({
type: "POST",
url: "loadImages12.php",
data: "category=0",
complete: function() {
alert("COMPLETE");
},
error: function (){
alert("NOT LOADED");
}
});
PHP (loadImages.php)
function createThumb() {
if(isset($_POST['category'])) {
$imageQuery = mysql_query("SELECT * FROM t_pictures WHERE p_category = 0");
$thumbHtml = '';
while ($tempImageQueryFetch = mysql_fetch_assoc($imageQuery)){
$thumbHtml .= '<img src="ressources/images/' . $tempImageQueryFetch["p_fileName"] . 'Small.jpg" />';
}
return $thumbHtml;
}
else {
$noCategory = "NO CATEGORY TEST";
return $noCategory ;
}
}
createThumb();
SOLVED
Php File
function createThumb(){
//Mysql request
$someVar = //Result of request
return $someVar
}
echo createThumb()
Javascript
$("#someDiv").load("loadImages.php", {category:0});
An AJAX request to PHP is exactly the same as a normal request for a website. You request data from example.com/foo/bar and in return you receive text. The return statement of PHP has nothing to do with what's returned to the client. Only things you echo or otherwise output will be received by the client. That's the same for normal pages and AJAX requests.
So, to "return" <img src="image/image1.jpg" /> to your Javascript AJAX call, echo that string in PHP.
if you want to use the php file that you already have (loadImages.php) just echo the result of the function:
echo createThumb();
Just make the php script to return the path to thumbnail.
and then do something like this in js
somediv.html('<a href="#" class="thumbnail"><img src="">');
and just use the path returned by the php file for the img src ..

how i can i change the content of a page without refreshing

how i can i change the content of a page without refreshing.I know we need to use hidden frames for this but all the tutorials i have come across teach this only for HTML files what if the content is returned from a PHP file how do i do it in such a case? what should the php file echo or return?
You will have to use Ajax for that, have a look at this tutorial:
AJAX Tutorial
If you use a hidden frame, the content won't be displayed (hence "hidden"), I think you just mean to use an iframe. But this doesn't fit your description of "without refreshing", since you have to refresh the frame.
When loading the PHP file inside the frame, your PHP file just needs to generate HTML the same way you would generate a normal page. It's the same whether the PHP file is loaded inside a frame or not.
I use this method for a lot of my websites and so does Google. If you want to get data from a PHP file and then dynamically update the page you need to "import" the PHP file somehow without the entire page being redirected, or using iframes (which works too but is a lot messier). The way you do this is to import the file as a "javascript" file.
The following code demonstrates a form called "testform" and a text input called "userpost".
When you submit the form, it will import a file, and then update div "outputText" with whatever you entered... and wait for it... all without the page being redirected at all or refreshed!
I have included a lot of extra functions to show how you can access all of your functions on the same DOM unlike if you use frames where you have to use "top.object" or what not
index.html
<html>
<head>
// Get objects by their id. We will use this in the PHP imported file
Get = function(id) {
return (!id) ? null : (typeof id == "object") ? id :
(document.getElementById) ? document.getElementById(id) :
(document.all) ? document.all[id] :
(document.layers) ? document.layers[id] : null;
}
// Formats a string so it does not break in a URL
String.prototype.formatForURL = function() {
var str = escape(this.replace(/ /gi, "%20"));
str = str.replace(/\&/gi, "%26").replace(/\=/gi, "%3D");
str = str.replace(/\//gi, "%2F")
return str;
}
String.prototype.contains = function(str) {
return (!str) ? false : (this.indexOf(str) > -1);
}
Object.prototype.killself = function() {
this.offsetParent.removeChild(this);
}
// Import the script
ImportScript = function(js) {
var head = document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("language", "JavaScript");
script.setAttribute("charset", "utf-8");
// we add the is tag so can delete the "js" file as soon as it executes
script.setAttribute("id", "import_" + head.children.length);
script.setAttribute("src", js + (js.contains("?") ? "" : "?") + "&is=" + head.children.length);
head.appendChild(script);
}
// Get and send value to php file
sendInfo = function() {
var file = "js/myFile.php?userpost=";
file += document.testform.userpost.value.formatForURL();
ImportScript(file);
}
</head>
<body>
<div>
<form name=testform onsubmit="sendInfo(); return false">
<input type=TEXT name=userpost />
<input type=SUBMIT value=Go />
</form>
</div>
<div id=ouputText>
This text will be replaced by what you type
and submit into the form above
</div>
</body>
<html>
js/myFile.php
<?php
// Here you can now use functions like mysql_connect() etc. even exec()
// ANYTHING! Save them into variables and output them as text which goes
// Straight into the javascript! e.g. :
// $con = mysql_connect("localhost", "username", "password");
// if($con) {
// ... code to retrieve data and save into $variable
// }
// print "alert(\"$variable\");"; // this alerts the value in variable
if(isset($_GET['userpost'])) {
$userpost = $_GET['userpost'];
?>
Get("outputText").innerHTML = "<?=$userpost; ?>";
<?php
}
?>
// Clear text area
document.testform.userpost.setAttribute("value", "");
// Remove the file from header after info is changed
Get("import_<?=$_GET['is']; ?>").killself();
If I had typed in "Hello World" into text input "userpost" then
div "outputText" would be filled with the words "Hello World"
deleting what was previously there, and the text input will be cleared
Hidden frames is one design pattern that is a part of the overall AJAX design pattern. This is an extreme high-level overview, but this is essentially how it works:
Javascript in your HTML page makes a request to your PHP script by using an XMLHTTPRequest object, or a hidden frame or iframe. This is usually done asynchronously, so you can continue to work with your HTML page while the request is being made.
The data is returned to your Javascript. At this point, you can then manipulate the page, and update data on the page using various DOM methods.

Categories