Javascript not loading on Ajax div load - javascript

I have a standard html page index.php and within this page I have a
<div id="alertMe">...</div>
I use a simple onclick function to do an AJAX change of this div. I wont paste the whole Ajax call.
xmlhttp.open("GET","message.php?msg=hello" , true);
message.php loads and I can display the $_GET['msg'] value in the alertMe div. However, I have a simple javascript alert which is in the file message.php
<script type="text/javascript">
alert("I am an alert box!");
</script>
I cannot get the alert to popup. Is this because I am trying to run javascript within a div load? I would have thought that was a common requirement.
Any ideas?
==== Including files =====
index.php
<html>
<script>
function loadMsg(moduleID) {
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("alertMe").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","message.php?msg=hello" , true);
xmlhttp.send();
}
</script>
<body>
<div id="alertMe"></div>
Load Message
</body>
</html>
message.php
<?php
echo $_GET['msg'];?>
<script type="text/javascript">
alert("I am an alert box!");
</script>

As some of the commentators have pointed out, <script>s inside an AJAX response do not get executed when the HTML is injected into the page by setting the innerHTML property of a DOM node. If you really need to execute those scripts:
function setHtml(element, html) {
element.innerHTML = html;
var scripts = element.getElementsByTagName("script"),
i = 0, script;
for (i; i < scripts.length; i++) {
script = scripts[i];
if (script.type = "text/javascript" && !script.src) {
eval(script.innerHTML);
}
}
}
Edit: I personally recommend against this. The "success" handler for your AJAX call should contain the logic you need to run post-AJAX.

Related

Ajax trying to execute PHP page brings me to a new page

