I have
index.php
<select id="year_list" name="year_list" onchange="check_year_event('year_list', 'event_list');" > . . . </select>
<select id="event_list" name="event_list" onchange="check_year_event('year_list', 'event_list');" > . . . </select>
.
.
.
<?php
function checkYearandEvent($year, $event) {
$year_event = mysql_query("SELECT * FROM year_event WHERE year = '$event' AND event = '$event'")
if (mysql_num_rows($year_event) > 0) {
// do this
}
}
?>
myscripts.js
function check_year_event(year_id, event_id) {
var year = document.getElementById(year_id).value;
var event = document.getElementById(event_id).value;
// call PHP function (but I don't know how): checkYearandEvent(year, event);
}
My question is how do I call the PHP function every time the user changes the value of any of the select element.
You need to use ajax. There is a basic example:
myscripts.js
function AjaxCaller(){
var xmlhttp=false;
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(E){
xmlhttp = false;
}
}
if(!xmlhttp && typeof XMLHttpRequest!='undefined'){
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}
function callPage(url, div){
ajax=AjaxCaller();
ajax.open("GET", url, true);
ajax.onreadystatechange=function(){
if(ajax.readyState==4){
if(ajax.status==200){
div.innerHTML = ajax.responseText;
}
}
}
ajax.send(null);
}
function check_year_event(year_id, event_id) {
var year = document.getElementById(year_id).value;
var event = document.getElementById(event_id).value;
callPage('file.php?year='+year+'&'+'event=+'+event,document.getElementById(targetId));
}
file.php
<?php
function checkYearandEvent($year, $event) {
$year_event = mysql_query("SELECT * FROM year_event WHERE year = '$event' AND event = '$event'")
if (mysql_num_rows($year_event) > 0) {
// do this
}
}
echo checkYearandEvent($_GET['year'], $_GET['event']);
?>
You won't be able to do this in the way you might be expeting to. PHP is executed on the server, before the browser receives the HTML. On the other hand, JavaScript runs in the browser and has no knowledge of the PHP (or any other server side language) used to create the HTML.
To "call" a php function, you have to issue a request back to the server (often referred to as AJAX). For example, you could have a checkYear.php script which checks the event and returns some HTML indicating whether the check succeeded. When the HTML fragment gets back to the JavaScript, you inject it into the page.
Hope this helps!
JavaScript is a client side language, PHP is a server side language. Therefore you can't call PHP functions directly from JavaScript code. However, what you can do is post an AJAX request (it calls a PHP file behind the scenes) and use that to run your PHP code and return any data you require back to the JavaScript.
Basically, you are mixing server-side (PHP) and client-side (JS) scripting.
It is however possible - thanks eg. to AJAX. Because you was not specific about what do you exactly need to be done after the select box changes, I can only point you to some resources and propose following:
learn and start using jQuery (jquery.com) - it will help you get started and maintain cross-browser compatibility,
learn how to make AJAX requests (eg. in the function you just were firing when onchange event was fired) - eg. using .post() jQuery function,
learn how to return data from PHP (eg. using json_encode() in PHP, but raw HTML is also ok) and use it in JS,
There may be many ways to do this. The one I prefer, is using MooTools Request object.
For example, you have a script called ajaxCallable.php, which receives thru $_REQUEST variables some parameters, then you do (in the Javascript side):
function check_year_event(year_id, event_id) {
var year = document.getElementById(year_id).value;
var event = document.getElementById(event_id).value;
var myRequest = new Request({method: 'get', url: 'ajaxCallable.php'});
myRequest.send('yearVar=' + year + '&eventVar=' + event);
}
then, your ajaxCallable.php will be able to access the variables: $_REQUEST['yearVar'] and $_REQUEST['eventVar'].
I was working on a project this week and came up with an easy way to call a php script from an onclick(). It goes like this.
I define an onclick() call in this case on a div called "sidebarItem"…
<a><div class="sidebarItem" onclick="populate('#content', 'help', 'open')">Click me for new content</div></a>
Then I made a simple little JS function that loads an external file into the target container…
function populate($container, $page, $item){
$($container).load('cyclorama/includes/populate.php?$page='+$page+'&$item='+$item);}
Then I write a small php file that gets the $page and $item, queries the database and returns the new content.
<?php
$page = $_GET['$page'];
$item = $_GET['$item'];
$getContentQuery = "SELECT content FROM myTable WHERE page='".$page."' AND item='".$item."'";
$content = mysql_query($getContentQuery, $db);
$myContent = mysql_fetch_assoc($content);
echo $myContent['content'];?>
The php script echoes the new content and it's loaded into the container. I think there are a lot of places this could serve. I'd be interested in finding out if there are any obvious reasons NOT to do this. It doesn't use AJAX just javascript and php but it's fast and relatively easy.
Related
I have an AJAX call on a loop, set to 1000 miliseconds.
The PHP script is simple, it just puts some information (a number) into a session variable. Yesterday I've recived an email from my hosting provider (HostGator), which states that I've been using 75%+ of CPU on shared hosting. After looking the logs, I've found that the problem is in that AJAX call. Here is the code:
PHP (ajax.session.php):
<?php
session_start();
$movieID_e = $_POST['id'];
$state = trim(strtolower($_POST['status']));
if ($state == 'playing') {
if (empty($_SESSION[$movieID_e])) {
$_SESSION[$movieID_e] = 1;
}
else {
$_SESSION[$movieID_e]++;
}
}
echo $_SESSION[$movieID_e];
?>
Javascript:
function interval(func,wait,times){
var interv = function(w, t){
return function(){
if(typeof t === "undefined" || t-- > 0){
setTimeout(interv, w);
try{
func.call(null);
}
catch(e){
t = 0;
throw e.toString();
}
}
};
}(wait,times);
setTimeout(interv, wait);
};
var watched = (function() {
var executed = false;
return function () {
$.post('ajax.session.php',{id:'<?php echo encrypt($id); ?>',status:'none'},function(result) {
if (result == 1000) {
if (!executed) {
executed = true;
var highlightad = introJs();
highlightad.setOptions({
steps: [
{
element: '#advertisment1',
intro: 'test',
position: 'bottom'
},
{
element: '#advertisment2',
intro: 'test2',
position: 'left'
}
]
});
highlightad.start();
}
}
else {
executed = false;
return false;
}
});
};
})();
interval(function(){watched()},1000,3000);
Explanation of JS:
function interval() -> Alternative to setInterval(), taken from thecodeship.com
function watched() -> AJAX request to file ajax.session.php shown above. If the result is 1000 then it highlights a part of a website using Intro.JS.
interval(function(){watched()},1000,3000); -> repeat watched() every 1000ms, max. number of repetitions is 3000 times.
Note that PHP script (ajax.session.php) is also called by AJAX from another script, also with function interval() every 1000ms.
I am using the interval() every second to count the number of seconds that past in a video player.
Do you have any suggestions on how to prevent CPU overload with the following script?
What server stats do you have? I think the problem is, that you have too much traffic for a weak server. Also of course 1second intervals for ajax calls are tooo often. Check your console, you will see that most of them will get timedout.
Sessions will be server side, so it will use servers resources. If you would convert your script to cookies, then the data will be stored in users browser. Also you could use $.cookie jQuery plugin to easily read the cookies via JS, so no need to ajax call.
Also, I would not recommend to use sessions at all, unless making some highly secure login system. I would recommend to use memcache to store temporary data.
Also, I'm pretty sure your JS could use optimization, because on first look I didn't see that you would check if one ajax call is active already. So it wouldn't ajax call before the last call was finished. Otherwise you can imagine the pointless ajax calls going to the server, where 50% of them get timedout.
I'm very new to PHP/Ajax/Html so here's my baby problem (I'm making a radio station site),
test.php queries my server for the currently playing song name.
listen.php displays this song name in the 'refreshTitle' div tag.
When my station changes song there is a 30-ish second delay, so what I want to do is get the song title every second and compare / delay the update of the display if the title is different to what is actually being heard, easy peasy right?! Here is listen.php:
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
function get_XmlHttp() {
// create the variable that will contain the instance of the XMLHttpRequest object (initially with null value)
var xmlHttp = null;
if (window.XMLHttpRequest) { // for Firefox, IE7+, Opera, Safari, ...
xmlHttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) { // for Internet Explorer 5 or 6
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlHttp;
}
function ajaxrequest(php_file, tagID) {
var request = get_XmlHttp(); // call the function for the XMLHttpRequest instance
// create pairs index=value with data that must be sent to server
var d = new Date();
var t = d.toLocaleTimeString();
var the_data = 'test=' + t;
//append time purely for testing to make sure text updates
request.open("POST", php_file, true); // set the request
// adds a header to tell the PHP script to recognize the data as is sent via POST
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(the_data); // calls the send() method with datas as parameter
// Check request status
// If the response is received completely, will be transferred to the HTML tag with tagID
request.onreadystatechange = function () {
if (request.readyState == 4) {
document.getElementById(tagID).innerHTML = request.responseText;
}
}
}
setInterval(
function () {
ajaxrequest('test.php', 'refreshTitle')
}, 1000); // refresh every 10000 milliseconds
//This time val should vary based on the song title retrieved during the last second
</script>
And somewhere down the rest of the page I have this:
echo "<div id=\"refreshTitle\" style=\"float:left; padding-top:6px;\">\n";
echo "</div>\n";
In test.php (the file with the song name) I have this:
if (isset($_POST['test'])) {
$str = $_POST['test']; // get data
echo $dnas_data['SONGTITLE'] . " Current time " . $str;
}
So basically every second I send the time to test.php, which echos it and that echo I assume is put into 'refreshTitle' with this line:
document.getElementById(tagID).innerHTML = request.responseText;
What I want to do is get the song title into my javascript in listen.php and only run the ajax request after some string comparison / delay logic.
Sorry for the long-winded description but I'm fairly confused and think I've done this whole thing backwards :) Please let me know any thoughts...
First, I would recommend to you to update your jQuery version (1.3 is kinda old, the current version is 2+).
What's more, AJAX requesting is very well abstracted in jQuery : you can use the load() function to simply load an element content.
Source : http://api.jquery.com/load/
well the question is enough explained can it be done.
what I am trying to do is to get data from a popup and onclose I want to send the content I retrieved to a php controller for processing.
But I dont want to use jquery library, because it is creating a conflict for me.
Update
window.onbeforeunload = confirmExit;
function confirmExit()
{
var a = document.getElementsByTagName("div");
for (i = 0; i < a.length; i++) {
if(a[i].className == 'Ymacs-frame-content'){
var b = a[i].getElementsByTagName("div").innerHTML;
//alert(b);
}
}
//Ajax should be here
window.onbeforeunload = reloadOpener;
if (top.opener && !top.opener.closed) {
try {
opener.location.reload(1);
}
catch(e) { }
window.close();
}
}
window.ununload=function() {
reloadOpener();
}
You can just use jquery-less AJAX:
var a = new XMLHttpRequest();
a.open("GET","myscript.php?var=foo&othervar=bar",true);
a.onreadystatechange = function() {
if( this.readyState == 4) {
if( this.status == 200) {
// data sent successfully
// response is in this.responseText
}
else alert("HTTP error "+this.status);
}
};
a.send();
Alternatively, you can create an iframe tag and point it to the right page. You can even create a form and post it to the frame if needed.
You can do it in javascript without using jQuery since that is all jQuery does in the background. You will need to look at the different ways IE does it compared to other browsers though.
Yes, XMLHttpRequest, but you'll need to account for differences in browsers, which jQuery does for you.
I just went through this. The only way to use Javascript to pass info to PHP is by using XMLHttpRequest, or at least if there is another way I did not find it. It has to do with the fact that PHP renders on the server side, and Javascript isn't executed until after it is served to the client...unless you use the XHR which is...AJAX.
I was wondering, what'd be the best way to store a shopping cart?
I thought about storing products ID's in localstorage/sessionstorage and then use AJAX to retrieve the products from the server.
The only problem is that I don't know how to pass the items from the localstorage to PHP...
I'm guessing it's probably not possible directly, and I thought about a form though I have no idea how to implent it...
The idea is that when a user clicks "Add to cart" the item id and quantity is added to the localstorage, and when a user views his cart, the item details (image, name, price...) are being retreived from the database.
I'm probably going to use this tutorial
http://verido.dk/index.php/ressourcer/artikler/loading-and-saving-data-dynamically-using-php-jquery-and-mysql/
I could as well give up on local storage and go with sessions and database but I'd really like to give users that dynamic web experience.
Another possible way I just came up with is to use URLs like file.php?prodid=......, although URLs like this may get way too long.
Thanks in advance!
'You must remember that Server-Side (PHP) code is read before it converts the code to browser-side code. JavaScript is manipulated browser-side...
So one-dimensionally, you cannot pass JavaScript to PHP.
However...
With Ajax and in your case I suggest JSON you can send JavaScript data to a PHP page and bring the response back to your JavaScript methods. I think this will suit your needs. I can provide a simple example if you want.
//--example below:
JavaScript:
//Ajax Method
function processAjax(queryString, processDiv, responseDiv) {
responseDiv.innerHTML = '';
var myAjax;
try {
// Modern Browsers-->
myAjax =new XMLHttpRequest();
} catch (e) {
// antique ie browsers-->
try {
myAjax =new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
myAjax =new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// Something went wrong
document.getElementById('processDiv').innerHTML="";
alert("Your browser malfunctioned! Please try again. Consider installing a modern browser if the problem persists.");
return false;
}
}
}
myAjax.onreadystatechange = function() {
if (myAjax.readyState == 4) {
var ajaxResponse = myAjax.responseText;
responseDiv.innerHTML = ajaxResponse;
processDiv.innerHTML = "";
//NOTE: HERE IS WHERE AJAX IS FINISHED, SO IF YOU WANT TO DO SOMETHING ELSE HERE YOU CAN!
//POST PROCESSING----->
// IE: alert('I am finished processing now!');
// or call another function:
// anotherFunction();
} else {
processDiv.innerHTML = '<img src="http://www.mysite.com/images/loadingicon.gif" alt="processing....." />';
}
}
myAjax.open("GET", queryString, true);
myAjax.send(null);
}
function sendStorage() {
var helloVar = 'Hello, I am passed to PHP #1';
var worldVar = 'I am the second value passed to PHP!';
var processId = 'process_div';
var resultId = 'result_div';
var queryString = 'http://www.mysite.com/process.php?hello=' + helloVar + '&world=' + worldVar;
processAjax(queryString, processId, resultId);
}
Now for some HTML:
<div id="content">
<div id="process_div"> This is where processing will occur </div>
<div id="result_div"> This is where my response will display </div>
</div>
Now for a process.php (NOTE: FOR SECURITY, I STRONGLY SUGGEST YOU DON'T REVEAL A SERVER-SIDE PROCESSING PAGE IN YOUR JAVASCRIPT)
<?php
//init
$hello = '';
$world = '';
$errors = 0;
//set
//Security note: never trust a URL request.. you should clean all $_GET, $_REQUEST, AND $_POST with the PHP htmlspecialchars() method (take a look at php.net for that)
(isset($_GET['hello'])) ? $hello = $_GET['hello'] : $errors++;
(isset($_GET['world'])) ? $world = $_GET['world'] : $errors++;
//process
if($errors > 0) {
echo 'Errors Detected! Missing querystring get data!';
} else {
echo '<p>Hello received: ' . $hello . '</p>';
echo '<p>World received: ' . $world . '</p>';
//now we can process $hello and $world server side!
}
?>
Important: you should really look into learning some JSON and $_POST requests as they are more secure, faster and you can easily manipulate returned data. I suggest looking at a library like jquery for simplified examples.
I have not tested this code, but it should work.. Let me know if you have questions or this does not answer your question.
Glad to help!
Use AJAX to send data to the server (GET or POST) and store these values in a session variable or cookie on the server
You can use your local/session storage data and populate some hidden inputs, then submit the respective form in an ajax request. To make things cleaner you can use one hidden input and set it's value into a JSON object created from your storage data.
No, javascript runs on the client, php runs on the server.
While developing a web app where I'm making great use of javascript php and ajax.
I want to call
display_terminal('feedback_viewer','logs/init-raid-log.txt','Init-Raid');
to build my terminal and call feed_terminal() which has its own setTimeout() recursion call
var url='../edit_initRaid.php';
status_text('Initializing raid-array. Please wait a moment...');
var xmldoc=ajaxPHP2(url,2);
a php file that does nothing more that
exec("sudo /usr/bin/./init-raid-drives-web.sh");
and this is where I fail. This next line is not executed until after the exec() in the php file returns to the php file and the php file returns to the javascript. Not that it matters, but I am pretty sure it did not used to be this way, as originally the bash script would execute over a time period of 2 minutes and the javascript would successfully be updating the html with feed_terminal. this is not the case anymore.
alert("javascript has returned from ajax call");
if (xmldoc) {
status_text('Raid-array initialized successfully. System will now restart.You must re-login to FDAS-Web.');
Below is a bunch of code for your questions
Ultimately my question is, how can I run javascript DURING the ajax call?
Or maybe my question should be, how can I have edit_initRaid return an xmldoc, without waiting for the exec() to return, or how can i have the exec() return even without the script completing?
function initRaidArray(){
if (document.getElementById('initRaid_doubleCheck')){
if (document.getElementById('initRaidHideButtonSpot'))
document.getElementById('initRaidHideButtonSpot').innerHTML = '';
var spot=document.getElementById('initRaid_doubleCheck');
spot.innerHTML='';
spot.innerHTML='This may take a few moments. Please wait.';
}
display_terminal('feedback_viewer','logs/init-raid-log.txt','Init-Raid');
var url='../edit_initRaid.php';
status_text('Initializing raid-array. Please wait a moment...');
var xmldoc=ajaxPHP2(url,2);
alert("javascript has returned from ajax call");
if (xmldoc) {
status_text('Raid-array initialized successfully. System will now restart. You must re-login to FDAS-Web.');
}
}
where display_terminal() does two things, builds a table and appends it to the page, and calls feed_terminal(logfile,bigDiv,0)
function feed_terminal(logFile,bigD,lap){
// AJAX
bigD.innerHTML = '';
var url='../view_xml_text.php';
/*
* lap(0)=clear file , lap(1)=do not clear file
*/
url+='?logFile='+logFile+'&lap='+lap;
var XMLdoc=ajaxPHP2(url,2);
var xmlrows = XMLdoc.getElementsByTagName("line");
alert("xmlrows.length=="+xmlrows.length);
// empty file
if (xmlrows.length==0){
var d = document.createElement('div');
var s = document.createElement('span');
s.innerHTML='...';
d.appendChild(s);
bigD.appendChild(d);
} else {
// Parse XML
for (var i=0;i<xmlrows.length;i++){
if (xmlrows[i].childNodes[0]){
if (xmlrows[i].childNodes[0].nodeValue){
var d = document.createElement('div');
var s = document.createElement('span');
s.innerHTML=xmlrows[i].childNodes[0].nodeValue;
d.appendChild(s);
bigD.appendChild(d);
}
}
}
}
setTimeout(function(){feed_terminal(logFile,bigD,1)},2000);
}
where the most important item is the setTimeout() call to continue reaching out to the php file which returns xml of the lines in the file, simply.
function ajaxPHP2(url,key)
{
if (window.XMLHttpRequest) {
xml_HTTP=new XMLHttpRequest();
if (xml_HTTP.overrideMimeType) {xml_HTTP.overrideMimeType('text/xml');}
} else { xml_HTTP=new ActiveXObject("Microsoft.xml_HTTP"); }
xml_HTTP.open("GET",url,false);
xml_HTTP.send(null);
if (key){return xml_HTTP.responseXML;}
}
You need to tell Javascript to do your XHR call asynchronously.
Change
xml_HTTP.open("GET",url,false);
to
xml_HTTP.open("GET",url,true);
But first, you'll need to tell it to do something when the request completes (a callback):
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert(xmlhttp.responseText);
}
}
xmlhttp.open("GET",url,true);
xmlhttp.send();
One recommendation: XHR is a pain. It would be a lot easier to use something like jQuery's $.ajax()
You need to set your ajax call to be asynchronous. In the ajaxPHP2 function, the line xml_HTTP.open("GET", url, false); is what is causing the page to pause. The false parameter is telling the ajax call to make everything else wait for it. Change the false to true so it looks like this:
xml_HTTP.open("GET", url, true);
You may also need to attach a function to the onreadystatechange property so that when the ajax call returns it knows what to do. See these links for more information.