I have a page with a dialog window which sends ajax post data to server and receives a response. During development, there can be two responses - one regular (this is not the question) or one with an error. Server returns code 500 and a page with lot of debug informations. This is a regular page returned from a framework and contains some javascript code. I want to be able to display this error page in case it happens.
The problem is, I can not simply attach the returned result to body element or open a new link in a new page and load this error again. I simply get a html page instead of data and I have to display the page (in current window or in another one).
I am using jQuery.
Configure jQuery ajax setup as follows:
$.ajaxSetup({
error: handleXhrError
});
where handleXhrError function look like this:
function handleXhrError(xhr) {
document.open();
document.write(xhr.responseText);
document.close();
}
See also:
Handling of server-side HTTP 4nn/5nn errors in jQuery
You may also try to use data URL's, the latest versions of the major browsers supporting it:
function utf8_to_b64( str ) {
return window.btoa(unescape(encodeURIComponent( str )));
}
function loadHtml(html)
{
localtion.href='data:text/html;base64,'+utf8_to_b64(html);
}
This way, you can load any html page you want in runtime.
In your ajax callback:
success: function (data) {
$("html").html($(data).find("html").html());
}
That will replace the entire page's HTML content with the one received from your AJAX request. Works in Chrome... not sure about IE.
Despite that, I'm not sure why you'd want to include the <head> section... but you can easily modify the above to display just what's in the body of the AJAX response, and append it to a div or even a lightbox. Much nicer.
Here is an example of how to change either if the response is a url or a html content (using django\php)
var xmlhttp;
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
var replace_t = '{{ params.replace_t }}';
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
if(replace_t == 'location')
window.location.replace(xmlhttp.responseText);
else if(replace_t == 'content')
{
document.open();
document.write(xmlhttp.responseText);
document.close();
}
}
}
xmlhttp.open("GET",SOME_ASYNC_HANDLER_URL,true);
xmlhttp.send();
I found this solution. I don't know if it si correct, but for Opera and Firefox it is working.
var error_win = window.open(
'',
'Server error',
'status=0,scrollbars=1, location=0'
);
error_win.document.write(XMLHttpRequest.responseText);
Have you tried just simply creating an element and inserting the returned error page into the element? I do this with error pages and jQuery.
var errorContainer = $( '<div/>' );
errorContainer.html( errorTextResponse );
errorContainer.appendTo( $( 'body' ) );
I may be misunderstanding, but do you know what elements from the result you specifically want to display? You could trying something like this:
success: function(data){
//store the response
var $response=$(data);
//use .find() to locate the div or whatever else you need
var errorMessage = $response.find('#warning').text();
alert(errorMessage);
}
Is that what you were looking for?
I don't think there's any way to do that. Iframes are meant for loading other pages and there's no other sandbox in which to dump a standalone page -- that's what frames were designed for.
It might be difficult with the framework you're using, but it's probably worthwhile to have it generate different errors for your Ajax requests. My Ajax pages will only ever send
{"exit": 1, "message": "As in the shell, a non-zero exit is an error and this is why..."}
Just figured this out
as easy as
document.body.innerHTML = YourAjaxrequest.responseText;
_______________________________________________^ up here is what over writes your current HTML page with the response.
request.onreadystatechange = function() {
if (request.readyState == 1) {
document.getElementById('sus').innerHTML = "SENDING.......";
}
if (request.readyState == 3){
document.getElementById('sus').innerHTML = "SENDING >>>>>>>>>>>>>";
}
if (request.readyState == 4 && request.status == 200) {
//document.getElementById('sus').innerHTML = request.responseText;
document.body.innerHTML = request.responseText;
}
}
request.send(formD);
},false);
Related
my code works only if i add this code:
document.write(str);
which open a new page and write in it insert data in database
but if i try to the code without it like this :
function addcourse2(str,cn)
{
xmlhttp=new XMLHttpRequest();
//document.write(str);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4 && xmlhttp.status == 200) {
alert('response:'+xmlhttp.responseText);
} else {
alert('failure!');
}
};
xmlhttp.open("GET","tpages/addcourse2.php?q="+str+"&p="+cn,true);
xmlhttp.send();
}
here i get alert message failure and nothing gets inserted into database
i need and explanation to this a way to fix it
looking at your comments i understand that the page is refreshing after you click the button before the state is reaching 4 then this is the button code to prevent it from refreshing
add return false;
<button "onclick='addcourse2("value1","value2");return false;'>add course</button>
Let's try to describe.
Note: as document.write writes to the document stream, calling document.write on a closed (loaded) document automatically calls document.open.
https://developer.mozilla.org/en-US/docs/Web/API/Document/write
So, this AJAX script with document.write work as from new page and each case calls to URL ""tpages/addcourse2.php?q="+str+"&p="+cn"
If commented document.write Then browser may be cached URL and browser read from cache and doesn't call same URL. So, you can use unique URL string and test so.
Also, may be was an other case.
I know that this question has been asked before but all of them are using jQuery library and i would like to use Javascript only, no libraries so please bear with me.
This link shows the PHP function being called from jQuery.
How can I call PHP functions by JavaScript?
The code is calling a function that displays images.
I have the following code and I don't understand how to call the function from the mainfile.php and not functions.php.
mainfile.php
<button id="btn">Click</btn> // button that calls ajax file
<div id="div"></div> // div where it should appear
<script>
function loadXML(method, url, div, index)
{
var xmlhttp;
try
{
xmlhttp = new XMLHttpRequest();
}
catch(e)
{
try
{
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
catch(e)
{
alert('sorry');
}
}
xmlhttp.onreadystatechange = function()
{
if( xmlhttp.readyState === 4 && xmlhttp.status === 200 )
{
if( index === null || index === 'undefined' || xmlhttp === '')
{
document.getElementById(div).innerHTML = xmlhttp.responseText;
}
}
};
xmlhttp.open(method, url, true);
xmlhttp.send(null);
}
document.getElementById('btn').addEventListener('click', function()
{
loadXML('GET', 'imgs.php', 'div', null);
}, false);
</script>
functions.php
<?php
function getImgs($dir, $type)
{
$images = glob($dir . $type);
print_r($images); // for now i'm printing the array the way it is to see the function work
}
getImgs('images/', '.*JPG'); // calling function from php file works
?>
I would like to call the function from inside mainfile.php without using any jQuery library, only plain Javascript, it should be possible considering that the libraries are made with Javascript. I don't know where to call the function from inside mainfile.php. Any help would be appreciated.
The reason I am getting files from php is because it is easier to load them into the DOM, I need to make an image gallery so I would like to know if it will be possible to manipulate the images when they are loaded into the DOM using AJAX.
You can only do it by Making an AJAX request to a php page while passing in a parameter to initialise the function.
That means your AJAX will send in for example "functionName" to the php page "functionsListPage.php"
The GET will be recieved :
if (isset($_GET['functionName']))
functionExec();
This is the only way so you are not calling direct from the client however you are indicating to the server you want to run a predefined request.
You cannot call a PHP function directly from the clientside.
It's just like the answer from #Pogrindis, but i think so explanation is needed
It is possible to do it with with plain JavaScript with a little workaround!
What you need to do is the following in JavaScript after the xmlhttp.open();
var functionname = getImgs;
xmlhttp.open();
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
xmlhttp.send(functionname);
What this does is simple: it sends the data to the server, so you php file can get this parameter!
In your called php file you need something like this:
if( isset($_POST['functionname']) )
{
if($_POST['functionname']) == 'getImgs'
{
getImgs();
}
}
Of course you need to make sure that you post the data with post in this case, if you want to use get you need to change the php to $_GET
Notice: This is totally unsafe right now! No escaping from the coming data and anything else.
i cant find an answer to this
i have been learning ajax lately but i learned how to do it all in javascript
now i go swiming around ajax question here and almost all are using jquery
so i end up confused. should i use normal javascript or do it through jquery?
so what are the differences?
this is my normal approach
var xmlHttp = createXmlHttpRequestObject(); //you first create the object to this function global
function createXmlHttpRequestObject() //here you instruct the function
{
var xmlHttp; //here you tell it to use the local variable not the global version of it because this returns to the global with the propper values
if (window.XMLHttpRequest) //if the "window" or browser is aware of this Object 90% of browsers
{
xmlHttp = new XMLHttpRequest(); // if true then the variable is now equal to the heart of ajax
}
else //for internet explorer
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlHttp; //we return it back to daddy the global variable this objects does everything
//this object is everything in ajax for the most part
}
function process() //function that gets called on load of the body
{
if(xmlHttp) //if its not void or if you can run ajax
{
try //try catch statement are sort of required for the heart of things like ajax and server communication
{
xmlHttp.open("GET", "bacon.txt", true); //here 1st type of call 2nd from where 3rd
//is it true assyscronly or at the same time
//it does not start the connection to the server, its only sets up settings for the connection
xmlHttp.onreadystatechange = handleServerResponse; //anytime something changes[propertie]
//i want to call that function handleserverresponse
//begin communication
xmlHttp.send(null); //this is what communicates to the server makesure on ready statechane before this
//if the server responds you want to make sure everything is taking care of like what function onready state change is it going to call
//or what to do like open a text file in this case
} catch(e)
{
alert( e.toString() ); //alert the error message as a string on a popup
}
}
}
//handling the server response
function handleServerResponse()
{
theD = document.getElementById('theD'); //get the div in a var
if(xmlHttp.readyState==1) //if the connection to the server is established
{ //google crhome may not show this one, some browsers ignore some states
theD.innerHTML += "Status 1: server connection established<br>";
}
else if(xmlHttp.readyState==2) //request received, hey client i am the server and i received your request
{
theD.innerHTML += "Status 2: request reveived <br>";
}
else if(xmlHttp.readyState==3) //while is doing its thing
{
theD.innerHTML += "Status 3: processing request <br>";
}
else if(xmlHttp.readyState==4) //your request is finished and ready
{ //it means your response is ready but doesnt guaranteed no trouble
if(xmlHttp.status==200) //if the status is 200 then is succesufll
{
//IF everthing finally good THE GOOD PART
try //put all your calls on a try statement REMEMBER
{
//get the txt file as a string
text = xmlHttp.responseText; //response text n a normal string
theD.innerHTML += "Status 4: request is finished and response is finished";
theD.innerHTML += text;
}catch (e)
{
alert( e.toString() );
}
} else //for the other statuses like 404 else somehting went wrong
{
alert( xmlHttp.statusText ); //this will give you a status report on the wrong
}
}
}
jQuery simply wraps all of the XmlHttpRequest calls into a simple to use library. In the guts of jQuery you will see code that creates the XmlHttpRequest objects.
You can see the code that does this here:
https://github.com/jquery/jquery/blob/master/src/ajax/xhr.js
The nice thing about using a framework like jQuery is that they handle a lot of the browser idiosyncrasies for you. They also handle a lot of the edge cases you might not think about when writing your code.
Using jQuery is just for ease of use. If you prefer doing it the javascript way then carry on doing that.
jQuery ajax calls do exactly the same as what you are doing but jQuery is a javascript framework which simplifies what you write.
jQuery is a javascript framework which contains library of simplified functions compared to the Native Javascript. One of the functions is the XMLHttpRequest.
This way we just need to implement functions that is needed to implement without needed to write the traditional codes to setup the AJAX system to work
You may learn more about jQuery ajax here:
http://api.jquery.com/jQuery.ajax/
I currently have a web page that uses javascript, however; when I use my Ajax to move towards the DB my responseText is always empty.
js to make the flag and send query
objAjaxUpdates.main_flag = "getNames";
objAjaxUpdates.SendQuery(query);
next in the flow
(The url is an aspx file)
this.SendQuery = function(data) {
this.Initialize();
if (this.req != null) {
//alert(data);
//alert(this.url + " " + this.main_flag);
this.req.open("POST", this.url);
this.req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
this.req.onreadystatechange = this.processData;
this.req.send(data);
}
}
Next
this.processData = function() {
if (objAjaxUpdates.req.readyState == 4) {
if (objAjaxUpdates.req.status == 200) {
if (objAjaxUpdates.req.responseText == "") {
alert('No Return');
}
else {
...
Any help would be appreciated.
I don't know the library you are using. But the procedure looks correct to me. (There are libraries like jQuery which avoids you to work on the low-level AJAX API, checking response code and so on.)
I advise you to work with something like Firebug for Mozilla, or the Chrome Developer Tools to "debug" your AJAX machinery.
There still is that good old technique:
First test the requests to the server manually.
Then, do a dumb AJAX request.
At the end, test both components.
I have an application that uses a mobile ad provider; the way ad provider works is that I make a request on the server side, the provider returns me the mark-up and I include that on my site.
In order to make the load page faster (which is a requirement that I don't control), I have an AJAX call to my server which then makes the call to the server side, returns the markup and I include the markup on my mobile view.
Most of the time, the markup I receive is a <img> or something similar.
However, when I receive a ad markup with <script> that make another call dynamically to receive the ad, the markup I receive from the dynamically loaded <script> ends up replacing the entire view; leaving with me just the ad.
I have tried a few things around it but haven't been successful so far. Is there anything I can do make sure the dynamically received markup doesn't end up replacing the entire page contents?
The problem is probably because the ad uses document.write as it's output.
document.write is recklessly dependent
on timing. If document.write is called
before the onload event, it appends or
inserts text into the page. If it is
called after onload, it completely
replaces the page, destroying what
came before. - crockford.com
What you can do is to temporarily overwrite the document.write method. It is as simple as that:
// overwrite document.write with a custom function
var old = document.write;
document.write = function ( html ) {
document.getElementById("target").innerHTML += html;
};
// ad code goes here, calling
// our document.write sandbox
document.write("<div> advertisement </div>");
// restore standard document.write
document.write = old;
You can see a little demo here.
Easy solution - put ad in DIV or IFRAME (ugly way).
Real solution - change ad system or make a deal with them to extend API. Nasty things you do will cost you alot to support in long term, no matter how easy was it to integrate this way.
If mobile AD system doing things like that - they must have little idea about development for mobile devices with limited recources.
ajax('POST','http://mobileAdProvider/',requestPayload,function(){insertHtmlAndScript("someDivID");});
OR
ajax('GET','http://mobileAdProvider/queryString','',function(){insertHtmlAndScript("someDivID");});
//=============================================================================
function injectJavascript(src)
{
var scripts = document.getElementById("scripts");
var javascriptSrc = document.createElement("script");
javascriptSrc.setAttribute("type", "text/javascript");
javascriptSrc.setAttribute("language", "JavaScript1.2");
javascriptSrc.innerHTML = src;
scripts.appendChild(javascriptSrc);
}
//=============================================================================
function insertHtmlAndScript(target)
{
if (req.readyState == 4) // 4 == "loaded"
{
if (req.status == 200) // 200 == "Ok"
{
var resp = req.responseText.split("^"); // delimiter for html and script
div = document.getElementById(target);
div.innerHTML = resp[0];
injectJavascript(resp[1]);
}
else
{
alert("Could not retreive URL:\n" + req.status + "\n" + req.statusText);
}
}
}
//=============================================================================
function ajax(method,url,payload,action)
{
if (window.XMLHttpRequest)
{
req = new XMLHttpRequest();
req.onreadystatechange = action;
req.open(method, url, true);
req.send(payload);
}
else if (window.ActiveXObject)
{
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req)
{
req.onreadystatechange = action;
req.open(method, url, true);
req.send(payload);
}
else
{
alert("Could not create ActiveXObject(Microsoft.XMLHTTP)");
}
}
}
//=============================================================================