AJAX not working in Internet Explorer 9 - php

This is my function:
<script type="text/javascript">
function loadXMLDoc() {
var x = document.getElementById("trazi_drzava");
var xmlhttp;
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("trazi_grad").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "gradovi.php?selected=" + x.value, true);
xmlhttp.send();
}
</script>
and I call it like this:
<select name="td" id="trazi_drzava" onchange="loadXMLDoc()">
<option value="">Država</option>
<?php
$sel_grad_arr=array();
$sel_grad_arr[]="<select name='tg' id='grad0'>
<option value=''>Grad</option</select>";
if($q=mysql_query("SELECT drzava_id,drzava FROM drzava")){
while($r=mysql_fetch_assoc($q)){
echo '<option value="'.$r['drzava_id'].'">'.$r['drzava'].'</option>';
}
}else echo mysql_error().__LINE__;
?>
</select><select name="tg" id="trazi_grad">
//code that ajax should load
</select>
It works fine with most browsers, but with Internet Explorer 9 it doesn't work at all. Anyone have any idea why?
UPDATE: I didn't manage to do this then. So I changed logic of working totaly. Thanks everyone for answers.

I know this is a very old question, but still, one with no actually correct answer....
The correct order of operations is:
Create your request object
open a connection
Set onreadystatechange listener
send request
You have steps 2 and 3 in the wrong order, which causes problems in certain browsers.

Maybe it's a cache problem. Parameter test set as a timestamp value, something like:
xmlhttp.open("GET","gradovi.php?selected="+x.value+"&t="+parseInt(new Date().getTime().toString().substring(0, 10)),true);
xmlhttp.send();
Regards!

Check how your request is sent to server. What does the double quotes look like? IE9, at least with jQuery, doesn't encode double quotes correctly according to this post:
Why does this jQuery Ajax call fail ONLY in IE9 (Even works fine in IE8 and IE7)

This is too late to answer but here's the solution that should solve this problem.
I had a similar problem this week. Change the
xmlhttp.open("GET", "gradovi.php?selected=" + x.value, true);
to
xmlhttp.open("POST", "gradovi.php?selected=" + x.value, true);
This solved my problem.
Check here:
This PHP script doesn't work in Internet explorer and Microsoft Edge but works in Chrome/Firefox/Safari/Opera

Related

AJAX no data in responsetext

Right up front...I am very new to using Ajax.
I'm working on a web site where I want the results of one Select object to determine the options in the second Select object(from a database query). I'm using PHP and it appears that the only way to do this is to use Ajax. I've written a short html page to test my Ajax knowledge and it seems to work just find on Firefox but not on Chrome or IE. I've done a lot of research and found all sorts of folks with similar problems but no real solution.
I'm making the XMLHTTPRequest call to a local file in the same folder even so I should not be experiencing any cross-domain problems. Any help would be greatly appreciated.
Here's my Javascript function that gets called when the Select box is changed:
...
function getData(str)
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","ajax_info.php?color=",true);
xmlhttp.setRequestHeader("Content-Type", "text/xml");
xmlhttp.send();
alert(xmlhttp.responseText);
}
********ajax_info.php
+++++++++++++++++++++
//this is the php file that runs in response to the xmlhttprequest. It just generates a string of number at this time.
<?php
$str = "";
$i = 0;
for($i; $i<1000; $i++)
{
$str = $str.$i."-";
}
echo $str;
?>
You need to attach an event handler to your xmlhttp object to catch the onreadystatechange event. Note that when you alert your value, the asynchronous ajax call has just fired and has not finished yet (you are not checking for that anyway):
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
alert(xmlhttp.responseText);
}
}
xmlhttp.open("GET","ajax_info.php?color=",true);
xmlhttp.setRequestHeader("Content-Type", "text/xml");
xmlhttp.send();
Well in that case you should try jQuery. It will be lot easier for you to make ajax request.
Here is an example for your problem
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
// FOR GET REQUEST
$.get("ajax_info.php",{color:'value'},function(data) {
alert(data); // RETRIEVE THE RESULT
});
</script>

