I'm trying to get a page with AJAX, but when I get that page and it includes Javascript code - it doesn't execute it.
Why?
Simple code in my ajax page:
<script type="text/javascript">
alert("Hello");
</script>
...and it doesn't execute it. I'm trying to use Google Maps API and add markers with AJAX, so whenever I add one I execute a AJAX page that gets the new marker, stores it in a database and should add the marker "dynamically" to the map.
But since I can't execute a single javascript function this way, what do I do?
Is my functions that I've defined on the page beforehand protected or private?
** UPDATED WITH AJAX FUNCTION **
function ajaxExecute(id, link, query)
{
if (query != null)
{
query = query.replace("amp;", "");
}
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)
{
if (id != null)
{
document.getElementById(id).innerHTML=xmlhttp.responseText;
}
}
}
if (query == null)
{
xmlhttp.open("GET",link,true);
}
else
{
if (query.substr(0, 1) != "?")
{
xmlhttp.open("GET",link+"?"+query,true);
}
else
{
xmlhttp.open("GET",link+query,true);
}
}
xmlhttp.send();
}
** Solution by Deukalion **
var content = xmlhttp.responseText;
if (id != null)
{
document.getElementById(id).innerHTML=content;
var script = content.match("<script[^>]*>[^<]*</script>");
if (script != null)
{
script = script.toString().replace('<script type="text/javascript">', '');
script = script.replace('</script>', '');
eval(script);
}
}
and on certain events, I had to within the script addevent listeners instead of just making a "select onchange='executeFunctionNotIncludedInAjaxFile();'" I had to addEventListener("change", functionName, false) for this. In the script that is being evaluated.
When you update your page by doing something like setting a container's innerHTML to some updated content, the browser simply will not run the scripts in it. You can locate the <script> tags, get their innerHTML (IE may prefer innerTEXT), and then eval() the scripts yourself (which is pretty much what jQuery does, though it finds the scripts with a regex before updating the DOM).
Use this function:
function parseScript(_source) {
var source = _source;
var scripts = new Array();
// Strip out tags
while(source.indexOf("<script") > -1 || source.indexOf("</script") > -1) {
var s = source.indexOf("<script");
var s_e = source.indexOf(">", s);
var e = source.indexOf("</script", s);
var e_e = source.indexOf(">", e);
// Add to scripts array
scripts.push(source.substring(s_e+1, e));
// Strip from source
source = source.substring(0, s) + source.substring(e_e+1);
}
// Loop through every script collected and eval it
for(var i=0; i<scripts.length; i++) {
try {
eval(scripts[i]);
}
catch(ex) {
// do what you want here when a script fails
}
}
// Return the cleaned source
return source;
}
then do parseScript(xmlhttp.responseText); when you're replacing/adding content.
In case some other people stumble upon this old thread, there is one issue with the accepted answer by Deukalion, there is one issue that may have been overlooked: as written, the script only looks for the first script tag. If multiple script tags exist, all others are overlooked.
A few minor tweaks would resolve the issue. Change one line from:
var script = content.match("<script[^>]*>[^<]*</script>");
To:
var script = content.match(/<script[^>]*>[^<]*<\/script>/g);
And another from:
script = script.toString().replace('<script type="text/javascript">', '');
To:
script = script.join("").replace(/<script type="text\/javascript">/g, '');
Now it will gather all the <script> code and execute them in the order found on the page. Otherwise it was an excellent solution.
After the AJAX request, you can make an "on success" function which can take the returned html and do something with it. Then something will be executed.
If there was a code example, then I could provide a code solution to the situation. But using just standard xmlhttprequest, the following could be done:
xhr = new XMLHttpRequest();
xhr.open("GET","ajax_info.txt",true);
xhr.onreadystatechange=function()
{
if (xhr.readyState==4 && xhr.status==200)
{
document.getElementById("myDiv").innerHTML = xhr.responseText;
}
}
xhr.send();
Related
This particular AJAX call is returning "\n" in front of the value returned by responseText.
It was previously not doing that and now when I test for a valid returned code with if (request.responseText == 100) it fails because it now equals "\n100".
I know I could strip off the "\n", but that would be a workaround and I would prefer to find the cause and fix it.
Here's my client-side code:
function AJAX(){
var xmlHttp;
try{
xmlHttp=new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari
return xmlHttp;
}
catch (e){
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
return xmlHttp;
}
catch (e){
try{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
return xmlHttp;
}
catch (e){
alert("Your browser does not support AJAX!");
return false;
}
}
}
}
function logDetails() {
var request,
Result = document.getElementById('Result'),
message = document.getElementById('message'),
url = 'ajax/login.user.php?',
us = document.getElementById('username').value,
pa = document.getElementById('password').value;
Result.innerHTML = 'Logging in...';
if (document.getElementById) {
request = AJAX();
}
if (request) {
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
var r = request.responseText;
//var r = 100;
if (r == '100') {
Result.innerHTML = 'You are now logged in.';
window.location.href = "prebooks.php";
}
else if (r == '101' || r == '102') {
Result.innerHTML = 'Your login attempt failed.';
resetDetails();
}
else if (r == '103') {
Result.innerHTML = 'Sorry, you have no books subscription.';
}
else if (r == '999') {
Result.innerHTML = 'You have no more attempts!';
message.innerHTML = 'Please call us on (02) XXXXXXX so that we can assist you.';
} else {
alert(r);
}
}
};
}
// add my vars to url
url += "arg1="+us+"&arg2="+pa;
request.open("GET", url, true);
request.send(null);
}
Here's my server-side code:
<?= 100 ?>
Ok, I simplified it, but I've tried just echoing '100' directly and the issue remains.
UPDATE
I was mistaken that echoing '100' directly didn't solve the problem. It does. Sorry about that and thanks for pointing me in the right direction.
However, this does leave me with trying to find how the output is being polluted on the server-side.
On the server-side I have a class which handles the authentication and returns a value (100) to be echoed. This is the line:
echo $L->doLogin($pkg);
The lines relating to the return in the doLogin() method are:
$pkg[status]=100;
return $pkg[status];
And to be sure that a newline isn't leaking in some place, if I replace echo $L->doLogin($pkg); with echo 100; it works.
UPDATE 2 - SOLVED
It turns out that the problem was in an included class file which is included within the doLogin() method, which had recently been updated to include a single line-break at the top of the file, before the opening <?.
Many thanks to everyone for your input (I'd still be fumbling around in client-side code without it)!
I had the same problem and discovered (by adding dataFilter option to Ajax with an alert show the stringified JSON returned) that it was really the PHP script which was having syntax problem. PHP server was then pre-pending an HTML mini-document to signal the error. But then, when back to AJAX, as dataType was 'json', the whole returned PHP response was json parsed first, thus stripping off all the HTML prepended and leaving only newlines. These newlines in front of valid JSON returned data was causing the JSON data to be considered syntax error, and that was it ! With dataFilter option sending the raw data in an alert, I was able to see the PHP script initial error and once corrected, no more newlines pre-pended!
i had the same problem and i understood I hit Inter several times in end of page that i incloude to my page and when i delete it my responseText show without \n. :)
example:
_enter
_enter
_enter
I need help figuring out how i can setInterval while keeping a "str" to the function.
The client chooses an option, and the function "GET"'s the selected option.. But when it refreshes in setInterval, it looses the string.. How can i do this?
I have tried this:
<script type="text/javascript">
function countrystats(str)
{
if (str=="")
{
document.getElementById("countrystats").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("countrystats").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","countrystats.php?q="+str,true);
xmlhttp.send();
setInterval(countrystats, 5000);
}
</script>
Hopefully you can help me sort out this mess :-)
I am aware that this can be done with some jQuery, but i cat seem to get that to work. Maybe those two things are related, i dont know :-)
Here is how the function countrystats gets its input:
script type="text/javascript">
$("#countrystats_menu > li > a").click(function (ev) {
var str = $(this).html();
countrystats(str);
$('#country_span').html(str);
});
</script>
EDIT/Solution:
It seems that the problem was, when doing setInterval, it looses the str attached, this code is however preserving it.
setTimeout((function(strPriorToTimeout)
{//IIFE's scope preserves state of str variable
return function()
{
countrystats(strPriorToTimeout);
};
})(str),5000);
The argument str goes out of scope at the end, the interval simply calls the function without passing any value to str. As some comments suggest, countrystats(str) would appear to do the trick, but it doesn't, here's why:
setInterval(countrystats(str), 500);
This line contains multiple expressions that will be evaluated/resolved to some value, like countrystats(str), which is a direct call to a function. The function, then, will be called prior to the interval being set. The quickest solution is creating an anonymous function, and call the function from within:
setInterval(function()
{
countrystats(str);
},5000);
You can even play it extra safe, by creating a closure, actually passing the intended value of str to the interval function. This is optional, and might look a bit confusing (and messy):
setInterval((function(strPriorToTimeout)
{//IIFE's scope preserves state of str variable
return function()
{
countrystats(strPriorToTimeout);
};
})(str),5000);
There is just one thing that's bothering me about your code: you're using setInterval, which repeats the same function call every X ms. If you only need to call a function once, it might be better using setTimeout.
Another thing is: setInterval returns the interval's id, so you can stop the constant function calls if needed. You don't seem to be assigning that ID anywhere, so your code will keep on running, unless you're brute-forcing the clearInterval calls. Perhaps consider assigning the return value of setInterval to some variable you can access.
If you don't the only way of clearing intervals AFAIK would be:
for (var i=0;i<Number.MAX_VALUE;i++)
{
clearInterval(i);
}
Now that's just terrible, isn't it?
In light of the comments, I thought I'd do well adding some info on webworkers here. From what I gather the OP wants to acchieve, I recommended using webworkers as much as possible. A basic setup here could be:
//client.js
var worker = new Worker('dashWorker.js');//worker script
//to kick off the worker:
function countrystats(str)
{
str = str || document.getElementById('countrystats').innerHTML;//get str value
worker.postMessage(str);//that's it, the worker takes care of everything else
}
worker.onmessage = function(response)
{
document.getElementById('countrystats').innerHTML = response.response;//cf worker code
return countrystats(response.str);//choose when to call the countrystats function again, as soon as the worker responded... easy!
};
//the worker:
self.onmessage = function(e)
{//you could add a way of stopping the constant updates, by posting a 'stopDash' or something...
//do ajax call using e.data --> this is the string anyhow
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(response)
{
if (this.readyState === 4 && this.status === 200)
{
self.postMessage({str: e.data,
response: response.responseText});
}
};
xhr.open('GET', 'countrystats.php?q=' + e.data,true);
xhr.send();
};
Of course, this code is far from "clean": it could do with some performance tweaks (like not querying the DOM all the time), but the basic principal stands...
A couple of important links for you here:
MDN
John Resig's blog post on workers
A step-by-step introduction to webworkers
you are calling setInterval(countrystats, 5000); in the same function. you can do with jquery also
url='countrystats.php?q='+str;
ajax calll
$.get(url, function(data) {
$('#countrystats').html(data);
});
once the get finishes. you can call setInterval(countrystats, 5000); for refreshing the content.
I've simplified your code with jQuery. I've used jQuery.load to load the remote html to the start element.
And whenever a new item is clicked you need to create the previous interval, otherwise multiple request threads will be running
function countrystats(str) {
if (str == "") {
$('#countrystats').empty();
return;
}
$('#countrystats').load('countrystats.php?q=' + str)
}
var interval;
$("#countrystats_menu > li > a").click(function(ev) {
if (interval) {
clearInterval(interval);
}
var str = $(this).html();
countrystats(str);
interval = setInterval(function() {
countrystats(str);
}, 5000);
$('#country_span').html(str);
});
How to make javascript code execute on php page which was previously loaded from an ajax call?
code samples:
ajax+function parseScript to force javascript to run on the ajax requested page
Senario: I am selecting a question from selectQuest.php and using ajax it request a page called showRecord.php.
The page showRecord.php will display a table which contain the information corresponding to the quetsion selected.It contains the javascript that do not run.The javascript return will allow me to update info in db when i click submit.
The code sample below is found in the showRecord.php.Finally, if the latter run the showRecord will make another ajax request for updateQuestion.php.
But the javascript is not running in showRecord.php
function show(fileTex,aTex,bTex,cTex,dTex,eTex,newQuestNumTex,textAreaTex,textQuesAnsTex)
{
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)
{
var resp=xmlhttp.responseText;
document.getElementById("txtHint2").innerHTML=resp;
parseScript(resp);
// document.getElementById("txtHint").style.border="1px solid #A5ACB2";
}
}
xmlhttp.open("POST","updateQuestionAdmin.php?param="+fileTex+"&text_A="+aTex+"&text_B="+bTex+"&text_C="+cTex+"&text_D="+dTex+"&text_E="+eTex+"&text_ID="+newQuestNumTex+"&text_Ques="+textAreaTex+"&text_Ans="+textQuesAnsTex,true);
xmlhttp.send();
}
// this function create an Array that contains the JS code of every <script> tag in parameter
// then apply the eval() to execute the code in every script collected
function parseScript(strcode) {
var scripts = new Array(); // Array which will store the script's code
// Strip out tags
while(strcode.indexOf("<script") > -1 || strcode.indexOf("</script") > -1) {
var s = strcode.indexOf("<script");
var s_e = strcode.indexOf(">", s);
var e = strcode.indexOf("</script", s);
var e_e = strcode.indexOf(">", e);
// Add to scripts array
scripts.push(strcode.substring(s_e+1, e));
// Strip from strcode
strcode = strcode.substring(0, s) + strcode.substring(e_e+1);
}
// Loop through every script collected and eval it
for(var i=0; i<scripts.length; i++) {
try {
eval(scripts[i]);
}
catch(ex) {
// do what you want here when a script fails
}
}
}
</script>
As iyrag said, a Javascript framework would help. jQuery has a callback function that you can run when a script is successfully loaded and finished with ajax.
You'll want to execute some other stuff within that callback function, for instance :
$.ajax({
url: 'test.php',
success: function(data) {
$('#result').html(data); // Display script return on some div
someFunction(); // blabla
// Execute some other javascript here, you'll be abble to access the DOM of the test.html
// page because here you'lle be sure that test.html is loaded.showRecord.php should not contain javascript, which would rather be here
}
});
I also posted this because the tag features jQuery...
I have a little script which uses AJAX and PHP to display an image. You can see below that if I call the function mom() it looks in the PHP file index.php?i=mom and displays the image I'm looking for.
But I need the javascript to be lighter as I have 30 images and for each one I have to modify and copy the script below. Is there not a simpler way to have the functions be different and still call a different page?
<script type="text/javascript">
function mom()
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
HandleResponse(xmlHttp.responseText);
}
}
xmlHttp.open("GET", "index.php?i=mom", true);
xmlHttp.send(null);
}
function HandleResponse(response)
{
document.getElementById('mom').innerHTML = response;
}
</script>
My Trigger is this
<a href="#" onclick='mom();' />Mom</a>
<div id='mom'></div>
You could modify your function so it takes a parameter :
// The function receives the value it should pass to the server
function my_func(param)
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
// Pass the received value to the handler
HandleResponse(param, xmlHttp.responseText);
}
}
// Send to the server the value that was passed as a parameter
xmlHttp.open("GET", "index.php?i=" + param, true);
xmlHttp.send(null);
}
And, of course, use that parameter in the second function :
function HandleResponse(param, response)
{
// The handler gets the param too -- and, so, knows where to inject the response
document.getElementById(param).innerHTML = response;
}
And modify your HTML so the function is called with the right parameter :
<!-- for this first call, you'll want the function to work on 'mom' -->
<a href="#" onclick="my_func('mom');" />Mom</a>
<div id='mom'></div>
<!-- for this secondcall, you'll want the function to work on 'blah' -->
<a href="#" onclick="my_func('blah');" />Blah</a>
<div id='blah'></div>
This should work (if I understand correctly)
<script type="text/javascript">
function func(imgName)
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
document.getElementById(imgName).innerHTML =
}
}
xmlHttp.open("GET", "index.php?i=mom", true);
xmlHttp.send(null);
}
</script>
MARTIN's solution will work perfectly.
By the way you should use some javascript framework for Ajax handling like jQuery.
It will make your life easy.
If you are having light weight images you preload the images on your page.
I solved this by making an array of in your case xmlHttp and a global variable, so it increments for each request. Then if you repeatedly make calls to the same thing (eg it returns online users, or, whatever) then you can actually resubmit using the same element of the array too.
Added example code:
To convert it to a reoccuring event, make a copy of these 2, and in the got data call, just resubmit using reget
var req_fifo=Array();
var eleID=Array();
var i=0;
function GetAsyncData(myid,url) {
eleID[i]=myid;
if (window.XMLHttpRequest)
{
req_fifo[i] = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
req_fifo[i] = new ActiveXObject("Microsoft.XMLHTTP");
}
req_fifo[i].abort();
req_fifo[i].onreadystatechange = function(index){ return function() { GotAsyncData(index); }; }(i);
req_fifo[i].open("GET", url, true);
req_fifo[i].send(null);
i++;
}
function GotAsyncData(id) {
if (req_fifo[id].readyState != 4 || req_fifo[id].status != 200) {
return;
}
document.getElementById(eleID[id]).innerHTML=
req_fifo[id].responseText;
req_fifo[id]=null;
eleID[id]=null;
return;
}
function reget(id) {
myid=eleID[id];
url=urlID[id];
req_fifo[id].abort();
req_fifo[id].onreadystatechange = function(index){ return function() { GotAsyncData(index); }; }(id);
req_fifo[id].open("GET", url, true);
req_fifo[id].send(null);
}
The suggestions to parameterize your function are correct and would allow you to avoid repeating code.
the jQuery library is also worth considering. http://jquery.com
If you use jQuery, each ajax call would literally be this easy.
$('#mom').load('/index.php?i=mom');
And you could wrap it up as follows if you'd like, since you say you'll be using it many times (and that you want it done when a link is clicked)
function doAjax(imgForAjax) { $('#'+imgForAjax).load('/index.php&i='+imgForAjax);}
doAjax('mom');
It makes the oft-repeated ajax patterns much simpler, and handles the issues between different browsers just as I presume your getXMLhttp function does.
At the website I linked above you can download the library's single 29kb file so you can use it on your pages with a simple <script src='jquery.min.js'></script> There is also a lot of great documentaiton. jQuery is pretty popular and you'll see it has a lot of questions and stuff on SO. ajax is just one of many things that jQuery library/framework (idk the preferred term) can help with.
Lets say I have an array of javascript objects, and I am trying to pass those objects to a php page to save them into a database. I have no problems passing a variable to the php and using $_POST["entries"] on that variable but I can't figure out how to pass an entire array of objects, so I can access my objects.entryId and .mediaType values on the php page.
Oh and before anyone asks, yes the reason I need to do it this way is because I have a flash uploader, that you guessed it.. uploads into a CDN server (remote) and the remote server only replies back with such js objects.
Thanks for any help anyone can provide.
Here is my JS functions:
function test() {
entriesObj1 = new Object();
entriesObj1.entryId = "abc";
entriesObj1.mediaType = 2;
entriesObj2 = new Object();
entriesObj2.entryId = "def";
entriesObj2.mediaType = 1;
var entries = new Array();
entries[0] = entriesObj1;
entries[1] = entriesObj2;
var parameterString;
for(var i = 0; i < entries.length; i++) {
parameterString += (i > 0 ? "&" : "")
+ "test" + "="
+ encodeURI(entries[i].entryId);
}
xmlhttp.open("POST","ajax_entries.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", parameterString.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.onreadystatechange = handleServerResponseTest;
xmlhttp.send(parameterString);
}
function handleServerResponseTest() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
else {
alert("Error during AJAX call. Please try again");
}
}
}
maybe you need to take a look at json and jQuery ajax methods:
.- http://blog.reindel.com/2007/10/02/parse-json-with-jquery-and-javascript/
.- http://us.php.net/json_decode
The turorial is maybe a little outdated because jQuery last version is 1.3.x but you will get an idea on that and about the PHP json functions... if your server does not have the json extension enabled you can use some php classes:
.- http://google.com.co/search?rlz=1C1GPEA_enVE314VE314&sourceid=chrome&ie=UTF-8&q=php+json+class
good luck!
I too had the same trouble. But googling dint help.
I tried myself to tweak and test. And I got it. I am using POST method though. Please try the idea with GET method. Here is the idea:
Append the array index value within square brackets to the Post/Get variable name for array. Do this for each array element.
The part var parameters="&Name[0]="+namevalue1+"&Name[1]="+namevalue2; of the following script would give you a hint.
This is the test JS, I used (Again this uses POST method not GET):
var xmlAJAXObject;
function test() {
xmlAJAXObject=GetxmlAJAXObject();
if (xmlAJAXObject==null) {
alert ("Oops!! Browser does not support HTTP Request.");
return false;
}
var namevalue1=encodeURIComponent("Element 1");
var namevalue2=encodeURIComponent("Element 1");
var parameters="&Name[0]="+namevalue1+"&Name[1]="+namevalue2;
xmlAJAXObject.open("POST", "test.php", true);
xmlAJAXObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlAJAXObject.setRequestHeader("Content-length", parameters.length);
xmlAJAXObject.onreadystatechange=stateChanged;
xmlAJAXObject.send(parameters);
}
function stateChanged() {
if (xmlAJAXObject.readyState ==4) {
if (xmlAJAXObject.status == 200) {
alert('Good Request is back');
document.getElementById("show").innerHTML=xmlAJAXObject.responseText;
}
}
}
function GetxmlAJAXObject() {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject) {
// code for IE6, IE5
return new ActiveXObject("Microsoft.Microsoft.XMLHTTP");
}
return null;
}
This worked for me. Sorry for the formatting and incomplete code. I meant to give a direction. Google reault websites couldn't give a solution. Hope you find this useful.