ajax - See if 2 URLs exist - javascript

what I have at the minute works for the first URL test, however, I don't know how to get it to test the second URL, should the first one not exist.
var str = document.title.replace(/ | My Site/i, '');
var title = str.replace(/ /g, '-');
var finish = title.toLowerCase();
var banner = finish.split('-', 1)[0]
var address = "http://example.com/images/" + finish + ".jpg";
var banneraddress = "http://example.com/images/" + banner + "-banner.jpg";
$.ajax({
type: 'HEAD',
url: address,
success: function() {
// Primary URL exists
document.getElementById("TRY").src = address;
},
error: function() {
$.ajax({
type: 'HEAD',
url: banneraddress,
success: function() {
// Secondary URL exists
document.getElementById("TRY").src = banneraddress;
},
error: function() {
// Both failed
null
}
});
}
});
What needs to happen is if the user loads a page and /images/page-title.jpg exists, it will add that src to the the images with the ID "TRY".
If that test fails, if /images/page-banner.jpg exists add that src to the images
And, for now, if neither work do nothing.

Just move your AJAX logic to separate function, later you can ask the function if both images exists, and if they, you can change the src attribute of your image.
E.g.
if( checkIfImageExists(address) && checkIfImageExists(banner_address) ) {
// both images exists, change src attribute
} else {
// both images do not exists, do something else
}
You should modify your success and error callbacks to return true or false.

Related

Reloading Ajax function with setTimeout doesnt clear previous timeout first

