Please read below my scenario…
I have a PHP file wherein I have javascript within it..
<?php
echo ‘<script>’;
echo ‘window.alert(“hi”)’;
echo ‘</script>’;
?>
On execution of this file directly, the content inside the script is executed as expected. But if this same page is being called via ajax from another page, the script part is NOT executed.
Can you please let me know the possible reasons.
(note: I’m in a compulsion to have script within php page).
When you do an AJAX call you just grab the content from that page. JavaScript treats it as a string (not code). You would have to add the content from the page to your DOM in your AJAX callback.
$.get('/alertscript.php', {}, function(results){
$("html").append(results);
});
Make sure you change the code to fit your needs. I'm supposing you use jQuery...
Edited version
load('/alertscript.php', function(xhr) {
var result = xhr.responseText;
// Execute the code
eval( result );
});
function load(url, callback) {
var xhr;
if(typeof XMLHttpRequest !== 'undefined') xhr = new XMLHttpRequest();
else {
var versions = ["MSXML2.XmlHttp.5.0",
"MSXML2.XmlHttp.4.0",
"MSXML2.XmlHttp.3.0",
"MSXML2.XmlHttp.2.0",
"Microsoft.XmlHttp"]
for(var i = 0, len = versions.length; i < len; i++) {
try {
xhr = new ActiveXObject(versions[i]);
break;
}
catch(e){}
} // end for
}
xhr.onreadystatechange = ensureReadiness;
function ensureReadiness() {
if(xhr.readyState < 4) {
return;
}
if(xhr.status !== 200) {
return;
}
// all is well
if(xhr.readyState === 4) {
callback(xhr);
}
}
xhr.open('GET', url, true);
xhr.send('');
}
Related
I have myfile.php, want to run this file first in myfile.html on load by using an ajax script. If its possible to do that? How? I don't want to use include and require.
If i understand your question you can try .load method in jquery for example
$(document).ready(function(){
$("#contents").load('url to myfile.php');
});
Yes. Using simple Javascript - jQuery or any other library isn't required. First, Define xhr:
var xhr;
if( window.XMLHttpRequest ) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject( 'Microsoft.XMLHTTP' );
}
Then, call the file, and output the result into an element with id="output" attribute:
var method, url, async;
method = 'get'; // Request - GET or POST?
url = 'myfile.php';
async = true; // asynchronous - true, synchronous - false
xhr.onreadystatechange = function() {
if( this.status === 200 && this.readyState === 4 ) {
document.getElementById( 'output' ) = this.responseText;
} else {
// File does not exist -or- any possible error
document.getElementById( 'output' ) = 'An error occurred';
}
}
xhr.open( method, url, async );
xhr.send();
Learn more about Ajax on MDN.
I am using SimpleXMLElement() to obtain data from a website, which is used to embed data. The code I am using is as follows:
$rss = new SimpleXMLElement('http://eliteprospects.com/rss_player_stats2.php?player='.$player_array[0]['embed_stats'], null, true);
foreach($rss->xpath('channel/item') as $item)
{
echo utf8_decode($item->description);
}
This works great, except for one issue, the data loads exceptionally slow from the other site. The page load goes from approximately 0.5-1s to 2.5-3s.
Is there a method that I can use, to load the asynchronously, or is there a faster function I should be using instead?
An idea that came to mind was to load a separate page within an iFrame after the initial page load, or is there a better method?
Is there a method that I can use, to load the asynchronously, or is
there a faster function I should be using instead?
Unfortunately, there is nothing to do about the long response time (trivially assuming that connection speed in not archaic). Also echoing out the results all at once might slow down the browser rendering and thus the page load time.
AJAX fits nicely here - wait for window.onload and trigger the AJAX call to your webservice (holds the snippet from question) to prepare the output buffer and return the response to browser. Afterwards set/replace the innerHTML value of selected DOM element with the response.responseText.
Pseudo-code
window.onload = function()
{
var url = 'http://example.com/webserice';
Ajax.get(url, function(response)
{
var responseText = response.responseText;
document.getElementById('someid').innerHTML = responseText;
}
}
The snippet I am using in pure JS, although jQuery has a lot more appealing way to do it
Ajax = {
request : {},
createRequest : function()
{
var request = false;
if (window.XMLHttpRequest)
{
request = new XMLHttpRequest();
}
else
{
if (window.ActiveXObject)
{
request = new ActiveXObject('MSXML2.XMLHTTP.3.0');
}
else
{
request = false;
}
}
return request;
},
get : function(page, callback)
{
var self = this;
var request = this.createRequest();
if (! page)
{
return false;
}
request.onreadystatechange = function()
{
if (request.readyState == 4 && request.status == 200)
{
delete self.request;
if (typeof callback == 'function')
{
callback(request);
}
else
{
self.update(request, callback);
}
var regex = /<script\b.*?>([\s\S]*?)<\/scri/ig;
var match;
while (match = regex.exec(request.responseText))
{
eval(match[1]);
}
}
}
request.open('GET', page, true);
request.setRequestHeader('X-Requested-With', 'ajax');
request.send(null);
}
}
All,
I have a fairly simple javascript script that changes some text in my html page. The weird thing is that the data is only changed if I have an alert. If I hide the alert as a comment, the data doesn't appear on the webpage. To be specific, here are the relevant pieces of the JS code:
var index=0;
var xmlObject=null;
function calcIndex(){
return index++;
}
function showNextName(){
retrieveNextName();
var someText = xmlObject.getElementsByTagName("name")[0].childNodes[0].nodeValue;
document.getElementById('nextName').innerHTML=someText;
}
function retrieveNextName(){
var index=calcIndex();
request = createRequest();
if (request == null) {
alert("Unable to create request");
return;
}
var url= "Ajax_retrieveName.php?index=" + index;
request.open("GET", url, true);
request.onreadystatechange = createXml;
request.send(null);
alert("abc");
//If the alert above is missing, the html is not modified...
}
function createXml() {
if (request.readyState == 4) {
if (request.status == 200) {
xmlObject = request.responseXML;
}else{
return;
}
}else{
return;
}
}
Does anyone know what might be causing that?
The problem is that XML object is not immediately available, because the request isn't finished yet, so the callback hasn't been called yet. (Alerting allows the request to finish in the time before you clock the alert box away.)
A better solution would be to have an updateElementHtml(newHtml) function and call that from within the callback.
I have problem with the site I'm developing. The dynamically loaded div (ajax) is empty in IE9 and works poorly on firefox (php doesn't compile) and I can read the source of my php file in the div.
I've tried a lot of solutions like changing from GET to POST or adding a unique id to the url or making an async request but the content is absolutely empty. Any ideas? thanks
function pageload(hash) {
if(hash == '' || hash == null)
{
document.location.hash = "#php"; // home page
}
if(hash)
{
getPage();
}
}
function getUniqueTime() {
var time = new Date().getTime();
while (time == new Date().getTime());
return new Date().getTime();
}
function getPage() {
var str = getUniqueTime();
console.log(str);
var data = 'page=' + encodeURIComponent(document.location.hash);
$('#content').fadeOut(200);
$.ajax({
url: "loader.php?_=" + str,
type: "POST",
data: data,
cache: false,
success: function (html) {
$('#content').fadeIn(200);
$('#content').html(html);
}
});
}
EDIT:
//loader.php
<?
require_once('session.class.php');
require_once('user.class.php');
$se = new session();
$lo = new user();
$se->regenerate();
if(isset($_POST))
{
$alpha = (string) $_POST['page'];
if($alpha == '#php')
{
include 'homeloader.php';
}
else if($alpha == '#cplus')
{
include 'cplusloader.php';
}
else if($alpha == '#web')
{
include 'underloader.php';
}
else if($alpha == '#about')
{
include 'underloader.php';
}
else if($alpha == '#social')
{
include 'socialloader.php';
}
}
else
$page = 'error';
echo $page;
?>
try this:
//on click of a button:
$("#button").live("click", function(){
//get you string data
var str = "test";
//do new version of ajax
$.post("loader.php", {str:str}, function(html){
$('#content').html(html);
});
});
and you dont need to do AJAX method anymore $.post works amazing
php doesn't compile? async request? actually not specifying ascync: true the request is executed asyncroniously and in version jQuery 1.8 there is no sync AJAX requests at all. Attach an error handler and you will see that your request probably results an error:
...
cache: false,
success: function (html) {
$('#content').fadeIn(200);
$('#content').html(html);
},
error: function (a,b) {
alert('Error!');
}
...
Normally AJAX consists of 2 parts - client side and server side. I don't see serverside posted in your question. You have to check both of them. Make a simple loader.php returning the string success and get rid of all extra get params. First test your php file in browser to be sure that it works. Check FireBug for javascript errors ...
How can I use javascript to send a one way message to php? I would like to get the browser information from javascript and just send it to php in the background. I know I can get some of this from php, but I'd rather use javascript. Is there a way to do this without a framework like jquery?
Yes, you can do it with something like this:
function xmlhttpPost(strURL) {
var xmlHttpReq = false;
var self = this;
// Mozilla/Safari
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
} else if (window.ActiveXObject) {
// IE
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
alert('Here goes something');
self.xmlHttpReq.send('browser info here');
}
}
}
This will send "browser info here" as POST in the php page you pass to the function as url. I didnt test it though
You would have to submit an AJAX request to a PHP script. Yes, you could do it without using a framework but I wouldn't advise it.
You need to make an AJAX call to a PHP page, preferably using POST. Any data you want to send needs to be sent along with the request.
I recommend using a framework such as jQuery, but if you insist on using raw JavaScript, you want to research XMLHttpRequest.
// fix for older IE versions
// see http://blogs.msdn.com/b/xmlteam/archive/2006/10/23/using-the-right-version-of-msxml-in-internet-explorer.aspx
if( typeof window.XMLHttpRequest === 'undefined' &&
typeof window.ActiveXObject === 'function') {
window.XMLHttpRequest = function() {
try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(e) {}
try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(e) {}
return new ActiveXObject('Microsoft.XMLHTTP');
};
}
function postData(url, data, errhandler) {
var req = new XMLHttpRequest;
req.onreadystatechange = function() {
if(this.readyState === 4 && this.status !== 200 && errhandler)
errhandler(this);
};
try {
req.open('POST', url, true); // async post request
req.send(data);
}
catch(e) {
if(errhandler)
errhandler(req);
}
}