I am trying to get a live chat working using PHP and mysql and AJAX. It is almost completely functioning, except I cant seem to figure out how to submit the chat message without reloading a page. I have a page, sendchat.php, that takes input from the previous page and enters the data into a database. I am trying to use a text input field and when the user clicks the enter key, it would execute the PHP page with the details needed to send to sendchat.php without actually loading or refreshing the page. This is what I have so far:
<form id="send-message-area">
<p>Your message: </p>
<input type="text" id="sendie" maxlength = '100' onkeydown="onChatEnter(this);"></textarea>
</form>
</div>
</td></tr></table>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">
function onChatEnter(str) {
if(event.key === 'Enter') {
$.ajax({
type: "GET",
url: "sendchat.php?msg=" + str ,
success : function() {
// here is the code that will run on client side after running clear.php on server
}
});
}
</script>
All it does is try to load the url, but its not trying to find sendchat.php or send the data. Instead it just tries to load a blank page. Where am I going wrong here? Everything seems spelled correctly and case sensitive. I check if the user pressed enter when they press a key. If they did, I am loading an AJAX function to execute a PHP page. Yet, it is not doing that. Just for FYI, I do not want a button there to be clicked.
EDIT:
I tried the suggestions below and still nothing. I decided to try a different approach now. Still doesn't work.
<script>
function updatechat(str) {
if(event.key === 'Enter') {
if (str=="") {
document.getElementById("sendie").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 (this.readyState==4 && this.status==200) {
document.getElementById("sendie").innerHTML=this.responseText;
}
}
xmlhttp.open("GET","sendchat.php?msg="+str,true);
xmlhttp.send();
}
}
</script>
<p>Your message: </p>
<input type="text" id="sendie" maxlength = '100' onkeypress="updatechat(this.value);"></input>
Try this:
$("#send-message-area").submit(function(e) {
e.preventDefault();
e.stopPropagation();
});
I am not sure how.. But I fixed it.. I think it had to do with giving the input a name along with the ID. See below:
<script language="javascript" type="text/javascript">
function updatechat(str) {
if(event.key === 'Enter') {
if (str=="") {
document.getElementById("sendie").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 (this.readyState==4 && this.status==200) {
document.getElementById("sendie").innerHTML=this.responseText;
}
}
var planetloc = document.getElementById("loc").value;
chaturl = "sendchat.php?msg="+str+"&loc="+planetloc;
sendie.value="";
xmlhttp.open("GET",chaturl,true);
xmlhttp.send();
}
}
//-->
</script>
This was the code I used for the html:
<p>Your message: </p>
<input type='text' id='sendie' name='sendie' maxlength = '100' onkeypress='updatechat(this.value);'></input>
<input type='hidden' id='loc' name='loc' value='$chatroom'></input>";
I also added chaturl to combine the ajax page I needed along with the parameters passed to it. It seemed by creating a variable for that it solved other issues too.

loading servlet from jsp and trying to pass multiple parameters

im trying to load a servlet using java script from a jsp. i am also trying to pass two parameter. the page loads but now im printing a sytem out from the servlet it suppose to give me the id and the vehicle vaules but it gives the vehicle felid as null.
ScanServlet doGet was called id = 1 vehicle= [object HTMLParagraphElement]vehicle=null
this is the code
<body onload="notifyOnLoad(<%=request.getParameter("imgid")%>)">
<img id="imgBarcode" src="ImageServlet?imgid=<%=request.getParameter("imgid")%>&vehicle=<%=request.getParameter("vehicle")%>" width=<%=request.getAttribute("Width")%> height=<%=request.getAttribute("Height")%>><br/>
<h4>Barcode Details</h4>
<p>Name :- <%=request.getAttribute("name")%></p>
<p>Type :- <%=request.getAttribute("type")%></p>
<p>Value :- <%=request.getAttribute("value")%></p>
<p id="wtf">type :- <%=request.getParameter("vehicle")%></p>
<script type="text/javascript">
function notifyOnLoad(imgid) {
var xmlhttp;
var vehicle =document.getElementById("wtf");
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) {
window.location = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "ScanServlet?imgid="+imgid+"vehicle="+vehicle, true);
xmlhttp.send();
}
</script
>
</body>
You cant directly access the request parameters in the javascript in the way you are trying.
<input type='hidden' name='field1' id='imgid' value='<%=request.getParameter("imgid")%>' />
access the variable in the javascript with its id,
<script type="text/javascript">
function notifyOnLoad(imgid,vehicle) {
var xmlhttp;
var imgid=document.getElementById("imgid");
xmlhttp.open("GET", "ScanServlet?imgid="+mgid+"&vehicle="+vehId, true);
xmlhttp.send();
}

What is wrong with this code using ajax?

I'm new to coding and now I'm trying to write a code that gets the text data form a file and replace the present text with the new one. I'm using AJAX to do the task but the problem is first I'm getting the error message and then expected answer The error message is what I have included in the code to display when there is error. Even though i'm getting the desired answer I want to know why the error message is displayed. Here is my code
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.min.js"></script>
<script>
function loadXML() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest;
}
else {
xmlhttp = new ActiveXObject("MICROSOFT.XMLHTTP")
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("p1").innerHTML = xmlhttp.responseText;
}
else {
alert(" there is a error in your code");
}
}
xmlhttp.open("GET","robots.txt", true);
xmlhttp.send(null);
}
</script>
</head>
<body>
<p id="p1">This is Text</p>
<button id="b1" onclick="loadXML()">Click me </button>
</body>
</html>
The problem is your if-block in onreadystatechange. During the request and response, xmlhttp.readyState changes multiple times and onreadystatechange is called every time this happens.
If you do it like this, it may work:
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 ) {
if( xmlhttp.status == 200 ) {
document.getElementById("p1").innerHTML = xmlhttp.responseText;
} else {
alert(" there is a error in your code");
}
}
It is simpler, however, to use the other event-methods like onload and onerror, as described here.
1- include 1 jQuery file jquery-1.9.0.js same as jquery-1.9.0.min.js but jquery-1.9.0.min.js is minified file
2- what is the Error message from javaconsole log ?
3- you are using jQuery so why you are working with XMLHttpRequest when jQuery $.get already using best of HttpRequest for all browsers
you can replace your JS code with this
<script type="text/javascript">
$( document ).ready(function() {
$.get('robots.txt',function(data){ $('#p1').html(data) });
});
<script>
Are you using a webserver ? Ajax doesn't work from local file url : 'file://...'
alert(" there is a error in your code");
Actually there is no error in your code. xmlhttp.onreadystatechange is called in different states of the request. Thats why you check for xmlhttp.readyState == 4. Learn more about the different stages here: http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp
So your code is running fine, you just alert an error message, that is not an error at all.