XML Request not working properly

I have an XML request in my javascript file that is not transferring my variable correctly to PHP and I cannot figure out why. Could I possibly be missing a reference library of some sort?
Here is the function in question. I do know that the str variable has what I want inside. I am leaving old trial code in comments just in case you want to see what I have tried.
function PHP_Con(str)
{
var xmlhttp;
if (str=="")
{
document.getElementById("txtHint").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("txtHint").innerHTML=xmlhttp.responseText;
}
}
if(!xmlhttp)
{
alert("Fehler");
}
else
{
/*$.ajax({
type:"POST",
url:"dbConnection.php",
data:{"test" : "str"},
success:function()
{
alert("success");
}
});*/
alert(str);
xmlhttp.open("GET","dbConnection.php?test="+str,true);
// Requestheader senden
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
// Request senden
xmlhttp.send();
/*var json_string= JSON.stringify(str); // convert it into a json string.
$.post('dbConnection.php' , {test : json_string },function(){
alert("success");
}); */
}
}
And here is my corresponding PHP code:
$test = intval($_POST['test']);
echo $test;
Also, I know about isset but I am trying to get the variable to show up. I'd rather get an error when it is not there, if that makes since...
Thank you very much. :) If there are easier ways to do this, I would be interested in that as well.
But as of now I feel like I do need to have a Form that calls a JS function, then my JS has variables retrieved from user input, and then those variables go to PHP so that they can be checked against my database... it all seems like the right order to me, but I admit to not having a very clear view of how JS variables show up in PHP and also of how PHP can respond in a way that is reflected through HTML code... for example I would like to "echo" back to a span in a p with the results of the comparison (user input against the database contents) and I have no idea of how that is done...
You are sending a GET request so you have to use $_GET instead of $_POST
$test = intval($_GET['test']);
echo $test;
a POST request would look like
xmlhttp.open("POST","dbConnection.php",true);
// Requestheader senden
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
// Request senden
xmlhttp.send("test="+encodeURIComponent(str));

AJAX PHP Submission not working

I'm trying to execute a PHP script that updates a MySQL DB on click of an image. I'm using a snippet I found online to do so:
function execute(filename,var1,var2)
{
var xmlhttp;
if(window.XMLHttpRequest)
{
//Code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
//Code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
alert("Your browser does not support AJAX!");
}
var url = filename+"?";
var params = "id="+var1+"&complete="+var2;
xmlhttp.open("POST", url, true);
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
{
//Below line will fill a DIV with ID 'response'
//with the reply from the server. You can use this to troubleshoot
//document.getElementById('response').innerHTML=xmlhttp.responseText;
xmlhttp.close;
}
}
//Send the proper header information along with the request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);
}
With this link: <a href="javascript:void(0);" onclick="execute(games_do.php,<?=$game['appid']?>,<?=$complete?>)" > </a>
And games_do.php contains:
$appid = $_GET['id'];
$complete = $_GET['complete'];
mysql_query("UPDATE ownedgames SET complete='".$complete."' WHERE steamid='".$steamid."' AND appid='".$appid."'") or die(mysql_error());
However, nothing seems to happen on click. Any suggestions would be greatly appreciated! :)
The parameter values for the execute function in the <a> tag should be enclosed within quotes as the function expects a string as the value.
In addition, the point mentioned in D. Schalla's answer should also be considered.
There are several prolems with your code:
First of all, you should always escape or type-cast your code, because you have SQL Injections made possible in your code:
$appid = $_GET['id'];
$complete = $_GET['complete'];
to:
$appid = intval($_GET['id']);
$complete = mysql_real_escape_string($_GET['complete']);
Also I would change the mySQL Driver from mysql_ to PDO later, since it might be that it will be unsupported in a later version of PHP.
But however, to find the problem in your code I would debug the request using Firebug (an Firefox Addon) or the Chrome Developer Console. Check what the Request Returns, it might be an mySQL Error relating to your Database Design.
To do so, check in Chrome under the Tab Network in the Console the "Answer" of the AJAX Request, when there is an error, it will be displayed there.
I would also switch to jQuery if you plan to work more heavy with AJAX, since it handles the fallback solutions for some browsers and offers an more easy integration, you can find a doc relation this there:
http://api.jquery.com/jQuery.ajax/
Change mysql_query("UPDATE ownedgames SET complete='".$complete."' WHERE steamid='".$steamid."' AND appid='".$appid."'") or die(mysql_error());
to this:
mysql_query("UPDATE ownedgames SET complete='$complete' WHERE steamid='$steamid' AND appid='$appid'") or die(mysql_error());
Further, you can make your ajax call easier with jQuery, if you're not using it, I strongly suggest you do. It would make it as this:
function execute(filename,var1,var2){
$.ajax({
type: "POST",
url: filename,
data: {id:var1, complete: var2}
}).done(function( result ) {
//do whatever you want to
});
}
as for your link, you should try this:
<?php
$id=$game['appid'];
echo('<a onclick=execute("games_do.php","'.$id.'","'.$complete.'")>Click Here </a>');
?>

