Combine two functions? Javascript and AJAX api call with throbber - javascript

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

Related

How to bind button function to a corresponding item in an array - AJAX, Firebase

I'm attempting to first make an AJAX request from a social API and append the results with a button inside the div that will save the corresponding item in the array to my firebase database. For example,
I have my AJAX request - I cut out about 75% of the actual code that isn't needed for the question.
$.ajax({
type : 'GET',
url : url,
dataType : "jsonp",
cache: false,
success : function(data){
console.debug(data);
vids = data.response.items;
for(var i in vids) {
dataTitle = vids[i].title;
ncode = "<div class='tile'><img src='"+ vids[i].title "'/></a><button class='btn' type='button' onClick='saveToDatabase()'>Save</button></div>";
$('#content').append( ncode )
And then I have my function that I want to save the 'title' of the object the button was appended with to the firebase database.
var dataTitle;
function saveToDatabase() {
ref.push({
title: dataTitle
});
}
The issue is that when the button is clicked it posts a random title from inside the array instead of the title of the item the button was appended with... How can I bind the buttons function to the correct dataTitle?
I'm not sure if that makes sense so please let me know if clarification is needed. Thanks in advance for any help you can provide!
This fails because you are iterating the entire list and assigning them to a global variable. The result is not random at all--it's the last item in the list, which was the last to be assigned to the globar variable.
Try using jQuery rather than writing your own DOM events, and utilize a closure to reference the video title.
function saveToDatabase(dataTitle) {
ref.push({
title: dataTitle
});
}
$.ajax({
type : 'GET',
url : url,
dataType : "jsonp",
cache: false,
success : function(data) {
console.debug(data); // console.debug not supported in all (any?) versions of IE
buildVideoList(data.response.items);
}
});
function buildVideoList(vids) {
$.each(vids, function(vid) {
var $img = $('<img></img>');
$img.attr('src', sanitize(vid.title));
var $button = $('<button class="btn">Save</button>');
$button.click(saveToDatabase.bind(null, vid.title));
$('<div class="tile"></div>')
.append($img)
.append($button)
.appendTo('#content');
});
}
// rudimentary and possibly ineffective, just here to
// point out that it is necessary
function sanitize(url) {
return url.replace(/[<>'"]/, '');
}
I actually just ended up passing the index to the function by creating a global array like so. It seems to be working fine... any reason I shouldn't do it this way?
var vids = []; //global
function foo() {
$.ajax({
type : 'GET',
url : url,
dataType : "jsonp",
cache: false,
success : function(data){
console.debug(data);
vids = data.response.items;
for(var i in vids) {
ncode = "<div class='tile'><img src='"+ vids[i].title "'/></a><button class='btn' type='button' onClick='saveToDatabase('+i+')'>Save</button></div>";
$('#content').append( ncode )
} //end ajax function
function saveToDatabase(i) {
ref.push({
title: vids[i].title
});
}

Calling Javascript Functions In Order

I'm trying to use a button to perform an API Call to Flickr, like so:
$(document).ready(function (){
$('#goButton').click(function (){
makeAPICall();
});
});
This works as expected, but the communication between the client and the Flickr API takes a while to execute, so the page appears like it is hung. I would like to add a "Working Notice" that is displayed immediately on button click to let the user know that their action is processing.
To do this, I added an H1 tag:
<h1 id="notice"></h1>
and a function that changes the inner HTML to display a notice:
function workingNotice() {
document.getElementById("notice").innerHTML="I am getting your results";
}
But when I try to edit the code for the button to something like this:
$(document).ready(function (){
$('#goButton').click(function (){
workingNotice();
makeAPICall();
});
})
The Working Notice is never displayed until the API Call has completed, which defeats the purpose.
I then tried using:
$(document).ready(function (){
$('#goButton').click(function (){
$.when(
workingNotice()
).then(
makeAPICall()
);
});
})
This gives the exact same results, where the Working Notice is not called until the API Call completes. Is there any alternative that I can try to force the order of these functions to comply?
UPDATE/EDIT:
While I found the solution to the initial problem in another answer, I know there's a reasonable chance the delay in the API Call processing is due to some mistake in this function. Here is the code for makeAPICall:
//call Flickr api and look for tags matching user search term
function makeAPICall(){
//get value tag from team 1 search box
var searchTag1 = escape(document.getElementById("searchTag1").value);
//get value tag from team 2 search box
var searchTag2 = escape(document.getElementById("searchTag2").value);
//build api call url with searchTag1
var url1 = "http://api.flickr.com/services/rest/?"
+ "method=flickr.photos.search&api_key=XXX&tags="
+ searchTag1 + "&sort=interestingness-desc"
+ "&safe_search=1&has_geo=1&format=json&nojsoncallback=1";
//build api call url with searchTag1
var url2 = "http://api.flickr.com/services/rest/?"
+ "method=flickr.photos.search&api_key=XXX&tags="
+ searchTag2 + "&sort=interestingness-desc"
+ "&safe_search=1&has_geo=1&format=json&nojsoncallback=1";
//make call to flickr api
$.when(
$.ajax({
dataType: "json",
url: url1,
async: false,
success : function(callReturn1) {
callData1 = callReturn1;
numResults1 = parseInt(callData1.photos.total);
}
}),
$.ajax({
dataType: "json",
url: url2,
async: false,
success : function(callReturn2) {
callData2 = callReturn2;
numResults2 = parseInt(callData2.photos.total);
}
})
).then(
drawChart()
);
}
Note "callData1", "callData2", "numResults1" & "numResults2" are all global.
If your makeAPICall is not async - call it out of bounds:
workingNotice();
setTimeout(makeAPICall, 1);

How to pass a javascript variable to php without opening a new page

I have a user enter a value in a form and onClick() activates a function that takes the URL the user pasted and cuts it down (using an algorithm I made, but that is irrelevant). I end up with a string of 11 characters and im not sure how to get this to a php page that submits it to my database. The way i am doing it now takes the browser to a new page and i want the user to stay on the same page.
function findvideoid(){
window.location.href = 'submitvid.php?videoID=' + videoID;
}
Pure JavaScript solution (recommended):
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyStatus == 4) { // finished
if (xhr.status == 200) { // 200 HTTP code returned by server
}
else { // error
}
}
};
xhr.open("GET", "your-script.php?videoID=" + encodeURIComponent(videoID));
xhr.send(null);
jQuery solution (recommended if you already use jQuery in your project or if you want to try it out):
// PHP script can access $_GET['videoID']
jQuery.get("your-script.php?videoID=" + encodeURIComponent(videoID));
// PHP script can access $_POST['videoID']
jQuery.post("your-script.php", {videoID: videoID});
jQuery.get( url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] )
jQuery.post( url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] )
What about masking the actual ajax call with the loading of an external html resource?
If no real callback is expected, you could inject an iframe into the document pointing to the specified url and then remove it from the document.
Here's an example of accessing your backend's api url masked by loading an image:
function findvideoid(id, callback){
var img = new Image();
img.onload = callback;
img.src = apiUrl + '?videoId=' + encodeURIComponent(id)
+ '&antiCache=' + new Date().getTime();
}
No ajax. No other libs. Google does it for it's analytics. Why shouldn't you?
Use AJAX:
function findvideoid()
{
var html = $.ajax({
type: "POST",
url: "submitvid.php",
data: "videoID=" + videoID,
async: false
}).responseText;
if(html == "success")
{
// Uncomment the following line in your application
//return true;
}
else
{
return false;
}
}
You can do this easily in jQuery
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});

ajax success callback not working

So I have this JavaScript which works fine up to the $.ajax({. Then it just hangs on the loader and nothing happens.
$(function() {
$('.com_submit').click(function() {
var comment = $("#comment").val();
var user_id = $("#user_id").val();
var perma_id = $("#perma_id").val();
var dataString = 'comment='+ comment + '&user_id='+ user_id + '&perma_id=' + perma_id;
if(comment=='') {
alert('Please Give Valid Details');
}
else {
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="ajax-loader.gif" />Loading Comment...');
$.ajax({
type: "POST",
url: "commentajax.php",
data: dataString,
cache: false,
success: function(html){
alert('This works');
$("ol#update").append(html);
$("ol#update li:first").fadeIn("slow");
$("#flash").hide();
}
});
}
return false;
});
});
Try replacing:
var dataString = 'comment='+ comment + '&user_id='+ user_id + '&perma_id=' + perma_id;
with:
var dataString = { comment: comment, user_id: user_id, perma_id: perma_id };
in order to ensure that the parameters that you are sending to the server are properly encoded. Also make sure that the commentajax.php script that you are calling works fine and it doesn't throw some error in which case the success handler won't be executed and the loader indicator won't be hidden. Actually the best way to hide the loading indicator is to use the complete event, not the success. The complete event is triggered even in the case of an exception.
Also use a javascript debugging tool such as FireBug to see what exactly happens under the covers. It will allow you to see the actual AJAX request and what does the the server respond. It will also tell you if you have javascript errors and so on: you know, the kinda useful stuff when you are doing javascript enabled web development.

Get URL parameters from text link and post to AJAX call

I'm currently working on a bit of jQuery that will allow users to make an AJAX call from a text link. This is no problem but the text link has parameters that I need to send to the AJAX request in order for it to execute properly.
My text link looks something like this:
Click here
Here is my jQuery:
function getUrlParam(name)
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
/* Let's create a function that will allow us to vote on the hosts */
function hostVote() {
/* These variables are used to determine the button clicked */
var affiliate = getUrlParam('affiliate');
var voteType = getUrlParam('voteType');
$.ajax({
cache: false,
type: "POST",
url: "/php/hostvote.php",
data: "affilate=" + affiliate + "&voteType=" + voteType +"",
success: voteSubmitted
});
function voteSubmitted() {
alert('Thanks for voting');
$(this).addClass('yes');
}
return false;
};
$("a.vote").click(hostVote);
The trouble with this code is I can't submit the link to put any parameters in the url before the function is executed, resulting in empty affiliate and voteType vars.
Can anyone help?
A better approach would be to store the data you need in the data-* attribute of the link. This would make it much easier to retrieve the corresponding data. Here's a simple example of how it would work.
Click here
$("a.vote").click(function(e){
var affiliate = $(this).data('affiliate');
var voteType = $(this).data('voteType');
// do your ajax call here
e.preventDefault();
});
Instead of -
var results = regex.exec( window.location.href );
could you do -
var results = regex.exec($("a.vote").attr('href'));
and parse the variables directly from your link?

Categories