How to use a php result set from a query in JavaScript - php

I am working on a page that displays all state parks. Something like this:
http://www.comehike.com/outdoors/state.php?country_id=1&state_id=6&state_name=California&country_name=
I have the park data, including lat/lng in my database and I already get that data during the request. What I want to avoid is doing an AJAX call which will query the park data again.
Is it possible for me to just send the PHP result set to the JS somehow and to loop through the parks and display them?
I am already doing something like that by sending the map-center lat/lng so I figured it is doable with a result set.
Thanks,
Alex

This depends on how your pages are setup. If you're using some kind of MVC setup, you need to pass the variable to your view first. Or if it's a single page, just retrieve the PHP above and pass it as a variable.
<?php
$parkData = $model->getData(); //make sure this returns an array or an object array or something
$parkDataJson = json_encode($parkData);
?>
//in your view
<script type='text/javascript'>
let parkData = <?php echo $parkDataJson ?>;
//now you have a JSON array available for your use
</script>

Related

Showing progress bar while fetching data [duplicate]

I have this while loop, that basically loops through a lot of records in a database, and inserts the data in another:
$q = $con1->query($users1) or die(print_r($con2->errorInfo(),1));
while($row = $q->fetch(PDO::FETCH_ASSOC)){
$q = $con2->prepare($users2);
$q->execute(array($row['id'], $row['username'])) or die(print_r($con2-errorInfo(),1));
}
(The script has been shortened for easy reading - the correct one has a much longer array)
I would like to do this more graphical, and show a progress bar on how far it has went, instead of just seeing a page loading for a few minutes (there are ~20.000 rows in this one - I have tables with much more data)
I get that you could get the total number from the old database, and I could also easily put the current number into a variable like this:
$q = $con1->query($users1) or die(print_r($con2->errorInfo(),1));
$i = 0;
while($row = $q->fetch(PDO::FETCH_ASSOC)){
$q = $con2->prepare($users2);
$q->execute(array($row['id'], $row['username'])) or die(print_r($con2-errorInfo(),1));
$i++;
}
But now I need to actually fetch $i and display it - or something like it.
How is this "easily" done?
The code for the progress bar can either be in the same document as the while loop, or in another if easier.
You can do a "master" file that does an ajax to this first file to run a single query. You could get all the entry id's in this master file, and then pass it as a parameter to the second file that does a single query. Store these ids in a javascript array.
Create a function that does this, and when the first ajax is done, move to the second element of the id array, and do another ajax with a second parameter. That's how magento imports are done by the way :)
If you need further explanations, let me know, I tried my best to explain, but may have not been perfectly clear.
// you generate this javascript array using php.
// let's say you have all the ids that have to be processed in $Ids php array.
Ids = [<?php echo implode(',', $Ids); ?>];
function doAjax(i) {
$.ajax({ // using jquery for simplicity
'url': "ajax.php?id=" + Ids[i],
}).done(function(){
if ( i >= 0 ) {
// at the point you know you're at ((Ids.length-i)/(Ids.length) * 100) percent of the script
// so you can do something like this:
// $('.progressbar').css('width', ((Ids.length-i)/(Ids.length) * 100) + '%');
doAjax(i-1);
}
});
}
doAjax(Ids.length); // starting from the last entry
So, just to explain what this does. It starts by declaring a global javascript array that has all the ids that will need to be changed.
Then I declare a recursive ajax function, this way we can make sure that only one ajax runs at any single time (so the server doesn't blow up), and we can have a fairly accurate progress. This ajax function does the following:
Sends a request to ajax.php?id=xxx - where xxx is one of the ids in the javascript array.
In the file, we get the id ($_GET['id']), you take it from the old database, and insert it in the new one. This is only for one entry.
when the ajax is done, it goes to the done() function. Since we start the doAjax() function with the last element, we do the next iteration doAjax(i-1). Since we're going backwards in the array, we check if the key is positive. If it's not, the script will stop.
That's about it.
You can't. The php is first interpreted by the server and then send to the user as HTML-Code.
The only possibility would be creating a html-page and call the php-script with AJAX.

Pass a database value to JavaScript

I retrieved all of my friends' names which are currently online using MySQL joins and PHP.
Now I want to insert their names inside JavaScript for chatting with them.
Friend1
Friend2
I am unable to do this. Because I don't know how to call JavaScript inside PHP or viceversa.
while($get_usernames=mysql_fetch_array($get_users_query)) {
echo '<br>'.$get_usernames['username'];
}
I want to show each of $get_usernames['username'] as Friend1, Friend2, inside JavaScript
You can use AJAX to call a php page and get value from that.
Call the php page and after querying simply return value using echo. You can get that value using responseText in javascript
http://www.tizag.com/ajaxTutorial/ajaxphp.php
If you want to place some PHP variable inside javascript, a simple way of doing it is by simply using the php loop inside your page to create the a tags.
Something like this:
$aTagList = "";
while($get_usernames=mysql_fetch_array($get_users_query)) {
$aTagList .= "<a href='javascript:void(0)' onclick='javascript:chatWith(\"".$get_usernames['username']."\")>".$get_usernames['username']."</a>";
}
Then echo the $aTagList wherever you need it in the page with some inline code.
<?php echo $aTagList; ?>
Not sure if I got all the escaping correct, but it should give you the right idea.
Something like:
<?php
$aUsernames = array();
while($get_usernames=mysql_fetch_array($get_users_query)) {
array_push($aUsernames, $get_usernames['username']);
}
foreach($aUsernames as $name) {
?>
<?= $name; ?>
<?php
}
?>
Using AJAX is much neater ofcourse, but this will suffice if it is all in one PHP file.
Also I would like to encourage you to move to PDO or Mysqli since mysql functions are deprecated.

Updating multiple page elements without refreshing the page using PHP & jQuery

I have a PHP page that uses jQuery to let a user update a particular item without needing to refresh the page. It is an availability update where they can change their availability for an event to Yes, No, or Maybe. Each time they click on the link the appropriate jQuery function is called to send data to a separate PHP file (update_avail.php) and the appropriate data is returned.
Yes
Then when clicked the params are sent to a PHP file which returns back:
No
Then, if clicked again the PHP will return:
Maybe
It all works fine and I'm loving it.
BUT--
I also have a total count at the bottom of the page that is PHP code to count the total number of users that have selected Yes as their availability by simply using:
<?php count($event1_accepted); ?>
How can I make it so that if a user changes their availability it will also update the count without needing to refresh the page?
My thoughts so far are:
$var = 1;
while ($var > 0) {
count($day1_accepted);
$var = 0;
exit;
}
Then add a line to my 'update_avail.php' (which gets sent data from the jQuery function) to make $var = 1
Any help would be great. I would like to stress that my main strength is PHP, not jQuery, so a PHP solution would be preferred, but if necessary I can tackle some simple jQuery.
Thanks!
In the response from update_avail.php return a JSON object with both your replacement html and your new counter value.
Or to keep it simple, if they click "yes" incriment the counter, if they click No or maybe and their previous action wasn't No or Maybe decrease the counter.
Assuming your users are logged into the system I'd recommend having a status field in the user table, perhaps as an enum with "offline", "available", "busy", "unavailable" or something similar and use the query the number of available users whilst updating the users status.
If you were to do this you'd need to include in extend your methods containing session)start() and session_destroy() to change the availability of the user to available / offline respectively
The best way is the one suggested by Scuzzy with some improvements.
In your php, get the count from the database and return a JSON object like:
{ count: 123, html: 'Yes' }
In your page, in the ajax response you get the values and update the elements:
...
success: function(data) {
$("#linkPlaceholder").html(data.html);
$("#countPlaceholder").html(data.count);
}
...

How can I set a session for multiple links that I want to disable?

piece of file1.php:
Add this to DB
This takes the user to a page where the data gets inserted into the database.
file2.php :
$clicked = $_GET['addid'];
$_SESSION['clicked'] = $clicked;
// data gets inserted
header("Location: file1.php?id=$clicked");
But I have got multiple pages (like: file1.php?id=1 | file1.php?id=2 | file1.php?id=3 etc.).
Can the session variable handle multiple numbers? Is there any way to do this?
Any help appreciated.
(P.S.: Currently I am using the GET method to disable the links, but I think SESSION is more reliable.)
(P.P.S.: I need this for a voting script.)
To hold more data in one session variable, you need to create a multi-dimensional array which will hold multiple against $_SESSION['checked']. You can do this like:
$clicked = (int)$_GET['addid'];
$_SESSION['clicked'][$clicked] = true;
// data gets inserted
header("Location: file1.php?id=$clicked");
(also, you should be sanitizing $_GET['addid'].
Then to check if it is set, you can use array_key_exists:
if(array_key_exists($clicked,$_SESSION['clicked'])){
echo "this button should be disabled!";
}
I am not sure I understood right your question, but if it is how to send an array of data with the same id via an http request you can use this syntax for the url
file.php?arr[]=val1&arr[]=val2&arr[]=val3
from your php code you would access the values as a regular array
Can the session variable handle multiple numbers? Is there any way to do this?
The session variable can store an array
$_SESSION['clicked'] this session variable can store one value at a time.
If you want use 2 dimension array to handle multiple values.
$clicked = $_GET['addid'];
Ex: $_SESSION['clicked'][$clicked];
firstly concatinate all the ids with comma in a string as $var = 1,2,3,4 and then pass it using GET.
Then there on that page you can explode it from comma and can store it in array and then foreach loop for the array will do it for you. Hope it works.

Reading JSON arrays with jQuery/JS

Alright, this pretty much goes along with my previous question. I'm still trying to figure out how to display data from an array which is created by a PHP file- using JS/jQuery. I'm working on a points system for ZetaBoards, and I've currently got it set up here. (Points will be displayed below the users post count once I get this working.. you guys can't see the +/- functions which work fine, haha. :p )
http://outlinetokens.hostei.com/scripts/output.php
So, for each user- I can get their user ID, I just don't know how to check if their name is in the array. (and if it is, display their points) I'm guessing I'll have to do something like this? Here's the chunk of the code that deals with this.. you'll see where I need help.
if (location.href.match('/topic/')) {
$.getScript('http://outlinetokens.hostei.com/scripts/output.php', function () {
$('td.c_username a.member').each(function () {
value = 0;
u = $(this).attr('href').split('profile/')[1].split('/')[0];
// this is where I need to do the 'search.' Just a basic guess.. help. D:
if (values.uid == u) {
value = values.points;
}
$(this).parents('tr').next().find('dl.user_info').append('<dt>' + options.system_name + ':</dt><dd class="Points"><span id="point_total">' + value + '</span></dd>');
});
})
}
...in case the code tag screwed it up:
http://ryjoe.pastebin.com/raw.php?i=0bsZNnVq`
Thanks! (:
Why are these lines in your data formatted like this:
{'uid','342230','name','Joe','points','250'}
instead of this:
{'uid': '342230', 'name': 'Joe', 'points','250'}
If that was formatted correctly you could access the properties.
I'm not sure if I'm reading your question right, but you can load JSON with jQuery, instead of a script.
If then, the array is one of usernames, you can just use response.hasOwnProperty(username) or similar to check if it's in the JSON object you got back
Also, in php use json_encode
You want JQuery.parseJSON. Load the data string, parse it, and assuming its valid JSON, it will become a JS object. Then just access the members in the usual way.

Categories