ajax button loading state

I made this little script with tutorials on internet. php function calls this javascript as many times as there are buttons (foreach), right now i have three. $value is the div name of specific button (buttons are stored in php array).
Everything works fine... except when i click through all the buttons fast, the loading gif remains without javascript changing the button status. The response, witch it gets from another php is the new button state and session variable change. Session variable gets changed but the div dosent.
So, heres where i need help, how can i make it so, when i click buttons fast, the div gets changed too?
my code
function load_javascripts() {
foreach ($GLOBALS["VARIABLES"]["button_list"] as $key => $value) {
$scripts .= "
function run_alias_button_".$value."(str)
{
document.getElementById('aliasbutton_".$value."').innerHTML='<img src=ajax_loader.gif>';
if (str=='')
{
document.getElementById('aliasbutton_".$value."').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('aliasbutton_".$value."').innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open('GET','?leht=alias_logimine&alias=".$value."',true);
xmlhttp.send();
}
";
}
return $scripts;
}
Put var xmlhttp; at the very beginning of the function, making the variable explicitly local. Sometimes without that statement browsers may try to find a global variable with this name and readystate monitoring is shifted from one request to another.
Just a tip. Use the open function always before the onreadystatechange event. The way you using may works on firefox but IE doens't understand. LIke this:
xmlhttp.open('GET','?leht=alias_logimine&alias=".$value."',true);
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById('aliasbutton_".$value."').innerHTML=xmlhttp.responseText;
}
}
xmlhttp.send();

Can't Get A Simple Ajax Response

I've implemented more complex AJAX before with javascript and PHP, but for some reason this refuses to work. This is copied almost directly from the W3 example.
var xmlhttp;
function changeLoc(str)
{
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
var url="action.php";
url=url+"?q="+str;
url=url+"&sid="+Math.random();
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
function stateChanged()
{
if (xmlhttp.readyState==4)
{
alert(xmlhttp.responseText);
}
}
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
And the simple action.php
<?php
echo 'here';
?>
The function changeLoc is called from a link on the html page. It gets into the readyState = 4 condition , but the alert is blank. I know it's something really simple, but I can't find it.
Thank you.
Use firebug to see if there are any issues(like there are any 404 etc). Also its better to choose a javascript framework like jQuery for AJAX.
After seeing some of the suggestions I saw that the call to my php file was never occurring through firebug. The action that was occurring was when I navigated back to my index through the links on my page that call the Ajax functionality. Once i removed the href from my links, the php worked!
Very tricksy, but now I know better
Thank you for your help.

Categories