How to tie bind and load methods? - javascript

Loaded content on the page to another page. If the information is read incorrectly, then you should use the bind () method to display a message about it. How to do it?
$("#result").load("university.html");

If you just want to know if the request succeeded, you can use a callback function.
$("#result").load("university.html", function( response, status, xhr ) {
if ( status == "error" ) {
var msg = "Sorry but there was an error: ";
$( "#error" ).html( msg + xhr.status + " " + xhr.statusText );
}
});

Related

AJAX returns status code 0? CORS allowed. Is this AJAX implemented incorrectly?

I have a browser action I've implemented it as an AddOn.
I'm testing my construction of the AddOn within my domain
between two machines as server and a client.
I'm stuck at AJAX failing with status code 0.
I set up Apache to enable CORS to make sure that the code is behaving as expected.
I added this line to the apache config and enabled headers:
Header set Access-Control-Allow-Origin "*"
The javascript code: UPDATED
function sendData(data){
var requestdata = 'data1=one&data2=two&data3=three';
var xhr = new XMLHttpRequest();
xhr.open("POST","http://server/test/test.php");
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.onloadstart = function(){
console.log("Onload status: " + xhr.status);
}
xhr.onerror = function(ev) {
console.log("OnError Status: " + xhr.status + ", Loaded: " + ev.loaded + ", Total: " + ev.total);
}
xhr.onreadystatechange = function() {
console.log(xhr.status);
if (xhr.status !== 200){
console.log("Failure :( + Status: " + xhr.status);
//console.log(requestdata);
console.log("Ready State: " + xhr.readyState + ", Status: " + xhr.status +", Response Text: " + xhr.responseText);
} else {
alert("Success!");
}
}
xhr.send(requestdata);
}
test.php
<?php
require '../lib/Database.php';
error_reporting(E_ALL);
$db = new Database('test');
var_dump($db);
json_encode($_POST);
?>
Have I done this AJAX implementation correctly?
If I have, and I have made adjustments for CORS, why is it failing with status code 0?
UPDATE
This is an AddOn I am testing in Firefox.
From the "matches" parameter in manifest.json, navigating to the page in question retrieves data from the page using Vanilla JS on the DOM.
The collected data is held in an object.
The data object is delivered
This is a picture of what's returned in the browser:
UPDATE2
I replaced the POST url with http://httpbin.org/post to see if the data is going anywhere. Nope.

sapui5 - javascript error handling - without try-catch in every callback

I am developing a SAPUI5-App. Is there a way to show all errors directly to the customer without having to put a try-catch-block into every callback of sapui5? He will use my app in a mobile device and wouldn´t be able to see the log.
I tried already the following code:
<script type="text/javascript">
window.onerror = function(msg, url, line, col, error) {
var extra = !col ? '' : '\ncolumn: ' + col;
extra += !error ? '' : '\nerror: ' + error;
alert("Error: " + msg + "\nurl: " + url + "\nline: " + line + extra);
return false; //true = suppress error alert
};
window.addEventListener("error", handleError, true);
function handleError(evt) {
if (evt.message) {
alert("error: "+evt.message +" at linenumber: "+evt.lineno+" of file: "+evt.filename);
} else {
alert("error: "+evt.type+" from element: "+(evt.srcElement || evt.target));
}
}
jQuery.sap.log.addLogListener({
onLogEntry : function(oLogEntry) {
if(oLogEntry.level == '1'){
alert(oLogEntry.details + ' - '+oLogEntry.message);
}
}});
</script>
But I like to actually copy the error-message from the log into an alert for the customer, so he can send me screenshots of the error in his device.
All my attempts did not show enough information or didn´t fire on every error in the console-log.

Get user IP from remote script

