I am currently loading the same page 3 times with 3 different .load() calls. I am wanting to know if there is something I can do to optimize the code.
When I click a link currently it loads the page 3 times
$("#"+target).load(url + " #page", function(response, status, xhr){
if(status === "error")
{
$("#"+target).load('error.php?error=503 #page', function(response, status, xhr){
if(status === "error")
{
alert("Something has gone very wrong right now, please contact an admin quoting 'error.php'");
return;
}
}); // This should never fail but if it does kill the page
console.log('Content failed to load ' + xhr.status + ' ' + xhr.statusText);
//Force update the title to error
document.title = "Error";
$("#pageBreadcrumbs").load('error.php #breadcrumbs');
}
else
{
console.log('Content was loaded');
//Load the title dynamically
document.title = "Venus | " + name;
$("#pageBreadcrumbs").load(url + ' #breadcrumbs');
if(sidebar === true)
$("#pageSidebar").load(url + ' #sidebar');
}
Is there anyway I can shorten this to just 1 call to the url or error page and extract it from there?
You can use this code:
$.get(url, function(response) {
var $nodes = $(response);
... some conditions ...
var $container1 = $("#"+target).html('');
$nodes.find('#page').appendTo($container1);
... some conditions ...
var $container2 = $("#pageBreadcrumbs").html('');
$nodes.find('#breadcrumbs').appendTo($container2);
});
I'm not really sure that it works, but you can try it...
UPDATE
This code assumes that whole server response is wrapped in one container (div)
Related
I am trying to make a program that decodes base64 images, sends the request to an AZCaptcha server, and puts the answer to the label that I want.
When I go to this website I see that the captcha is base64 encoded, and the ID is changeable every time when I press the button Load another picture. In this site there are no unique IDs.
The code should have four functions: one that gets the exact ID (ID is not unique, when you refresh the website, it changes the ID of captcha), another that sends this ID (ID of captcha when I will open the website), to the server, and a third that puts the answer from AZCaptcha server to the next label.
Here are two functions that are used to send and parse the request to the server:
function sendToAPI(base64) {
base64 = encodeURIComponent(base64);
GM_xmlhttpRequest({
method: "POST",
url: "http://azcaptcha.com/in.php",
data: "method=base64&key=" + apikey + "&body=" + base64,
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
onload: function(response) {
var responseString = response.responseText;
GM_log("Debug(Send): " + responseString);
if (responseString == "ERROR_WRONG_USER_KEY" || responseString == "ERROR_KEY_DOES_NOT_EXIST" || responseString == "ERROR_ZERO_BALANCE" || responseString == "ERROR_ZERO_CAPTCHA_FILESIZE" || responseString == "ERROR_TOO_BIG_CAPTCHA_FILESIZE" || responseString == "ERROR_WRONG_FILE_EXTENSION" || responseString == "ERROR_IMAGE_TYPE_NOT_SUPPORTED") {
userLog("There has been a pretty severe error:" + responseString + ", you should disable the plugin and report this.", "error");
throw new Error("Stopping execution");
} else if (responseString == "ERROR_IP_NOT_ALLOWED" || responseString == "IP_BANNED") {
userLog("For some reason your IP has been banned from the service. You should disable the plugin and report this.", "error");
throw new Error("Stopping execution");
} else if (responseString == "ERROR_NO_SLOT_AVAILABLE") {
userLog("The server is at maximum capacity, we are resubmitting in 15s.", "warning");
} else {
userLog("Captcha sent, awaiting response", "success"); //Should really if this to deal with other responses sooner
setTimeout(parseResponse, 15000, responseString);
}
}
});
}
//Parse the response from the server
function parseResponse(prevResponse) {
var captchaID = prevResponse.split("|");
GM_xmlhttpRequest({
method: "GET",
url: "http://azcaptcha.com/res.php?key=" + apikey + "&action=get&id=" + captchaID[1],
onload: function(response) {
var getResponse = response.responseText;
if (getResponse == "CAPCHA_NOT_READY" || getResponse == "CAPTCHA_NOT_READY") {
userLog("Captcha is not ready yet. Let's wait 10 seconds", "warning");
captchaID = null;
setTimeout(parseResponse, 10000, prevResponse);
//Deal with errors
} else if (getResponse == "ERROR_KEY_DOES_NOT_EXIST" || getResponse == "ERROR_WRONG_ID_FORMAT") {
userLog("Fatal error! We have to quit out of the script. The error was: " + getResponse, "error");
throw new Error("Stopping execution");
} else if (getResponse == "ERROR_WRONG_CAPTCHA_ID") {
userLog("Our ID is wrong, so the server is probably having issues. Wait 15s and attempting resubmit.", "warning");
setTimeout(checkBotcheck, 15000);
} else if (getResponse == "ERROR_CAPTCHA_UNSOLVABLE") {
userLog("Server thought the captcha was unsolvable, so we're going to resend it.", "warning");
setTimeout(checkBotcheck, 5000);
} else {
GM_log("Debug(Response): " + getResponse);
//Assuming we're all good
var captchaArray = getResponse.split("|");
var captchaAnswer = captchaArray[1];
submitToCaptcha(captchaAnswer);
count++;
setTimeout(userLog, 3000, "We think the botcheck is: " + captchaAnswer + ". We are going to wait 15 seconds to see if it was. We have attempted to solve " + count + " botchecks (including retries).", "success");
}
}
});
I want to make an code, that sends to the server, the exact ID of the image, gets the response from the server, and puts the answer to next label.
Can you help me somehow to solve this problem?
For more clarity I made it simple (so let's presume that iframe.attr() will be called after previous load was fully completed):
var iframe = $("iframe");
var counter = 0;
var trackLoads = function(){
console.log("I was loaded:" + counter);
counter += 1;
};
iframe.load(trackLoads);
iframe.attr("src","http://stackoverflow.com/");
iframe.attr("src","http://localhost:9081/mobile/api/content/badPath"); //returns 204 No Content
iframe.attr("src","http://stackoverflow.com/");
Console log looks like this:
I was loaded:1
I was loaded:2
When the iframe loaded new content from stackoverflow.com, It trigger the callback "trackLoads", but iframe will never trigger callback for 204 No Content from some reason.
How to detect "204 No Content" after iframe has changed "src" attribute?
Change your previous code to this:
var trackLoads = function(response, status, xhr){
console.log("I was loaded:" + counter);
counter += 1;
if ( status == "error" && xhr.status == 204) {
console.log( "Sorry but there was an error: " + xhr.status + " " + xhr.statusText );
}
};
From: http://api.jquery.com/load/
When trying to use intercom.js I can print what my message is to the log in line 21 of the index file
intercom.on('notice', function (data) {
console.log(data);
$messages.append($('<p>').text(data.message));
document.title = '(' + $messages[0].childNodes.length + ') ' + title;
});
Is there any way when clicking it simply to trigger an alert on the other page.
In the read me file it gives you a basic code
// run this in multiple tabs!
var intercom = Intercom.getInstance();
intercom.on('notice', function(data) {
console.log(data.message);
});
intercom.emit('notice', {message: 'Hello, all windows!'});
Put the emit code on the page with the button, put the on code on the page where you want the alert to appear [of course change the console line to an alert.]
So making the alert happen would be:
Page 1 [Page with the alert]:
var intercom = Intercom.getInstance();
intercom.on('notice', function(data) {
alert(data.message);
});
Page 2 [Page with the button]:
function broadcast () {
var intercom = Intercom.getInstance();
intercom.emit('notice', {message: 'Hello, all windows!'});
}
document.getElementById("myButtonId").addEventListener("click", broadcast , false);
When I go to the Games section of my website, the buttons work perfectly: http://sharepanel.net/games/
When I go to the page with a Secure SSL connection, the buttons don't do anything: https://sharepanel.net/games/
Am I missing something?
This is the Javascript code for the buttons:
<script>
function getPage(el,page){
$(el).load(page, function(response, status, xhr) {
if (status == "error") {
var msg = "Error While Loading Page: ";
$(el).html(msg + xhr.status + " - " + xhr.statusText);
}
});
}
$(function(){
$("#top10").on("click",function(){
getPage("#main","/games/top10.php");
});
$("#action").on("click",function(){
getPage("#main","action.php");
});
$("#adventure").on("click",function(){
getPage("#main","adventure.php");
});
$("#timemanage").on("click",function(){
getPage("#main","timemanage.php");
});
$("#fungames").on("click",function(){
getPage("#main","fungames.php");
});
$("#newgames").on("click",function(){
getPage("#main","newgames.php");
});
$("#randomgames").on("click",function(){
getPage("#main","randomgames.php");
});
});
</script>
Thanks for all the help guys,
I just fixed this by saving all the jQuery files to my website and replacing the urls to the jQuery code to the urls on my webserver.
Thanks
Hrach
I've got a JavaScript function that I want to report an alert message to the users if it successfully updates the database, or if it has an error.
In the main X.JSP file I have:
function startRequest(pChange)
{
//alert("startRequest");
createXmlHttpRequest();
//alert("sending message");
//var u1=document.f1.user.value;
//alert("Running startRequest for: " + pChange.id);
//xmlHttp.open("GET","updateEntry.jsp&pID=pChange.id&pStatus=pChange.status&pAddress=pChange.address&pDate=pChange.date&pNotes=pChange.note&pAssigned=pChange.assigned" ,true)
xmlHttp.open("GET","updateEntry.jsp?pID=" + pChange.id + "&pAddress=" +pChange.address + "&pStatus=" + pChange.status +"&pNote=" + pChange.notes +"&pAssigned=" +pChange.assigned ,true)
//alert(xmlHttp.responseText);
xmlHttp.onreadystatechange=handleStateChange;
xmlHttp.send(null);
}
function handleStateChange()
{
//alert("handleStateChange");
var message = xmlHttp.responseText;
alert("Return Code:" + message);
if(xmlHttp.readyState==4)
{
if(xmlHttp.status==200)
{
//alert("test2");
//alert("recieved Message");
var message = xmlHttp.responseText;
alert(message);
}
}
else
{
alert("Error loading page"+ xmlHttp.status +
":"+xmlHttp.statusText);
}
}
I then run a method in updateEntry.jsp that does a number of things, but of interest is this section:
if(nId.equals("NMI")||nId.equals("MI")||nId.equals("NI")||nId.equals("SA")||nId.equals("S"))
{
org.hibernate.Query query2 = session2.createQuery("update Leads set Status = :nstatus where Id = :nid");
query2.setParameter("nid", nId);
query2.setParameter("nstatus", nstatus);
query2.executeUpdate();
out.println("Update successfully with: " + nstatus);
// Actual contact insertion will happen at this step
session2.flush();
session2.close();
}
else
{
out.println("Status must be: NMI, MI, NI, SA or S");
}
My understanding is that this should only create a single alert, if the function completes successfully. Instead it creates like 9 alerts all of which are blank. What am I doing wrong? I'm seeing both the "Return Code: " message and a blank " " message, (two different sections of code) but both output blank message variables.
If the readystate is not 4, it does not mean it is an error. Ajax has multiple states that inform the clientside about what is happening. Your code says that those connection states are all errors.
if(xmlHttp.readyState==4)
{
if(xmlHttp.status==200)
{
//alert("test2");
//alert("recieved Message");
var message = xmlHttp.responseText;
alert(message);
} <-- your else should most likely be up here
}
else <-- this is incorrect
{
alert("Error loading page"+ xmlHttp.status +
":"+xmlHttp.statusText);
}
Read the document at MDN - Ajax Getting Started