Executing Javascript through AJAX debug - php

Whats wrong with this code or what might be causing this problem? It's not alerting "hello", but it is filling the div with The Hello and Bye World tables. I want it to alert "hello". Also I don't know jquery. Thank You
FILE1
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){
var reScript = /\<script.*?>(.*)<\/script>/mg;
response = xmlhttp.responseText.replace(reScript, function(m,m1) {
eval(m1);
return "";
});
document.getElementById("div").innerHTML=response;
}
}
xmlhttp.open('GET','file2.php',true);
xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlhttp.send();
FILE2
<table><tr><td>Hello World</td></tr></table>
<script type="text/javascript">
alert('hello');
</script>
<table><tr><td>Bye World</td></tr></table>

Try without the eval():
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){
/*var reScript = /\<script.*?>(.*)<\/script>/mg;
response = xmlhttp.responseText.replace(reScript, function(m,m1) {
eval(m1);
return "";
});*/
document.getElementById("div").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open('GET','file2.php',true);
//xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded'); //unnecessary for GET calls
xmlhttp.send(null);
Evaluing your code inside the <script...></script> is unnecessary, the javascript code will be executed as soon as it's added to the DOM.
New edit:
You have to eliminate the linebreaks \n\r in your reponseText in order for your script to be evaluated properly. Also, there was an extra \ escape character before the first < which was breaking your code. Try:
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){
var reScript = /<script.*?>(.*)<\/script>/mg;
response = xmlhttp.responseText.replace(/\n|\r/g, " ").replace(reScript, function(m,m1) {
eval(m1);
return "";
});
document.getElementById("div").innerHTML=response;
}
}
xmlhttp.open('GET','file2.php',true);
//xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlhttp.send(null);
I've added a .replace(/\n|\r/g, " ") to replace all line breaks by an white space in your responseText, which will allow for your JS to be evaluated properly and cause no visible change to the end-user. You may also replace the white space " " by an empty string "" if all of your JS is properly semi-colon'd.
The above should work fine for simple scripts, now if you'd include the JQuery lib in your page's head:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
Your AJAX call would be as simple as:
<script type="text/javascript">
$(document).ready(function(){
$('#div').load('file2.php');
});
</script>
JQuery automatically parses scripts from your responseText, as noted in your linked answer.

Give this a try:
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
var reScript = /<script.*?\>(.*)<\/script\>/mg.exec(xmlhttp.responseText)[1];
var scriptElement = document.createElement('script');
scriptElement.innerHTML = reScript;
document.body.appendChild(scriptElement);
}
}
Placing the code into a script element, and then appending that element to the body should cause it to execute.

Related

Refresh div every two seconds using ajax without jquery

I made a chat website. And it has a div with id=chatlogs. I want it to get chatlogs from logs.php every 2 seconds. How can I do that? I want to use ajax with it and avoid using jquery.
You can do smoething like this:
<script>
setInterval(refresh_logs(), 2000); // 2000 = 2 Seconds
function refresh_logs()
{
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("logs_div").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","get_logs.php",true);
xmlhttp.send();
}
</script>

Data is not stored into $_POST array from ajax request

So I've already done an AJAX request using GET, and so now i wanted to try my luck using POST instead. But for some reason, when i try to send data, I get a crazy weird message in the console - NS_ERROR_XPC_JSOBJECT_HAS_NO_FUNCTION_NAMED: 'JavaScript component does not have a method named: "available"' when calling method: [nsIInputStream::available]
I literally have no idea what this means, and I know the data isnt going through because all im doing in the load.php file that I request is echo the variable its supposed to store. So its something in the javascript.
Here is my HTML for the first page that makes the request.
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript" src="test.js"></script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<input id="input">
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>
And my Javascript:
function loadXMLDoc()
{
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("myDiv").innerHTML=xmlhttp.responseText;
}
}
var data = "id="+document.getElementById("input").value;
xmlhttp.open("POST","load.php",true);
xmlhttp.send(data);
}
And finally, the code for load.php:
$param = $_POST['id'];
if($param){
echo "Variable was stored.";
} else{
echo "Not working";
}
And everytime i run this, i get "not working" in the browser. So the php code is at least attempting to store the variable, but its not. Thankyou!
Your forgot to add xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'). With this line we are basically saying that the data send is in the format of a form submission
function loadXMLDoc()
{
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("myDiv").innerHTML=xmlhttp.responseText;
}
}
var data = "id="+document.getElementById("input").value;
xmlhttp.open("POST","load.php",true);
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send(data);
}

