How to run Ajax script on load of an HTML page? - php

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.

Related

SimpleXMLElement slow performance

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);
}
}

script within a php page not executed when called using ajax

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('');
}

How to add a PHP template to a dynamically generated Javascript code

I'm using Code Igniter and the Googlemaps library. This library generates a lot of Javascript code dynamically, including the contents of the InfoWindows for each new marker, but I'd like to keep that in a separate template file, like a regular View.
I have this Javascript code (from Googlemaps' library):
var lat = marker.getPosition().lat();
var long = marker.getPosition().lng();
var windowContent = "";
if( _new ) {
var newIW = new google.maps.InfoWindow( { content: windowContent } );
What I want to do is to load windowContent from a template file. I have already succeeded in dynamically generating a form for this variable and using lat and long variables defined just above, but how can I achieve this in Code Igniter? I can't use load->view because I'm not in a Controller's context. And I cannot use include() or readfile() either because of CI's security constraints.
Any hints?
Using pure javascript, get the lat and long, make a url with the lat and long in the query string, and use xhr to do the ajax call.
var lat = marker.getPosition().lat();
var long = marker.getPosition().lng();
var xhr;
var url = "http://myurl.to/script.php?lat="+lat+"&lng="+long;
if(typeof XMLHttpRequest !== 'undefined')
xhr = new XMLHttpRequest();
else {
//Get IE XHR object
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){}
}
}
xhr.onreadystatechange = function(){
//This function is called every so often with status updates
//It is complete when status is 200 and readystate is 4
if(xhr.status == 200 && xhr.readyState === 4) {
//Returned data from the script is in xhr.responseText
var windowContent = xhr.responseText;
//Create the info window
var newIW = new google.maps.InfoWindow( { content: windowContent } );
//Pass newIW to whatever other function to use it somewhere
}
};
xhr.open('GET', url, true);
xhr.send();
if using a library like jQuery it would be like
var lat = marker.getPosition().lat();
var long = marker.getPosition().lng();
var url = "http://myurl.to/script.php";
jQuery.ajax({
"url":url,
"data":{ //Get and Post data variables get put here
"lat":lat,
"lng":long
},
"dataType":"html", //The type of document you are getting, assuming html
//Could be json xml etc
"success":function(data) { //This is the callback when ajax is done and successful
//Returned data from the script is in data
var windowContent = data;
//Create the info window
var newIW = new google.maps.InfoWindow( { content: windowContent } );
//Pass newIW to whatever other function to use it somewhere
}
});

split return data from old way ajax

i have page that do add new record by old way ajax, this code was add new record and return the error or done result message , how can i print the message on div and print result on other div. i try but some one tell me to use JOSN, how can i do that
<script language="JavaScript">
$(document).ready(function() {
});
$("#closeerr").live('click', function() {
$("#gadget").hide();
});
var HttPRequest = false;
function doCallAjax(Mode,Page,ID) {
HttPRequest = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
HttPRequest = new XMLHttpRequest();
if (HttPRequest.overrideMimeType) {
HttPRequest.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) { // IE
try {
HttPRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
HttPRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!HttPRequest) {
alert('Cannot create XMLHTTP instance');
return false;
}
var url = 'AjaxItemsGroupsRecord.php';
var pmeters = "titems_groups_GroupName=" + encodeURI( document.getElementById("items_groups_GroupName").value) +
"&titems_groups_sys_type_ID=" + encodeURI( document.getElementById("items_groups_sys_type_ID").value ) +
'&myPage='+Page +
"&tID=" + ID +
"&tMode=" + Mode;
HttPRequest.open('POST',url,true);
HttPRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
HttPRequest.setRequestHeader("Content-length", pmeters.length);
HttPRequest.setRequestHeader("Connection", "close");
HttPRequest.send(pmeters);
HttPRequest.onreadystatechange = function()
{
if(HttPRequest.readyState == 3) // Loading Request
{
document.getElementById("mySpan").innerHTML = "looding";
}
if(HttPRequest.readyState == 4) // Return Request
{
document.getElementById("mySpan").innerHTML = HttPRequest.responseText;
}
}
}
</script>
If jQuery is an option... As mentioned in my comment I'd recommend you try out jQuery http://jquery.com/ as you look to be fairly new to JavaScript.
It makes AJAX requests a lot simpler and you don't have to worry about making XMLHttpRequest work cross browser.
For making an actual AJAX request see: http://api.jquery.com/jQuery.ajax/
Now if you want to use JSON you need to convert the data to return in your PHP script.
This is really easy, you just pass the data in json_encode() and it will convert the data to a JSON string. You then just echo it out so that it's returned to the AJAX request.
echo json_encode($data);
Now if you've setup your AJAX request to expect a JSON response then you can use the data that comes back. So something like this:
$.ajax({
url: 'request.php', // the php you want to call
dataType: 'json' // the type of data being returned
}).done(function(json) {
// you now have a json object
});
If you can only use native JavaScript...
If you can't use jQuery then it roughly works the same way. You'd have the code in your example for the AJAX request. You'd still use json_encode() in the PHP. The only difference is when the data comes back you'd need to parse it like so:
JSON.parse(json);
For more info on this last bit checkout: Parse JSON in JavaScript?

javascript send one way message to php

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);
}
}

Categories