This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
So I have an array of records retreived from a database. The array is in the format;
$rows[0]['id']=1;
$rows[0]['title']='Abc';
$rows[0]['time_left']=200;
$rows[1]['id']=2;
$rows[1]['title']='XYZ';
$rows[1]['time_left']=300;
//And so on upto 10-20 rows
What's the best way of transferring this array over to my javascript code? I'd like the javascript to be able to loop through all of the records, and using the 'id' attribute, update the div with that id with some information.
My javascript code is in an external .js file, but i'm able to execute php code in the HTML code of my page. So I could do something like this:
In my_file.js:
var rows=New Array();
In HTML code:
<html>
<head>
<script type="text/javascript" src="js/my_file.js"></script>
<script type="text/javascript">
<? foreach ($rows as $row):?>
<? extract($row);?>
rows[<?=$id;?>]['title']="<?=$title;?>";
//And so on
<? endforeach;?>
</script>
I tend to use a JSON object for this:
On the server side, JSON encode your data: json_encode($data);
On the JavaScript side, I write a function that takes a JSON object as a parameter and unpack it.
When you unpack the object, you can print the array's contents into a <DIV> tag, or where ever you would like on the page (jQuery does a pretty sweet job of this).
If you're doing inline data, I've always been fond of doing
<script type="text/javascript">
window.sitescriptdata = {};
window.sitescriptdata.foo = ( <?php echo json_encode( $structure ); ?> );
</script>
For basic stuff, saves you doing an AJAX callback. Also, if you want to glue data to a DOM node, the "metaobject" way is something I really love.
<div id="foobar">
<div><object class="metaobject">
<param name="data" value="<?php echo htmlentities(json_encode($data), ENT_QUOTES );?>" />
</object></div>
</div>
Now this may not look great, but its an effective way of associating data directly with a DOM node without needing to know the exact unique path to that node. Very handy if you have many many datasets that need to be attached to specific screen elements.
I usually use http://noteslog.com/metaobjects/ plugin for jQuery, but its so simple I have on occasion written it myself ( there was a time I couldn't find the plugin, but new how it worked )
When done, there will be
$("div#foobar > div").get().data.($yourarrayhere)
Visible to your code.
To follow up to your question (and my reply, I ran out of space on the comment reply), here is a very simplified subset of the code I use:
Javascript AJAX handler in jQuery:
$.ajax({
type: "POST",
url: "BACKEND.php",
timeout: 8000,
data: "var1=" + myVar,
dataType: "json",
error: function(){
$("#DIVID").html("<div class='error'>Error!</div>");
},
success: function(jsonObj){
$("#DIVID").html(jsonObj.mydata);
}
});
PHP Array:
$data['mydata'] = $myData;
In an AJAX example like here you can solve this problem on this way:
.php file (ajax return function)
$myArray = array("object_id"=>1, "object_title"=>"Testobject");
return json_encode($myArray);
.js file (javascript function)
...
if(g_httpRequest.readyState == 4)
{
var jsonRes = JSON.parse(g_httpRequest.responseText);
alert(jsonRes.object_title)
}
...
im still fairly new too say maybe this method isnt the most secure, but you can always turn your javascript array into a string and then pass it through the URL for the php to GET.
so:
for(var i=0;i < jsarray.length;i++)
{
var x = jsarray[i];
urlstring += "myvalue[]="+x+"&";
}
document.location.href = "mypage.php?"+urlstring;
and then the php would be:
$phparray = $_GET['myvalue'];
hope that helps
Related
I'm kinda confused how to solve this problem in a right way..
This is jQuery function I intend to use. Runs on 1.7.2 jQuery, PHP 5.2.
$(function() {
var timer = setInterval( showDiv, 5000);
//var categoryid = ;??
function showDiv()
{
$.post("check4_new_data.php?categoryid="+encodeURIComponent(categoryid),
function(response)
{
$('#awaiting').fadeOut(400); //cosmetics, nothing important
$('#posting1').html(unescape(response));
$('#posting1').fadeIn(200);
});
}
});
Question:
There is a PHP variable $categoryid set when PHP page loads and.. this function needs it. So, how to send $categoryid back to jQuery in a right, safest way?
Note:Ive been using cookie as first test to keep categoryid present for PHP, but then all opened (and different) pages started to load up same data (according to latest page visited).
Thx!
Use json_encode;
var categoryid = <?php echo json_encode($categoryid);?>;
json_encode always produces a JavaScript-safe encoding. Even for complex variables and multidimensional arrays, and it's type-safe (for scalars at least).
You could do it like this:
<div id="posting1" data-category="my_category">
...
</div>
This way, your markup and JavaScript can be separated completely. So you can fetch the category for the related post you are trying to refresh:
var category = $('#posting1').attr('data-category');
$.post(
"check4_new_data.php?categoryid="+encodeURIComponent(category),
function (response) {
$("#posting1").html(response);
}
);
You may try this.
json_encode;
var categoryid = <?php echo json_encode($categoryid);?>;
For further details: http://php.net/manual/en/function.json-encode.php
I have built an area on my client's website that displays a song that is currently playing, as parsed from an XML file via PHP. However, my client wants the song to auto-refresh itself instead of him having to manually refresh the page.
I played around with parsing the file using jQuery.get() and also .ajax(), but because of the way the XML file is structured, it seems as though I can only get the artist and the name squashed into one string, or when I try to be specific it only returns [object Object].
I haven't even tried to tackle having the song's length be calculated and then refresh the feed based on that length. I may not seeing as this is apparently such an issue for me.
Any help or general guidance would be greatly appreciated.
Example working PHP code (obviously, non-AJAX):
<?php
$recentlyPlayed = simplexml_load_file('http://publicapi.streamtheworld.com/public/nowplaying?mountName=ABCDFM&numberToFetch=1&eventType=track');
$trackTitle = $recentlyPlayed->{'nowplaying-info'}[0]->property[1];
$trackArtist = $recentlyPlayed->{'nowplaying-info'}[0]->property[0];
echo "<h6>" . $trackArtist . "<span class=\"song-title\">" . $trackTitle . "</span></h6>";
?>
I've tried several different things to get this to work, but it seems the initial obstacle is trying to reference the data in the XML file using the attributes, rather than the node-names. The nodes are all named the same, and it's the attributes that differentiate them. So, as such this code will render correctly, unless the artist/song title are blank, then it renders the third field which is sort of cryptically-named "cue_time_start".
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
<script type="text/javascript">
$(document).ready(function() {
setInterval("songPull()",1000);
});
function songPull() {
$.get(
"http://publicapi.streamtheworld.com/public/nowplaying?mountName=ABCDFM&numberToFetch=1&eventType=track",
"xml",
function(data) {
$(data).find("nowplaying-info").each(function(){
var artist = $(this).find("property").eq(0).text();
var title = $(this).find("property").eq(1).text();
$('body').html("<h1>" + artist + "<small class=\"song-title\">" + title + "</small></h1>");
console.log (artist);
console.log (title);
});
}
);
}
</script>
<body>
</body>
Any guidance, advice or examples of best practices when trying to do this sort of thing would be so very greatly appreciated.
I'm not exactly sure if this is what you want, but you could simply use attribute selectors to extract the data you want out of your XML document.
http://jsfiddle.net/P8dc6/
$.get("http://publicapi.streamtheworld.com/public/nowplaying?mountName=KROXFM&numberToFetch=1&eventType=track",
"xml",
function(data) {
var $nowPlaying = $(data).find('nowplaying-info');
console.log($nowPlaying.find('[name=track_artist_name]').text());
console.log($nowPlaying.find('[name=cue_title]').text());
}
);
Also, never pass a string to setInterval or setTimeout, you can just pass the function reference directly:
setInterval(songPull ,1000);
I am trying to utilize a javascript variable as the key of a PHP array to echo out. Notice the javascript variable id is want I want to use as the key of the PHP array $allNames[].
Is this possible? Without JSON/AJAX? If so please help.
<script type="text/javascript" language="javascript">
$('*[class^="spec"]').mouseover(function(){
var the_class = $(this).attr("class");
var id = the_class.replace("spec", "");
$('#here').html('<?php echo $allNames[id]; ?>'); // here
});
</script>
Many thanks.
You could use AJAX, but it may be wasteful to do so in this case. Try this:
var allNames = <?php echo json_encode($allNames); ?>;
$('[class^="spec"]').mouseover(function() {
var id = this.className.substr(4); // more efficient than previous code
document.getElementById('here').innerHTML = allNames[id];
});
Alternatively, try refactoring your approach. Instead of having this (example)
<div class="spec1">Hover here</div>
Try this:
<div class="spec" data-hover="<?php echo htmlspecialchars($allNames[1]); ?>">Hover here</div>
Then your script could be as simple as:
$(".spec").mouseover(function() {
document.getElementById('here').innerHTML = this.getAttribute("data-hover");
});
You are doing it wrong. in client-side javascript the php has to already contain all of the variables already.
PHP is rendered before the javascript so you cannot create echo statements by javascript
If you want to dynamically generate HTML from the ajax, this can still be possible as the whole point of many javascript libraries such as jQuery is to dynamically modify elements in the Document Object by using selectors.
Yes you can do it with JSON. Just call the PHP file like this
file.php?id=JAVASCRIPT_ID_HERE
Then in that PHP file, just use $_GET['id'] to grab the ID
I am hitting roadblock after roadblock in my quest to get this JSON usable by PHP, so I'm wondering if someone can help me out here.
I have JSON being stored in the variable divisionsJSON:
var divisionsJSON = JSON.stringify(divisions);
Then I try to use .ajax to post with the following:
$.ajax({
url: "divisions.php",
type: "post",
data: divisionsJSON,
success: function(){
alert("success");
$("#result").html('submitted successfully');
},
error:function(){
alert("failure");
$("#result").html('there is error while submit');
}
});
(I copied this from another question on SO, but have nothing in my html with the id="result" - I think I can delete that part [deletion confirmed])
Then, my divisions.php page contains the following:
<?php
$url = "divisions.php";
$json = file_get_contents($url);
$json = utf8_encode($json);
$elements = json_decode($json);
var_dump($elements);
?>
My inexperience with PHP/ajax combined with my frustration with getting this to work has made me try a bunch of different things. So far I've either gotten NULL or nothing when I load divisions.php. My gut tells me that it's a problem with the ajax, but I'm so inexperienced with PHP that I can't say with confidence that my PHP is correct enough to where I should be getting something back. I've tried var_dump, print_r, echo, absolutely nothing is showing up on divisions.php related to the actual PHP/JSON. Any and all help would be greatly appreciated!
Response with updated code:
I am getting NULL with the following php without the utf8 line, and string(0) "" when I added in the utf8 line:
<?php
$json = json_decode(file_get_contents('php://input'));
$elements = utf8_encode($json);
var_dump($elements);
?>
Any ideas?
Edited for full php page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>untitled</title>
<link rel="stylesheet" href="styles/reset.css" />
</head>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="underscore.js"></script>
<script type="text/javascript" src="application.js"></script>
<script type="text/javascript" src="divisions.js"></script>
<?php
print_r($_POST);
?>
</body>
</html>
I've tried multiple lines for the php, print_r($_POST);, json_decode($_POST);, etc. but I'm changing so many things based on what I'm seeing on other SO's and this page that I'm really in a daze.
EDIT: Would this code, which I intended to make an array, not produce JSON? Because it doesn't seem like I'm working with JSON atm.
var divisions = [];
for (var i = 0; i < arr.length; i++) {
if(arr[i].value != "N/A"){
var obj = { "login": arr[i].login,
"value": "http://www.value.net/index/" + arr[i].value};
divisions.push(obj);}
First of all, when dealing with JSON the best approach is to leave it alone as much as possible. Think if it as fragile goods. Anything you do to it could break it.
With that in mind, don't use stringify() and in fact you don't need to as JQuery will detect it and handle it for you (because they know it's fragile).
Second, the option data: in the $ajax() method needs to be given an object. Generally you would do something like this,
data: {mydata:divisionsJSON}
That way you can access the JSON on the backend via
$json = json_decode($_POST['mydata']);
Or, depending on how you have your divisions array set up, you could post it as the object data: is looking for and access it in PHP via $_POST['divisions_key'] = divisions_value; but that makes for all kinds of issues later and hard links the front end to the back end which is very bad (most of the time, exception is below).
Also, if you are expecting a JSON response you'll need to specify that in the original call using the dataType: 'JSON' option so JQuery can handle it appropriately.
$.ajax({
url: "divisions.php",
type: "post",
data: {mydata:divisions},
success: function(response){
$("#result").html(response.message);
},
error:function(response){
$("#result").html(response.message);
}
});
But, before we get too far, that division variable in JS is troubling. Where is that sourced from? Is it a form by any chance? If so, you can use serialize() such that
var divisions = $('#myform').serialize();
This will create key=>value pairs where the key is the name of the form field and the value is (obviously) the value of the field. You can access the values in PHP just as you would normally.
When considering the earlier question about how your array is structured, this is an acceptable case of posting data as the object. If it's a form then the form structure is going to be linked to the backend out of necessity anyway and so the direct use of the object in the data: option is just fine. It's that whole first concept of "leave it alone". The last case here leaves that object alone completely; from the time it leaves the DOM to the time it's received by the handler it's an object 100% of the time.
As #slamborne mentioned in the comment, the correct call is json_decode(file_get_contents('php://input')).
What your call is doing is actually making another call to divisions.php, which is why you're getting NULL back (it doesn't have any data to return to you, as divisions.php doesn't output anything).
This question already has answers here:
using php include in jquery
(2 answers)
Closed 9 years ago.
My problem is that I need to include a PHP file inside a DIV when a button is pressed without the page reloading.
There is even more explanation in the 'Jsfiddle' file.
Below is an included Jsfiddle document.
http://jsfiddle.net/jjygp/5/
Thanks for your time. I am more than happy to provide any information upon request.
See here for your updated jsfiddle
You had marked the change button with a name of Change but were trying to select it with an id of change. Also, you had not told jsfiddle to include jQuery.
Try the following:
<button name="Change" id="Change">Change Div</button>
You are specifying a click function on an id, but no id is set on the button.
You can try with load() function in jquery
http://api.jquery.com/load/
PHP is a server-side script language, which will be executed before a JavaScript script did.
Therefore, you cannot use .load() to execute a PHP code, however, you may try .ajax() to create an AJAX request to the server which can implement the PHP code.
Please see http://api.jquery.com/jQuery.ajax/ if you have trouble on using .ajax().
Note: in .ajax() method, there is a setting called beforeSend, which "can be used to modify the jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object before it is sent". Hope this method helps you in any way.
Then, your JavaScript code will be like this:
$(document).ready(function(){
$("#Change").click(function(){
//doing AJAX request
$.ajax({
url:"include/start10.php",
beforeSend:function(){
$('#myDiv').fadeOut('slow');
},
success:function(data){
// do something with the return data if you have
// the return data could be a plain-text, or HTML, or JSON, or JSONP, depends on your needs, if you do ha
$('#myDiv').fadeIn('slow');
}
});
});
});
You cannot include PHP file with AJAX, but instead the response of the AJAX server-side script, which is the PHP (which has the same effect).
Loading...
The JS file (code):
function ajaxalizeDiv()
{
$.ajax({
type: "get",
url: "/path/to/the/php/you/want/to/include",
data: {
// Anything in json format you may want to include
id: myvarwithid, // descriptive example
action: "read" // descriptive example
},
dataType: "json",
success: onAjax
});
}
function onAjax(res)
{
if(!res || !res.text)
return;
$("#mydiv").html(res.text);
}
And here goes the PHP file:
<?php
$id = (int) #$_GET['id']; // same as in data part of ajax query request
$action = #$_GET['action']; // same as in data part of ajax query request
$text = 'click me';
// Note this is short example you may want to echo instead of die
// You may use not JSON, but raw text. However, JSON is more human-friendy (readable)
// and easy to maintain.
// Note also the array keys are used in the onAjax function form res (response).
die(json_encode(array('text' => $text /* and anything else you want */)));
?>