Backbutton With Ajax loading Content

This will load the content to the page and change the URL. The problem is that the back button and the forward won't load the content agin. They only change the URL. How can I make them load the function?
<a onclick="load_content('p1');" >Page1</a>
<a onclick="load_content('p2');" >Page2</a>
function load_content(name)
{
window.history.pushState(null, null, "/?page=" + name + "");
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("response").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","load_content.php?name=" + name + "",true);
xmlhttp.send();
}
In the history.pushState, save all relevant data that is dynamic and then listen to the popState event and replace all elements just like you would do with AJAX.

ajax and portable OSes

Well, i have an select list in my php page and i want to refresh only that with new data from my database.Idone it using ajax but on android or other mobiles OSes this messes up the layout.Is there a problem with protable OSes and ajax?Can you give me any hints to solve this problem?
Edited
/*function loadXMLDoc()
{
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)
{
var sel1 = document.getElementById("select1");
var selectedI = sel1.selectedIndex;
var i=0;
var excode = excur[selectedI];
var val = sel1.options[selectedI];
excursioncode=excode;
excindex = selectedI;
val.innerHTML = xmlhttp.responseText;
//alert(xmlhttp.responseText);
//setTimeout("loadXMLDoc();",10000);
}
}
xmlhttp.open("POST","<?php echo SITE_ROOT;?>ajaxphp/ajax_get_seats.php?excode="+excursioncode+"&date="+selected_date,true);
xmlhttp.send();
}
function timedRefresh(timeoutPeriod) {
tm=setTimeout("loadXMLDoc();",timeoutPeriod);
}
*/
This is some code that is doing the job.On a regular pc is working but on a mobile browser brings up problems.Anyu ideas
If the problem were with the AJAX, it would not be causing layout issues. Instead the problem is most likely with your implementation of using the data retrieved by AJAX. However, I can't provide any more insights because I have no clue what you're working on and have never experienced such a problem.

XMLHttpRequest to PHP script - what's missing here?

This is my first time using AJAX, and I'm trying to send JS variables to a PHP script. I've got an XMLHttpRequest but it doesn't seem complete - what am I missing?
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
else {
document.write("Geolocation is required for this page.");
}
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
// document.write("<a href='http://api.geonames.org/findNearbyPlaceNameJSON?lat="+lat+"&lng="+lng+"&username=sebastiano'>my town</a>");
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","location.php?lat=position.coords.latitude",true);
xmlhttp.send();
// SOMETHING MISSING HERE?
}
function errorFunction(position) {
document.write("Error");
}
It appears that you're not passing the contents of your variable to the open command.
xmlhttp.open("GET","location.php?lat=position.coords.latitude",true);
in this example your lat will contain a string with contents "position.coords.latitude"
instead try
xmlhttp.open("GET","location.php?lat="+position.coords.latitude,true);
Or better yet, use the variables you created at the top of the function and pass both long and lat in.
xmlhttp.open("GET","location.php?lat=" + lat + "&long=" + lng,true);
you are sending it with "position.coords.latitude" as value...
try xmlhttp.open("GET","location.php?lat=" + position.coords.latitude,true);
Also, take a look at jQuery
Try this:
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){
console.log(xmlhttp.responseText);
}
}
xmlhttp.open("GET","location.php?lat=" + position.coords.latitude,true);
xmlhttp.send();

Categories