Calling PHP Function within Javascript - php

I want to know is it possible to call a php function within javascript, only and only when a condition is true. For example
<script type="text/javascript">
if (foo==bar)
{
phpFunction(); call the php function
}
</script>
Is there any means of doing this.. If so let me know. Thanks

PHP is server side and Javascript is client so not really (yes I know there is some server side JS). What you could do is use Ajax and make a call to a PHP page to get some results.

The PHP function cannot be called in the way that you have illustrated above. However you can call a PHP script using AJAX, code is as shown below. Also you can find a simple example here. Let me know if you need further clarification
Using Jquery
<script type="text/javascript" src="./jquery-1.4.2.js"></script>
<script type="text/javascript">
function compute() {
var params="session=123";
$.post('myphpscript.php',params,function(data){
alert(data);//for testing if data is being fetched
var myObject = eval('(' + data + ')');
document.getElementById("result").value=myObject(addend_1,addend_2);
});
}
</script>
Barebones Javascript Alternative
<script type="text/javascript">
function compute() {
var params="session=123"
var xmlHttp;
var addend_1=document.getElementById("par_1").value;
var addend_2=document.getElementById("par_2").value;
try
{
xmlHttp = new XMLHttpRequest();
}
catch (e)
{
try
{
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("No Ajax for YOU!");
return false;
}
}
}
xmlHttp.onreadystatechange = function()
{
if (xmlHttp.readyState == 4) {
ret_value=xmlHttp.responseText;
var myObject = eval('(' + ret_value + ')');
document.getElementById("result").value=myObject(addend_1,addend_2);
}
}
xmlHttp.open("POST", "http://yoururl/getjs.php", true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.send(params);
}
</script>

No that's not possible. PHP code runs before (server-side) javascript (client-side)

The other answers have it right.
However, there is a library, XAJAX, that helps simulate the act of calling a PHP function from JavaScript, using AJAX and a particularly designed PHP library.
It's a little complicated, and it would be much easier to learn to use $.get and $.post in jQuery, since they are better designed and simpler, and once you get your head around how they work, you won't feel the need to call PHP from JavaScript directly.

PHP always runs before the page loads. JavaScript always runs after the page loads. They never run in tandem.
The closest solution is to use AJAX or a browser redirect to call another .php file from the server.

Related

setInterval - ajax with string attached (GET)

