php variable to javascript via ajax - php

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.

Related

Call javascript function in parent window from child ajax

been working on a new site, and run into a problem.
I have an ajax loader on my main page, which loads a script every second to check if a background process is completed (usually 20 seconds-ish)
But, once the ajax script has executed (20 seconds later) it still refreshes every second.
I need to redirect the parent page to a new url, once the ajax script has finished its job.
My ajax code:
<script type="text/javascript">
function myFunction()
{
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.getElementById("txtHint").innerHTML=ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "code/timer.php?file='.$file.'", true);
ajaxRequest.send(null);
}
</script>
<script type="text/javascript">
function forward(){
location.href=\'http://domain/newpage.html\';
}
function setTimer(){
set = setInterval( "myFunction()", 1000 );
}
</script>
the backslashes in forward(); are because my code is echoed from php.
i have tried a few codes, but the main one that should work (in child ajax element) is:
window.opener.forward();
would be greatful of any help you guys can provide... thanks
opener is only available in windows opened with javascript, call simply
forward();
but you should use another name for the function, there is a predefined method window.forward()

Open PHP file using AJAX

i am trying to execute a PHP file using AJAX, which is supposed to update a txt file
here is my javascript
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();
var host = window.location.hostname;
var dir1=window.location.pathname.split("/")[1];
var dir2=window.location.pathname.split("/")[2];
var p = document.getElementById(\'CTI_IP\').value;
var url=\'http://\'+host+\'/\'+dir1+\'/modules/company/include/file.php?var=\'+p;
xmlHttp.open("POST",url,true);
if (xmlHttp.readyState==4)
{
xmlHttp.send();
}
}
the url is fine, i alerted it, copy pasted the link, the php file is working perfect and updating the txt file but it won't work in ajax? why
thanks !!
You have a syntax error:
var p = document.getElementById(\'CTI_IP\').value;
^HERE
(And similar ones scattered throughout).
This should have shown up in your browser's JavaScript error console.
When you build the URL, you are building it wrong. You are escaping quotes that don't need escaping. It should be built as follows:
var url = "http://" + host + "/" + dir1 + "/modules/company/include/file.php?var=" + p;
You are also escaping the quotes on your getElementById call for some unknown reason. It should be called as follows:
var p = document.getElementById("CTI_IP").value;
The only time you want to escape quotes is when you want them included in your string. In these instances, you shouldn't have escaped them because they denote a string - they aren't meant to be included.
I recommend that you research a little bit about how strings work in Javascript.
Once you've fixed those errors, remove the if block around your xmlHttp.send().
You have:
if (xmlHttp.readyState==4)
{
xmlHttp.send();
}
But should only have
xmlHttp.send();
Finally, since you don't include it in your example above, I'm assuming you aren't actually making a call to your MakeRequest() function anywhere. You have to call that function somewhere in your code to get it to actually execute the function.
Simply invoke the function as follows:
MakeRequest();

Adding more parameters in ajax

I am using AJAX function. I am passing 3 variables to the next page using AJAX. When I add the 4th variable the function doesn't get called.
Code:
<script language="javascript" type="text/javascript">
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var count = document.getElementById('count').value;
var type = document.getElementById('type').value;
var sem = document.getElementById('sem').value;
var rid = document.getElementById('room').value;
ajaxRequest.open("GET", "add_requi_ajax.php?count=" + count+"&type="+ type+"&sem="+sem+"&rid="+rid, true);
ajaxRequest.send(null);
};
</script>
Your code is syntactically and logically correct, which means that the problem is likely one of your input IDs is wrong (typo? Should room be rid?), or you call the function before the inputs are rendered on the page (use window.onload).
Verify each of your input IDs. If they all look correct, then comment them out and hard code the values to rule out your inputs as a problem. Watch the error console for any error messages. If an uncaught error is encountered, it can appear that the function isn't being called.
You probably need to urlencode your values.

ajax passing parameter to javascript/php

I experience a weird problem in this code, actually it works for 1 second and then not anymore.. maybe some variable/function is not correctly declared and is causing this strange thing..
I have in my index.php this piece of code. If I put hardcode inside the function myfunc par1 and par2 set to zero then everything behaves correctly, means loadfunc.php is correcly called with those parameters, while if try the code I posted I see that loadfunc.php is called once correctly and so I can see the correct output for only 1 second..
<script type="text/javascript">
function myfunc(par1, par2)
{
var
$http,
$self = arguments.callee;
if (window.XMLHttpRequest) {
$http = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
$http = new ActiveXObject('Msxml2.XMLHTTP');
} catch(e) {
$http = new ActiveXObject('Microsoft.XMLHTTP');
}
}
if ($http) {
$http.onreadystatechange = function()
{
if (/4|^complete$/.test($http.readyState)) {
document.getElementById('ReloadThis2').innerHTML = $http.responseText;
setTimeout(function(){$self();}, 1000);
}
};
$http.open('GET', 'loadfunc.php' + '?par1=' + par1 + '&par2=' + par2);
$http.send(null);
}
}
</script>
<script type="text/javascript">
setTimeout(function() {myfunc("0","0");}, 1000);
</script>
setTimeout(function(){$self();}, 1000);
Resets the timeout, but doesn't set up the parameters, which is why they show up as undefined.

Calling PHP Function within Javascript

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.

Categories