the JS code stop working while ajax load

The code 1: When I click on the "click here" it's supposed to hide the div with "id=adiv", and when I click again its show it again.
The code 2 and 3: the ajax code (code 2) belongs to code 3. but there not belong to code 1! this codes just refresh php page every 1 second.
Why after the ajax code (code 2&3) loads in the page, the 'code 1' stops working? When I click on "click here", its doing nothing.
But before the ajax load, the code 1 works good.
the codes 2 and 3 works good, i have no problem with them. the only problem is with code 1.
edit: when i debug this page its show me for the line: "hideshow(document.getElementById('adiv'))" (in code 1), this eror: "Uncaught ReferenceError: hideshow is not defined (anonymous function)".
but i dont really understand why i have this problem? and what i need to do to solve this?
1) The script:
Click here
<script type="text/javascript">
function hideshow(which){
if (!document.getElementById) { return; }
if (which.style.display=="block") { which.style.display="none"; }
else { which.style.display="block"; }
}
</script>
<div id="adiv" style="font:24px bold; display: block">Now you see me</div>
2) The ajax code:
<script type="text/javascript">
function refresh(name, url, info, info_1, info_2, type)
{
if (type == "send") {
document.getElementById("send_"+name).innerHTML = info; // just show the txt that send
Input(name);
if (info == "") {
document.getElementById(name).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");
}
var xhr = new XMLHttpRequest();
var params = "c=<?php echo $_GET["c"]; ?>&info="+info+"&info_1="+info_1+"&info_2="+info_2;
xhr.open("POST",url,true);
xhr.onreadystatechange = function() {
if( this.readyState == 4 && this.status == 200) {
document.getElementById(name).innerHTML = this.responseText;
}
};
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-length", params.length);
xhr.setRequestHeader("Connection", "close");
xhr.send(params);
return false;
}
</script>
3) The code that play the ajax code:
<script type="text/javascript">
setInterval("refresh('aaa', 'refresh.php', '', '', '', 'refresh')", "1000");
</script>

Adding html variables dynamically with javascript

I want to add html variables : "<script>var var1 = new CalendarPopup();</script>" according to a number that the user chooses. At the moment I have an ajax setup that is suppose to change my tag to add the variables by changing the inner html like so :
<div id="calVar">
<script>
var cal1 = new CalendarPopup();
var cal2 = new CalendarPopup();
</script>
</div>
function addRespDropDownAjax(currentNumberOfDropDown)
{
//Prepare a new ajaxRequest.
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//Ajax receiving the response in this function
xmlhttp.onreadystatechange = function()
{
//state 4 is response ready.
//Status 200 is page found.
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('calVar').innerHTML = '<script>var cal3 = new CalendarPopup();</script>';
alert(document.getElementById('calVar').innerHTML);
}
};
//Send the Ajax request.
xmlhttp.open('GET','mainServlet?command=ajax.AddRespDropDown&NUMBER_OF_DROP_DOWN=' + currentNumberOfDropDown, true);
xmlhttp.send();
}
The last alert :document.getElementById('calVar').innerHTML return nothing and my varaibles are not created. any ideas?
Thanks alot!!
HTML doesn't have variables, and any that are defined in a <script> without deeper nested scope can be simple defined off the window object.
Instead of trying to insert HTML, just use:
window.cal3 = new CalendarPopup();
then any other script can access this variable now or later.

Categories