I need help figuring out how i can setInterval while keeping a "str" to the function.
The client chooses an option, and the function "GET"'s the selected option.. But when it refreshes in setInterval, it looses the string.. How can i do this?
I have tried this:
<script type="text/javascript">
function countrystats(str)
{
if (str=="")
{
document.getElementById("countrystats").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("countrystats").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","countrystats.php?q="+str,true);
xmlhttp.send();
setInterval(countrystats, 5000);
}
</script>
Hopefully you can help me sort out this mess :-)
I am aware that this can be done with some jQuery, but i cat seem to get that to work. Maybe those two things are related, i dont know :-)
Here is how the function countrystats gets its input:
script type="text/javascript">
$("#countrystats_menu > li > a").click(function (ev) {
var str = $(this).html();
countrystats(str);
$('#country_span').html(str);
});
</script>
EDIT/Solution:
It seems that the problem was, when doing setInterval, it looses the str attached, this code is however preserving it.
setTimeout((function(strPriorToTimeout)
{//IIFE's scope preserves state of str variable
return function()
{
countrystats(strPriorToTimeout);
};
})(str),5000);
The argument str goes out of scope at the end, the interval simply calls the function without passing any value to str. As some comments suggest, countrystats(str) would appear to do the trick, but it doesn't, here's why:
setInterval(countrystats(str), 500);
This line contains multiple expressions that will be evaluated/resolved to some value, like countrystats(str), which is a direct call to a function. The function, then, will be called prior to the interval being set. The quickest solution is creating an anonymous function, and call the function from within:
setInterval(function()
{
countrystats(str);
},5000);
You can even play it extra safe, by creating a closure, actually passing the intended value of str to the interval function. This is optional, and might look a bit confusing (and messy):
setInterval((function(strPriorToTimeout)
{//IIFE's scope preserves state of str variable
return function()
{
countrystats(strPriorToTimeout);
};
})(str),5000);
There is just one thing that's bothering me about your code: you're using setInterval, which repeats the same function call every X ms. If you only need to call a function once, it might be better using setTimeout.
Another thing is: setInterval returns the interval's id, so you can stop the constant function calls if needed. You don't seem to be assigning that ID anywhere, so your code will keep on running, unless you're brute-forcing the clearInterval calls. Perhaps consider assigning the return value of setInterval to some variable you can access.
If you don't the only way of clearing intervals AFAIK would be:
for (var i=0;i<Number.MAX_VALUE;i++)
{
clearInterval(i);
}
Now that's just terrible, isn't it?
In light of the comments, I thought I'd do well adding some info on webworkers here. From what I gather the OP wants to acchieve, I recommended using webworkers as much as possible. A basic setup here could be:
//client.js
var worker = new Worker('dashWorker.js');//worker script
//to kick off the worker:
function countrystats(str)
{
str = str || document.getElementById('countrystats').innerHTML;//get str value
worker.postMessage(str);//that's it, the worker takes care of everything else
}
worker.onmessage = function(response)
{
document.getElementById('countrystats').innerHTML = response.response;//cf worker code
return countrystats(response.str);//choose when to call the countrystats function again, as soon as the worker responded... easy!
};
//the worker:
self.onmessage = function(e)
{//you could add a way of stopping the constant updates, by posting a 'stopDash' or something...
//do ajax call using e.data --> this is the string anyhow
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(response)
{
if (this.readyState === 4 && this.status === 200)
{
self.postMessage({str: e.data,
response: response.responseText});
}
};
xhr.open('GET', 'countrystats.php?q=' + e.data,true);
xhr.send();
};
Of course, this code is far from "clean": it could do with some performance tweaks (like not querying the DOM all the time), but the basic principal stands...
A couple of important links for you here:
MDN
John Resig's blog post on workers
A step-by-step introduction to webworkers
you are calling setInterval(countrystats, 5000); in the same function. you can do with jquery also
url='countrystats.php?q='+str;
ajax calll
$.get(url, function(data) {
$('#countrystats').html(data);
});
once the get finishes. you can call setInterval(countrystats, 5000); for refreshing the content.
I've simplified your code with jQuery. I've used jQuery.load to load the remote html to the start element.
And whenever a new item is clicked you need to create the previous interval, otherwise multiple request threads will be running
function countrystats(str) {
if (str == "") {
$('#countrystats').empty();
return;
}
$('#countrystats').load('countrystats.php?q=' + str)
}
var interval;
$("#countrystats_menu > li > a").click(function(ev) {
if (interval) {
clearInterval(interval);
}
var str = $(this).html();
countrystats(str);
interval = setInterval(function() {
countrystats(str);
}, 5000);
$('#country_span').html(str);
});

php variable to javascript via ajax

Ok im tring to get PHP variable to javascript variable via ajax.
i have some piece of php code to make this variable it look like this: (i wont put entire code because its working so only relevant code for this topic. i have new_m variable which is ARRAY and i want to pass it)
shuffle($new_m);
echo json_encode($new_m);
then i have js file which should catch that echo and it look like this:
function getXMLHttp()
{
var xmlHttp
try
{
//Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
}
catch(e)
{
//Internet Explorer
try
{
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
alert("Your browser does not support AJAX!")
return false;
}
}
}
return xmlHttp;
}
function MakeRequest()
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
var myvar = new Array();
var myvar=JSON.parse(xmlHttp.responseText);
return myvar;
}
}
xmlHttp.open("GET", "showimage.php", true);
xmlHttp.send(null);
}
When this code is not on separate page like here and when is myvar is used inside function it works (because i have used this code on another page successfully). So i think my problem is not returning correct variable or not returning it on correct way.
and final piece of code is part where this myvar should be used it looks like:
<script type="text/javascript" src="js/shuffle.js"></script>
<title>undf</title>
</head>
<body onload="MakeRequest()">
<script type="text/javascript">
alert(myvar);
var pos = 0;
var imgs = myvar;
</script>
and nothing happens. im still new at this ajax and javascript. thanks for you help in advance.
Your problem is that when alert( myvar); is executed, the request to the server hasn't happened yet, and the variable is undefined (not to mention that I believe the variable is out of scope, so you can't access it).
You should set up the JS so that when the window loads, you execute the request to retrieve the data and then read it:
<script type="text/javascript">
window.onload = function() {
var myvar = MakeRequest();
alert( myvar);
}
</script>
You can then get rid of the onload within the <body> tag.
Note that I'm not entirely sure that you're returning the value from the MakeRequest() function correctly, since the return is within the xmlhttp callback and not in the function. You should investigate this and verify.

