5

i have a drop down select list and a button in which i have inserted an onclick event so that whenever anyone is clicking on that button it will call a function which is basically includes an ajax and when on executing it will include a php file. In my php file it is taking the value from the selected drop down list and after that it will display an alert option but it is not displaying any alert.

Below is my code:-

<html>
<head>
<script>
function showUser(str)
{
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;
    }
  }
xmlhttp.open("GET","user.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>

<form>
<select name="users1" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Glenn Quagmire</option>
<option value="4">Joseph Swanson</option>
</select>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here.</b></div>

</body>
</html>

user.php

<?php
$q=$_GET["q"];
if($q ==1)
{
    echo '<script type="text/javascript">
    alert("Hello")
    </script>';
}
else {
    echo "No";
}
?>

Any help would be appreciated much and thanks for your help in advance:)

Oh What A Noob
  • 507
  • 1
  • 10
  • 33

9 Answers9

1

So, as Chris already pointed out, if you use the AJAX call you described to return some text, you can put that in your page with a DOM update, such as you had:

document.getElementById("txtHint").innerHTML=xmlhttp.responseText;

That works. But if your responseText contains javascript, it will merely be posted into the document. Your page has already finished loading, so it will not be executed.

However, you apparently want two behaviors to result from your AJAX call. In addition to posting a body of user data to the txtHint div, you also want to have an alert pop up. To do this, you could place the code for the alert in your onreadystatechange function, after the point that posts to your txtHint div.

It is not clear from your question what logic you want controlling the alert. If you want the alert to say "Hello" for some choices of the selection and "No" for other choices, then you can just test your select input:

if (str=="1") alert("Hello");
else          alert("No");

If instead, the content of your alert should depend on what your AJAX call returned, then you would have some other logic based on xmlhttp.responseText instead. Perhaps you would even write the body of the alert into the response that user.php sends back. Then you could parse that out of the responseText, use it in your alert, strip it out, and use the rest to set txtHint's content.

Mark Goldfain
  • 731
  • 2
  • 8
  • 24
0

I don't think that the "script" tag you add to the page dynamically will be parsed and executed. But you could just return a json object from your user.php including your answer (yes/no). And then you cann decide what to display in your onreadystatechanged callback. Or just return "yes" / "no" and do something like:

<?php
$q=$_GET["q"];
if($q ==1)
{
    echo "Yes";
}
else {
    echo "No";
}
?>

and in your main page:

if(xmlhttp.responseText === "yes"){
 alert("Hello");
}
else{
 alert("No");
}
Chris
  • 7,675
  • 8
  • 51
  • 101
  • What about the value that has being fetched in the user page? – Oh What A Noob Mar 16 '13 at 08:49
  • 1
    Now, what i have done is that included if(xmlhttp.responseText === "yes"){ alert("Hello"); } else{ alert("No"); } in my showusr function then whenever i am clicking on any option then it is displaying alert with the value of "No". – Oh What A Noob Mar 16 '13 at 09:17
0

Try inserting the HTML you receive from the AJAX call into the body.

document.getElementsByTagName('body')[0].appendChild(xmlhttp.responseText);

Obviously if this works, you will need to make sure there is data to append, or you'll likely get an error.

I often use scripts in PHP snippet files which I retrieve via AJAX, and I have found that they never work until I append them to something. I have never tried a PHP file that returns only a script tag, but in theory it should work the same.

EDIT: Changed code example to Javascript when I realized you weren't using jQuery. Actually I haven't done this without jQuery in a long time, so I am not entirely sure it will work, but give it a try anyway. I think maybe using appendChild() and innerHTML will give different results.

EDIT AGAIN: Again, I have not tested this out because I am not currently able, but perhaps wrapping the xmlhttp.responseText in a document.createDocumentFragment() might work:

var frag = document.createDocumentFragment();
frag.innerHTML = xmlhttp.responseText;
document.getElementsByTagName('body')[0].appendChild(frag);
David John Welsh
  • 1,564
  • 1
  • 14
  • 23
  • 1
    I guess the -1 means this doesn't work. Apologies for suggesting something without trying it out myself. I probably should have deleted rather than edited when I realized jQuery was not being used. I know that anonymous downvotes are fine on SE, and I think that's a good thing, but this is not the first time I have been confused as to the reason. Seriously, I want to do better - if you give no indication of why you downvote, how am I supposed to rectify whatever the problem is? – David John Welsh Mar 18 '13 at 03:10
  • i really appreciate about your time and help for my answer. It does not worked for me but i was not the one who has done -1 to your answer. To be honest, i never done -1 to any of the answer till now bcoz i think that giving an opinion to others really matters a lot. It's good that atleast you have tried out something. thanks a lot dude:)) – Oh What A Noob Mar 18 '13 at 05:56
  • 1
    Sorry, I didn't mean to sound snarky, and I certainly wasn't trying to point fingers. Just frustrated with the system :-) – David John Welsh Mar 20 '13 at 09:31
0

Use showUser(this.options[this.selectedIndex].value) instead of showUser(this.value)

Edit:

So change $q=$_GET["q"]; to $q=intval($_GET["q"]);

Amir
  • 4,089
  • 4
  • 16
  • 28
0

Try

if(xmlhttp.responseText == "yes"){
 alert("Hello");
  }
else{
 alert("No");
 }

Swap === with ==

Alexander Kimaru
  • 375
  • 4
  • 21
0

The problem is that adding scripts with innerHTML=... does add the script to the DOM but does NOT automatically evaluate (execute) the script. Change this:

    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
        document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }

to this:

    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
        document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
        var myScripts = document.getElementById("txtHint").getElementsByTagName("script");
        if(myScripts.length > 0) 
        {
            for(i=0; i < myScripts.length;i++)
            {
                eval(myScripts[i].innerHTML);
            }
        }
    }

This way all of your async added scripts will get evaluated.

0
<html>
<head>
<script>
function showUser(str)
{
if (str=="")
  {
  document.getElementById("txtHint").innerHTML="<b>Person info will be listed here.</b>";
  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;

     //////////// YOU CAN ADD THIS!///////////////////
    if (str=="1"){alert('hello');}
     ////////////////////////////////////////////////

    }
  }
xmlhttp.open("GET","user.php?q="+str,true);
xmlhttp.send();

}
</script>
</head>
<body>

<form>
<select name="users1" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Glenn Quagmire</option>
<option value="4">Joseph Swanson</option>
</select>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here.</b></div>

</body>
</html>
0

Try to have a Fiddler running to see what is the traffic/output that is going between the servers. That will give an insight into what is the output of user.php? which can help debug.

0

Unfortunately you cannot simply use innerHTML to append scripts as it was told already. Your best bet would be using some DOM handler like jQuery, which handles the DOM API very easily. The better way to do what you need would be by writing some Javascript:

var jsTag = document.createElement('script');
var jsCode = "alert('this came from PHP or whatever you have on server side');";
jsCode = document.createTextNode(jsCode);
jsTag.appendChild(jsCode);
document.body.appendChild(jsTag);

or, with jQuery it would be something like:

$('body').append("<script>alert('this came from PHP or whatever you have on server side');</script>");

~cheers~