I have a page which loads a script from a remote location (say myscript.com.
This scripts makes an Ajax request to a distant API.
How can this API get the visitor's IP address?
If I use request.remote_addr in the request handler, I get the IP from the script's location (myscript.com).
use this api to get all this data as a json who visited your page
{"as":"AS9583SifyLimited","city":"Bengaluru","country":"India","countryCode":"IN","isp":"Sify Limited","lat":12.9833,"lon":77.5833,"org":"Sify Limited","query":"202.191.210.194","region":"KA","regionName":"Karnataka","status":"success","timezone":"Asia/Kolkata","zip":"560099"}
API_Location=' http://ip-api.com/json';
$.getJSON( API_Location)
.done(function( position ) {
if (position.lat && position.lon) {
updateWeather(position);
} else {
updateWeather({"lat":DEFAULT_LAT, "lon":DEFAULT_LON});
}
})
.fail(function( jqxhr, textStatus, error ) {
var err = textStatus + ", " + error;
console.log( "Request Failed: " + err );
});
visit this page ip and you can get how to get ip!

Javascript load file fails without error

When I run this:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
$("#btn").click(function(){
try {
$("#div1").load("demoddd.txt"); //there is no demoddd.txt
}
catch (err)
{
alert("Error: " + err); //this never runs
}
finally {
alert("Finally");
}
});
});
</script></head>
<body>
<button id="btn">Load file</button>
<div id="div1"></div>
</body>
</html>
I get "Finally" but no error. In the debug console, I see the 404. Can I trap 404 errors when using the load() function?
Use the complete function as shown in the documentation:
$( "#success" ).load( "/not-here.php", function( response, status, xhr ) {
if ( status == "error" ) {
var msg = "Sorry but there was an error: ";
$( "#error" ).html( msg + xhr.status + " " + xhr.statusText );
}
});
You need to get the httprequest status, you can't catch an 404 with that catch.
Use this:
$("#div1").load("/demoddd.txt", function(responseText, statusText, xhr){
if(statusText == "success")
alert("Successfully loaded!");
if(statusText == "error")
alert("An error occurred: " + xhr.status + " - " + xhr.statusText);
});
The first thing I would try is to set the full URL, and not a relative one. See if that works first.

JQUERY LOAD unable to load same html again

I have created an html page which renders differently depending on the parameter 'resourceType'.
ResourceType can be IO/CPU/STORAGE etc . I have adopted this design for reusability as we have same layout for all the charts except that the inputs to chart differs based on resourceType.
<script>
require(['../js/viewmodel/db-resource-analyze']);
</script>
<div class="oj-row" id="pageContent">
<div class="topchartRegionDiv">
.....
</div>
</div>
Now I am loading this page from my HOME page which have vertical tabs (like a left side menu)
On click of a tab ,I load my page dynamically using jquery load
window.paramObj =
{
resType: "cpu"
};
$('#cpuContent').load("db-analytics-resources-home.html", function(responseTxt, statusTxt, xhr) {
if (statusTxt == "success")
alert("External content loaded successfully!");
if (statusTxt == "error")
alert("Error: " + xhr.status + ": " + xhr.statusText);
});
The next time user click on IO tab ...i do same operation but with different parameter
window.paramObj =
{
resType: "io"
};
$('#ioContent').load("db-analytics-resources-home.html", function(responseTxt, statusTxt, xhr) {
if (statusTxt == "success")
alert("External content loaded successfully!");
if (statusTxt == "error")
alert("Error: " + xhr.status + ": " + xhr.statusText);
});
The first load happens without any issues , but subsequent load do not happen and page comes as blank.
I am suspecting the page is cached and not loaded. How to enforce reload skipping cache using JQUERY load. Any pointers ?
Try this Stop jQuery .load response from being cached
$.ajaxSetup ({
// Disable caching of AJAX responses
cache: false
});
As the guy mentions if the convenience functions like .load, .loadJSON, etc don't do what you need, use the .ajax function and you can find a lot of configuration options in there that will likely do what you need
you can try this methode. this will prevent all caching
$('#ioContent').load("db-analytics-resources-home.html?"+Math.random(), function(){})
Many Thanks for all response . I could get this resolved by passing JS script as parameter to JQUERY load callback and invoking it there on successfully load of html doc .
smthing like this :
$('#' + resType + 'Content').load(url, function(responseTxt, statusTxt, xhr) {
if (statusTxt == "success")
{
alert("External content loaded successfully!...calling JS");
new self.dbResourceAnalyze();
}
if (statusTxt == "error")
alert("Error: " + xhr.status + ": " + xhr.statusText);
});

Categories