inserting javascript variable into php/mysql

I have two file one is index.php another one is dbsubmit.php
In my index.php i got some javascript variable in between script tag..
var address = "Address of some places";
var latitude = 79.00256978;
var longitude = 125.89564725;
i want to pass these variables into my php script (dbsubmit.php) so that i can populate MySQL database. How can i solve this problem?? can anybody help me??
You could use something like this and than in php using $_GET you can retrieve the values
<script>
function send(url){
var request;
try{
request= new XMLHttpRequest();
} catch (e){
try{
request= new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
request= new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
alert("Your browser broke!");
return false;
}
}
}
request.onreadystatechange = function(){
if(request.readyState == 4){
//alert(request.responseText); this would be the value we get back, anything php would print would be alerted here
}
}
request.open("GET", url, true);
request.send(null);
}
send("dsubmit.php?address="+address+"&latitude="+latitude+"&longitude"+longitude);
</script>
You can use AJAX to pass the variables to a PHP script, which in turn will be able to write them to a database.
Are you using some sort of javascript framework (jQuery, etc.) ? Because they make it really easy.
You just have to make another php script to get the variables from $_GET or $_POST and save them. AJAX effectively calls the php script passing it those vars.

How to call multiple AJAX functions (to PHP) without repeating code

I have a little script which uses AJAX and PHP to display an image. You can see below that if I call the function mom() it looks in the PHP file index.php?i=mom and displays the image I'm looking for.
But I need the javascript to be lighter as I have 30 images and for each one I have to modify and copy the script below. Is there not a simpler way to have the functions be different and still call a different page?
<script type="text/javascript">
function mom()
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
HandleResponse(xmlHttp.responseText);
}
}
xmlHttp.open("GET", "index.php?i=mom", true);
xmlHttp.send(null);
}
function HandleResponse(response)
{
document.getElementById('mom').innerHTML = response;
}
</script>
My Trigger is this
<a href="#" onclick='mom();' />Mom</a>
<div id='mom'></div>
You could modify your function so it takes a parameter :
// The function receives the value it should pass to the server
function my_func(param)
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
// Pass the received value to the handler
HandleResponse(param, xmlHttp.responseText);
}
}
// Send to the server the value that was passed as a parameter
xmlHttp.open("GET", "index.php?i=" + param, true);
xmlHttp.send(null);
}
And, of course, use that parameter in the second function :
function HandleResponse(param, response)
{
// The handler gets the param too -- and, so, knows where to inject the response
document.getElementById(param).innerHTML = response;
}
And modify your HTML so the function is called with the right parameter :
<!-- for this first call, you'll want the function to work on 'mom' -->
<a href="#" onclick="my_func('mom');" />Mom</a>
<div id='mom'></div>
<!-- for this secondcall, you'll want the function to work on 'blah' -->
<a href="#" onclick="my_func('blah');" />Blah</a>
<div id='blah'></div>
This should work (if I understand correctly)
<script type="text/javascript">
function func(imgName)
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
document.getElementById(imgName).innerHTML =
}
}
xmlHttp.open("GET", "index.php?i=mom", true);
xmlHttp.send(null);
}
</script>
MARTIN's solution will work perfectly.
By the way you should use some javascript framework for Ajax handling like jQuery.
It will make your life easy.
If you are having light weight images you preload the images on your page.
I solved this by making an array of in your case xmlHttp and a global variable, so it increments for each request. Then if you repeatedly make calls to the same thing (eg it returns online users, or, whatever) then you can actually resubmit using the same element of the array too.
Added example code:
To convert it to a reoccuring event, make a copy of these 2, and in the got data call, just resubmit using reget
var req_fifo=Array();
var eleID=Array();
var i=0;
function GetAsyncData(myid,url) {
eleID[i]=myid;
if (window.XMLHttpRequest)
{
req_fifo[i] = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
req_fifo[i] = new ActiveXObject("Microsoft.XMLHTTP");
}
req_fifo[i].abort();
req_fifo[i].onreadystatechange = function(index){ return function() { GotAsyncData(index); }; }(i);
req_fifo[i].open("GET", url, true);
req_fifo[i].send(null);
i++;
}
function GotAsyncData(id) {
if (req_fifo[id].readyState != 4 || req_fifo[id].status != 200) {
return;
}
document.getElementById(eleID[id]).innerHTML=
req_fifo[id].responseText;
req_fifo[id]=null;
eleID[id]=null;
return;
}
function reget(id) {
myid=eleID[id];
url=urlID[id];
req_fifo[id].abort();
req_fifo[id].onreadystatechange = function(index){ return function() { GotAsyncData(index); }; }(id);
req_fifo[id].open("GET", url, true);
req_fifo[id].send(null);
}
The suggestions to parameterize your function are correct and would allow you to avoid repeating code.
the jQuery library is also worth considering. http://jquery.com
If you use jQuery, each ajax call would literally be this easy.
$('#mom').load('/index.php?i=mom');
And you could wrap it up as follows if you'd like, since you say you'll be using it many times (and that you want it done when a link is clicked)
function doAjax(imgForAjax) { $('#'+imgForAjax).load('/index.php&i='+imgForAjax);}
doAjax('mom');
It makes the oft-repeated ajax patterns much simpler, and handles the issues between different browsers just as I presume your getXMLhttp function does.
At the website I linked above you can download the library's single 29kb file so you can use it on your pages with a simple <script src='jquery.min.js'></script> There is also a lot of great documentaiton. jQuery is pretty popular and you'll see it has a lot of questions and stuff on SO. ajax is just one of many things that jQuery library/framework (idk the preferred term) can help with.

