my problem is I am not sure how to call my php function from JS. I am trying to learn xmlhttprequest but something seems to be wrong with my code:
HTML:
<input type="button" id="btn" value="Click">
JS:
window.onload = initForms;
function initForms(){
document.getElementById("btn").onclick = doSomething;
}
function doSomething(){
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
// response
}
}
try {
xmlhttp.open("GET", "test.php", true);
xmlhttp.send();
} catch (e) {
alert(e);
}
}
PHP:
<?php
echo "Echo!";
EDIT: My question is "Echo" doesn't appear, so test.php doesn't seem to be called?! Why not?
EDIT: In the Firefox console i get the following error: "XML Parsing Error: no root element found". Not sure what to make of it (yes, I googled it..)
"// Response, you have to actually do something with the response, such as console.log(xmlhttp.response);"
console.log is worthless, especially if you are wanting to do something with the data.
getElementById("idName").innerHTML = xmlhttp.response;
Is more likely what the OP is looking for.
Related
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST","test.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("abc=123");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
<?php if(isset($_POST['abc'])) {
$test123 = 'worked';
}
?>
}}
var worked = '<?php echo $test123;?>'; // <--- this is not working
How can I make this work? I don't receive the variable in PHP whether I use get or post methods.
You seem to have two fundamental misunderstandings. One is about AJAX, and the other is about client side vs. server side code. The latter is more important.
Server vs. Client
Essentially PHP and JavaScript are totally agnostic to each other. They do not run in parallel. In this context, they don't even run on the same machine (the PHP code runs on your server, the JavaScript on the user's computer). The only communication each script can do with the other is via HTTP.
It's test.php that needs to have the code
<?php if(isset($_POST['abc']))
{
$test123 = 'worked';
}
?>
As long as test.php exists, this should work, but I'm thinking of it as a standalone script.
Using AJAX
Because of the asynchronous nature of AJAX and its HTTP dependency, you can't rely on when an ajax request will complete or even if it will complete. That is to say that any code that depends on the result of an AJAX call must be done in the ajax response callbacks.
That is, you would do something like this:
//php
<?php if (isset($_POST['abc']) { echo json_encode(array('success' => true)); }
//JavaScript
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
if (JSON.parse(xmlhttp.responseText).success) {
console.log('it worked!');
}
}
Additionally to what #Explosion Pills explained this means the php inside the ajax doesn't work as you expect.
At the place inside test.php put this:
<?php if(isset($_POST['abc']))
{
$test123 = 'worked';
}
echo $test123;
?>
Then in the code you have up there replace this:
<?php if(isset($_POST['abc']))
{
$test123 = 'worked';
}
?>
by:
var worked = xmlHttp.responseText;
and finally remove this last line:
var worked = '<?php echo $test123;?>';
And check out what happens.
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.
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.
I am trying AJAX for the first time on my localhost.
I am using IIS and PHP with MySQL.
This error is generated: "A HTTP Error 404.3 - Not Found" when I try this javascript command:
xmlhttp.send(null);
xmlhttp is a varable and is used to retrieve the GetXmlHttpObject
Just in-case something inside your xmlhttp object creation is not setup correctly or you have not waited for the correct status, have you looked at some simple xamples like from XUL.fr or W3 Shools or Your HTML Source?
Below is a simple example. Notice the inline function for the onreadystatechange callback and the check on readystate and status. I believe your issue may reside in you note doing these checks, but without your code I could be wrong.
<html>
<head>
<script>
function submitForm()
{
var xhr;
try { xhr = new ActiveXObject('Msxml2.XMLHTTP'); }
catch (e)
{
try { xhr = new ActiveXObject('Microsoft.XMLHTTP'); }
catch (e2)
{
try { xhr = new XMLHttpRequest(); }
catch (e3) { xhr = false; }
}
}
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4)
{
if(xhr.status == 200)
document.ajax.dyn="Received:" + xhr.responseText;
else
document.ajax.dyn="Error code " + xhr.status;
}
};
xhr.open(GET, "data.txt", true);
xhr.send(null);
}
</script>
</head>
<body>
<FORM method="POST" name="ajax" action="">
<INPUT type="BUTTON" value="Submit" ONCLICK="submitForm()">
<INPUT type="text" name="dyn" value="">
</FORM>
</body>
</html>
I have the following code, which is the core part of my small AJAX application. I am not getting any errors, it is just that nothing happens. I am guessing there is a more efficient way to do what I am trying to do.
Here is the code:
var xmlHttp
var layername
function update(layer, part, pk, query)
{
if (part=="1")
{
$url "get_auction.php?cmd=GetAuctionData&pk="+pk+"&sid="+Math.random()
}
else if (part=="2")
{
var url "get_records.php?cmd=GetRecordSet&query="+query+"&sid="+Math.random()
}
xmlHttp=GetXmlHttpObject()
if(xmlHttp==null)
{
alert("Your browser is not supported?")
}
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
document.getElementById(layer).innerHTML=xmlHttp.responseText
} else if (xmlHttp.readyState==1 || xmlHttp.readyState=="loading") {
document.getElementById(layer).innerHTML="loading"
}
};
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
xmlHttp=new XMLHttpRequest();
}catch (e)
{
try
{
xmlHttp =new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
return xmlHttp;
}
function makewindows(){
child1 = window.open ("about:blank");
child1.document.write(json_encode(<?php echo $row2["ARTICLE_DESC"]; ?>));
child1.document.close();
}
and an example of how I am calling the function from php
onclick="update(\'Layer3\',\'2\','.$pk.'\',\'0\',)">'
pk or query will never be passed at the same time, only one of them will ever be passed.
edit: I am also wondering if it would make more sense for the makewindows function to take a parameter, or stay as it is. Are there advantages and disadvantages for each approach?
Looks like you may have some javascript errors:
if (part=="1")
{
$url "get_auction.php?cmd=GetAuctionData&pk="+pk+"&sid="+Math.random()
}
else if (part=="2")
{
var url "get_records.php?cmd=GetRecordSet&query="+query+"&sid="+Math.random()
}
Use Firefox and Open the javascript console to get the javascript errors, then try to fix the lines it complains about.
Javascript will stop running as soon as it encounters an error.
Also, checkout firebug if you haven't already. Great tool!
I'd check the HTML the PHP is generating. Assuming $pk is a string it looks like you're missing an opening quote. Try this:
onclick="update(\'Layer3\',\'2\',\''.$pk.'\',\'0\',)">
json_encode is a PHP function, and thus you need to modify that particular line like so:
child1.document.write(<?php echo json_encode($row2["ARTICLE_DESC"]); ?>);