I am trying to load a chat box when a contact name is clicked. On initial load it displays the inbox. All functionality works ok until I try and click the contact name a second time. It loads the new contacts chat but also displays the original contact chat even though I set clearTimeout().
Here is the JS file -
$(document).ready(function(){
var contactTimeout;
var inboxTimeout;
function contact() {
var fromName = $('#from').val();
var toName = $("#to").val();
$(".chat-title").replaceWith("<div class='chat-title'>" + toName + "</div>");
$(".chat-form").fadeIn(100);
$.ajax('chat/get-chat.php', {
data: ({ to: toName,from: fromName}),
type: "POST",
success: function(data) {
$(".chat-body").replaceWith("<div class='chat-body'>" + data + "</div>");
contactTimeout = setTimeout(contact, 2000);
}
});
}
function inbox() {
var user = $('#from').val();
$.ajax('chat/get-chat-inbox.php', {
data: ({ user: user}),
type: "POST",
success: function(data) {
$(".chat-body").replaceWith("<div class='chat-body'>" + data + "</div>");
inboxTimeout = setTimeout(inbox, 2000);
}
});
}
// Load inbox when chat box is opened
$(".chat-arrow").click(function(){
clearTimeout(contactTimeout);
inbox();
});
// Load chat from contact name
$(".contact-name").click(function() {
clearTimeout(contactTimeout); // Here I try and kill previous timeout
clearTimeout(inboxTimeout);
var contactName = $(this).attr('id');
$("#to").val(contactName);
contact();
});
});
Why would it just add more timeout functions rather than replace them when a new contact name is clicked?
First i would suggest you instead of using replace each time, you could easily use .html(data) to put new data in existing content of chat-body.
And explanation is you call your function on ajax success (there's wait time to server respond to your request) and if you click in meanwhile on your another call, you will have two calls instead of one, because you can't clear timer that's not started yet.
Well one of the solutions would be, let timer works only through it's default state, and when you need some fast data, you can call your contact without calling the next timer.
$(document).ready(function(){
var contactTimeout;
var inboxTimeout;
/* add parameter which will mean will we call timer or not */
function contact(dotimer) {
var fromName = $('#from').val();
var toName = $("#to").val();
$(".chat-title").replaceWith("<div class='chat-title'>" + toName + "</div>");
$(".chat-form").fadeIn(100);
$.ajax('chat/get-chat.php', {
data: ({ to: toName,from: fromName}),
type: "POST",
success: function(data) {
$(".chat-body").replaceWith("<div class='chat-body'>" + data + "</div>");
/* default calling of timer with repeating */
if (dotimer) { contactTimeout = setTimeout(function(){ contact(true); }, 2000); }
}
});
}
function inbox() {
var user = $('#from').val();
$.ajax('chat/get-chat-inbox.php', {
data: ({ user: user}),
type: "POST",
success: function(data) {
$(".chat-body").replaceWith("<div class='chat-body'>" + data + "</div>");
inboxTimeout = setTimeout(inbox, 2000);
}
});
}
// Load inbox when chat box is opened
$(".chat-arrow").click(function(){
clearTimeout(contactTimeout);
inbox();
});
// Load chat from contact name
$(".contact-name").click(function() {
clearTimeout(inboxTimeout);
var contactName = $(this).attr('id');
$("#to").val(contactName);
/* call function without TIMER, default one will work as it works */
contact(false);
});
});

Ajax sends two files at one time through one onclick event in JavaScript

jQuery AJAX seems to be sending two requests at once when I use the onclick event with JavaScript in a tag. I click once, and that seems ok, but when I change the id value to an invalid id value, it sends two requests to the PHP file. I think the problem may be caused by the browser caching JavaScript code.
Here's is the JavaScript code I'm using to generate the query:
function unlike_image(id, image_id, obj) {
var url_unlike_image = base_url + 'profile/unlike_image';
$.ajax({
type: "POST",
data:
{
user_id: id,
image_id: image_id
},
url: url_unlike_image,
success: function(data) {
if (data.status=='error_exists') {
alert('This image not exists');
}
if (data.status=='success') {
//like = like - 1 for view
var str = $(obj).next().text();
var n = str.length;
str_like = str.substring(1, n-1);
var number_likes = parseInt(str_like) - 1;
$(obj).next().text('('+number_likes+')');
//change event click unlike
$(obj).text('Like');
$(obj).attr('onclick', 'like_image('+id+' ,'+image_id+ ',this); return false');
}
}
});
}
After changing the true id to the wrong id, I check the website traffic, I see two instances where unlike_image is called. The first is with the true id, and the second is with the wrong id.

using jQuery to get url and extract url segments

On a webpage that has a list of categories, and each category title is linked in this format: http://localhost/admin/category/unpublish/2
I wrote the following js code, trying to capture the url and the segments 'unpublish' (action) and '2' (id), and need to send the request to http://localhost/admin/category
$('#statusChanges a').click(function(evt) { // use the click event of hyperlinks
evt.preventDefault();
var url = $(location).attr('href');
// var action = url.segment(3); /*JS console complains that url.segment() method undefined! */
// var id = url.segment(4);
$.ajax({
type: "GET",
url: $(location).attr('href'),
dat: '',
/* do I need to fill the data with json data: {"action": "unpublish, "id": 2 } ? but I don't know how to get the segments */
success: function(data) {
$('.statusSuccess').text('success!');
},
error: function(data) {
$('.statusSuccess').text('error!');
}
});
}); // end of status change
Try this
var url = $(location).attr('href').split("/").splice(0, 5).join("/");
Update Answer:
User this object to get current anchor link see below
$(this).attr('href')
Split the URL into segments first:
var segments = url.split( '/' );
var action = segments[3];
var id = segments[4];
I think you can use split. Then you can have an array to work with from which you can get the action and id.

Combine two functions? Javascript and AJAX api call with throbber

I have a function getShare which creates a script and then calls an url shortener api which then returns a shortened url and sets that link to an input box's value.
Secondly I also have this function which I'm trying get to work with the first. So far I've only been able to .show the loader gif but not hide it when the function is successful.
EDIT: Below is updated code with my original script inside the response.success but i'm get a message in the console saying Failed to load resource and a 404 - the missing url is shown to be http://b1t.co/Site/api/External/MakeUrlWithGet?callback=apiCallback&_=1391704846002
function getShare(url)
{
$('#loader').show(); // show loading...
$.ajax({
dataType: "jsonp",
jsonpCallback:'apiCallback', // this will be send to api as ?callback=apiCallback because this api do not want to work with default $ callback function name
url: 'http://b1t.co/Site/api/External/MakeUrlWithGet',
data: {'url':url},
success: function(response){
$('#loader').hide(); // hide loading...
//respponse = {success: true, url: "http://sdfsdfs", shortUrl: "http://b1t.co/qz"}
if(response.success){
{
var s = document.createElement('script');
var browserUrl = document.location.href;
//alert(browserUrl);
if (browserUrl.indexOf("?") != -1){
browserUrl = browserUrl.split("?");
browserUrl = browserUrl[0];
}
//alert(browserUrl);
var gifUrl = $('#gif_input').value;
var vidUrl = $('#gif_input').value;
//alert(gifUrl + "|" + vidUrl);
url = encodeURIComponent(browserUrl + "?gifVid=" + gifUrl + "|" + vidUrl);
//alert(encodeURIComponent("&"));
s.id = 'dynScript';
s.type='text/javascript';
s.src = "http://b1t.co/Site/api/External/MakeUrlWithGet?callback=resultsCallBack&url=" + url;
document.getElementsByTagName('head')[0].appendChild(s);
}
function resultsCallBack(data)
{
var obj = jQuery.parseJSON(JSON.stringify(data));
$("#input-url").val(obj.shortUrl);
}
}
},
error:function(){
$('#loader').hide();
}
});
}
There's no need to "combine" it.
What someone is suggesting is a regular ajax method. Just move your js scripts you want executed on success, inside the success: callback.
Read more about the ajax method at another answer I did here: https://stackoverflow.com/questions/21285630/writing-my-first-rest-api-call-to-a-webservice-endpoint-post/21286810#21286810 or jQuery's docs: http://api.jquery.com/jQuery.ajax/
Note: to use this you will need jQuery and probably an XDR plugin for the ajax to support < IE 10

Ajax success function issue

My javascript looks like that.
There are some problems that I can't figure out, where I did mistake
#status_message doesn't show generated message
$("#status").className = 'fail'; doesn't override current class
var message=$("#status_message"), form=$("#bcscan"), ids=$('#itemids'),proctype, destination, counter=0, tenWordCounter = 0, autoPostInterval=null, errorcount=0, successcount=0;
function ajaxPost() {
formData = form.serialize()+'&process=Scan';
formUrl = form.attr('action');
formMethod = form.attr('method');
$.ajax({
url: formUrl,
type: formMethod,
dataType: "json",
data: formData,
success: function (data) {
var now = new Date();
if(data.err_detected==="yes")
{
if(data.errors.indexOf(",") != -1)
errorcount=errorcount+data.errors.split(",").length;
else errorcount=errorcount+1;
$("#status").className = 'fail';
message =errorcount+" errors found";
$('#errors').prepend(data.errors).slideDown("slow");
}
$('#success').prepend(data.success).slideDown("slow");
if(data.success.indexOf(",") != -1)
successcount=successcount+data.errors.split(",").length;
else successcount=successcount+1;
message +="Last submitted:"+now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds();
$("#status_message").text(message);
}
});
}
Here is page in action
If you want to test, please choose some option from selects like, output from db, ebay.fr and press "scan". Enter 10 digits seperated by comma try 41,42 (they exist in db tables) too between them. After 10th digit it will post textarea via ajax.
For the message, you've declared a jQuery object pointing at the element:
var message = $('#status_message'), ...
but then you're overwriting it with a string:
message = errorcount + ' errors found';
You should be calling:
message.text('some string...')
to change its contents.
For the class change, the correct syntax is:
$("#status").addClass('fail');
How about
$('#status').attr('class','fail');
This will override the current class.
did you try this?? $("#status").addClass( 'fail');

Categories