Is it possible to send an AJAX request on load?

Hello I have two dependants select box, the second one is popularited after onchange event.
The first one is loaded with a selected value (selected=selected), what I'm asking, it is possible to send the requested while the page is loading, ie as I have the the selected option, just send the request.
Javascript
function getXMLHTTP() {
var xmlhttp=false;
try{
xmlhttp=new XMLHttpRequest();
}
catch(e) {
try{
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1){
xmlhttp=false;
}
}
}
return xmlhttp;
}
function getSubCat(catId,incat) {
var strURL="../Includes/subcatAds.php?SubCat="+catId+"&incat="+incat;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('subcat').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
The PHP will be provided if needed
You really need to use jQuery and replace all of the above with:
function getSubCat(catId, incat)
{
$('#subcat').load("../Includes/subcatAds.php?SubCat="+catId+"&incat="+incat);
}
// Run on load:
$( function(){
getSubCat(4, 5);
});
It will do the same thing. It's set up to run on load, and you don't have to worry about cross browser compatibility.
You will find yourself using jQuery selectors all the time and your code will be very lightweight. If you link the jQuery library to Google servers people will not even have to download it. Most people have it in cache already.
You could use the onload event like this:
window.onload = function(){
var selectbox = document.getElementById('select box id');
if (selectbox.value !== ''){
// your code to send ajax requests...
}
};
The code runs as soon as page loads. It then checks if the value of the specified select box is not empty meaning something is selected; in that case you put your code for the ajax request which will execute.
Since you are doing this before getting any input from the user, you could immediately make the call to the server, before the DOM is finished, before the page is fully loaded, and then just wait until the onload event takes place, or you get informed that the DOM tree is finished, and you can then safely change the value of any of the html elements.
This way you don't have the user wait for the browser to finish loading before you even start your request, which will improve the user experience.

Categories