AJAX GET Request to API(Same origin policy does not apply) - javascript

I am making an attempt to do a GET through an AJAX request towards an API. I am aware of the same origin policy. But the web service gave me a special API key to perform the GET AJAX request to the API. The problem is that I am not getting either a alert(data) success or alert(boom) error. Nothing is being displayed. The jquery function is taking the value from the textbox and then using that data to perform the api call.
<script>
$(document).ready(function () {
var timer = null;
var $new_result=$("#entry");
var $api = $new_result.data('url',$new_result.val());
function submitForm( input ) {
$.ajax({
type: "GET",
url: $api,
success: function(data) {
alert(data);
},
error: function() {
alert("boom");
}
});
return false
}
$("#entry").on("change", function() {
var input = $(this).val();
clearTimeout(timer);
timer = setTimeout(function(){
submitForm(input) ;
}, 1000);
})
});
</script>
<input type="text" id="entry" name="entry" style="width: 1000px;" value="http://somesite.com/apikey?123658744sdfs88f7></br>

This doesn't look correct at all:
var $new_result=$("#entry");
var $api = $new_result.data('url',$new_result.val());
Rather, if you want to get the value from the input, as you stated, you should use the following:
var api = $("#entry").val();
Unless you've explicitly set the url value on the data object on that input somewhere else in your code, nothing is going to exist there, which may be the cause of your problem.

Related

ASP.net: AJAX Result Not Kicking Off

I think this will be a weird one for you as I am at my wits end with this. On a screen I have in a table, I have a link being clicked that is setting off a javascript/ajax request. I have similar code in another screen that works perfectly as it heads down into the success part of the ajax call and runs code in the success portion of the call. For some reason though I can't seem to get this to work and when I debug it in chrome, I lose my breakpoints and it never seems to get into the success portion of the Ajax call.
#section scripts{
<script>
// Get the bond ID Data from the row selected and return that to the program.
function getIDData(el) {
var ID = $(el).closest('tr').children('td:first').text();
var iddata = {
'ID': ID
}
console.log(iddata);
return iddata;
}
// Submit the data to a function in the .cs portion of this razor page.
$('.updatelink').click(function () {
var bondid = JSON.stringify(getIDData(this));
$.ajax({
url: '/Maintenance/Bond_Maint?handler=UpdateandReloadData',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
type: 'POST',
dataType: 'json',
data: { bondid: bondid },
success: function (result) {
if (result.pass != undefined) {
document.forms[0].submit();
}
},
});
});
</script>
}
The ASP.net code behind that is calling does an update to the database and then passes back a variable containing Success as its message.
//-------------------------------------------------------------------------------
// Try to get and insert the data from a selected row and copy it
//-------------------------------------------------------------------------------
public ActionResult OnPostUpdateandReloadData(string bondid)
{
return new JsonResult(new { pass = "Success" });
}
I'm not sure how else to describe my issue other than when I debug my other code via the browser, it appears to take a different path than this code does and I cannot fathom why. For reference my other code looks like this:
#section scripts{
<script>
// Get the offender ID Data from the row selected and return that to the program.
function getIDData(el) {
var ID = $(el).closest('tr').children('td:first').text();
var iddata = {
'ID': ID
}
console.log(iddata);
return iddata;
}
// Submit the data to a function in the .cs portion of this razor page.
$('.copybtn').click(function () {
var offenderid = JSON.stringify(getIDData(this));
$.ajax({
url: '/Copy_Old_Account?handler=CopyData',
beforeSend: function (xhr) {
            xhr.setRequestHeader("XSRF-TOKEN",
                $('input:hidden[name="__RequestVerificationToken"]').val());
        },
type: 'POST',
dataType: 'json',
data: { offenderid: offenderid },
success: function (result) {
if (result.path != undefined) {
window.location.replace(result.path);
}
},
});
});
</script>
}
Any help would be appreciated.
Okay guys so first off, thank you everyone for responding to my question. Frank Writte and Alfred pointed me into the right direction by looking for the status in the network tab for my calls. I found out that I was getting cancellations for my requests. After looking into that I found this article What does status=canceled for a resource mean in Chrome Developer Tools? that has an answer from FUCO that gave me what I needed to do. Apparently I needed to add event.preventDefault(); in front of my ajax call and all of a sudden my code worked. I'm not sure I completely understand why this works but I can't complain about the results. Again thank you everyone for trying to help. This one has been boggling my mind all morning.

Is there a time lag in the YouTube Data API 3 rate endpoint?

I have an application that displays a YouTube video and has a rate button to allow a user to like or unlike the video. On the click event 3 functions are called chained together through the success function of the ajax. The flow is this: ytvRate() -> getRating() -> showRating()
When I log the actions and results the response from getRating() does not have the value that I sent in ytvRate(). If I wait a while and refresh the page, the result of getRating() comes back correct. I call getRating() inside the success function of the ajax in ytvRate(). Doesn't that mean the function should not be called until a success response is received?
Here is an example of my logs:
rating sent: like
call get rating
this is my rating: none
call show rating
As you can see, the rating returned from the API is not correct - it should be the rating I just sent. Upon refresh the same call does return the correct rating... so, is there a delay or something to the data api updating the correct information? How can I get the correct rating on the same button click that sends the request?
Here are the functions (showRating does not seem relevant to the problem. It works fine as long as it gets the correct rating - which it is not.)
function ytvRate(id, rating, event){
event.preventDefault()
var apiKey = 'This is a valid key';
var client_id = 'This is a valid client id';
var redirect_uri = 'This is a redirect uri';
var scope = 'https://www.googleapis.com/auth/youtube';
var rateUrl = 'https://www.googleapis.com/youtube/v3/videos/rate?id='+id+'&key='+apiKey+'&rating='+rating;
if(getHash().access_token){
var token = getHash().access_token;
$.ajax({
type: "POST",
url: rateUrl,
beforeSend: function (request){
request.setRequestHeader('Authorization', 'Bearer ' + token);
},
success: function(data){
console.log('rating sent: '+rating);
getRating(id);
},
error: function(e) {
console.log(e);
}
});
} else{
window.location = 'https://accounts.google.com/o/oauth2/v2/auth?client_id='+client_id+'&redirect_uri='+redirect_uri+'&scope='+scope+'&response_type=token&prompt=consent&include_granted_scopes=false';
}
return false;
}
function getRating(id){
var getRatingUrl = 'https://www.googleapis.com/youtube/v3/videos/getRating?id='+id;
console.log('call get rating');
if(getHash().access_token){
var token = getHash().access_token;
$.ajax({
type: "GET",
url: getRatingUrl,
beforeSend: function (request){
request.setRequestHeader('Authorization', 'Bearer ' + token);
},
success: function(data){
var rating = data.items[0].rating;
console.log("this is my rating: " + rating);
showRating(rating, id);
}
});
}
}
function showRating(response, id){
console.log('call show rating');
numLikes(id);
if(response == 'like'){
document.getElementById("notliked").className = "hide";
document.getElementById("liked").className = "";
document.getElementById("like-btn").style.color = "#87CEFA";
document.getElementById("like-btn").setAttribute("onclick", "ytvRate('"+id+"', 'none', event)");
} else{
document.getElementById("notliked").className = "";
document.getElementById("liked").className = "hide";
document.getElementById("like-btn").style.color = "inherit";
document.getElementById("like-btn").setAttribute("onclick", "ytvRate('"+id+"', 'like', event)");
}
}
Edit:
Interestingly, if I call the youtube/v3/videos resource in a new method instead of youtube/v3/videos/getRating and access the statistics.likeCount, the number is instantly updated. Why can I not receive the user rating with the same efficiency?
After the discussion in the comments I suggest you to take a different approach. When ytvRate success you don't need to fetch getRating as you already know what is the rating set by the user.
The rate method is like a setter in regular programming language - if it successed (didn't throw an exception or returned an error) you can assume the current value is the one you set without fetching it again. This might be wrong assumption in multithreaded/distributed enviroments but might be ok in your case.
function ytvRate(id, rating, event){
...
success: function(data){
console.log('rating sent: '+rating);
showRating(rating, id);
}
...
}

Ajax success/error message only displaying once

I have created a form using php ajax and JavaScript.
With ajax I successfully managed to display an error/success message while staying on the same page.
It works alright if I use console.log to display the error/success message.
But I don't want to display the error message on the console.log
so this is what I did:
$('form.form-style-4').on('submit', function() {
var that = $(this),
url = that.attr('action'),
method = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: method,
data: data,
success: function(response) {
console.log(response);
$('#success-message').html(response);
setTimeout(function() {
$('#success-message').fadeOut('slow');
}, 3000);
}
});
return false;
});
As you can see I created a div called #success-message the reponse is displayed in this div.
My problem now is It only shows the error or success message just once, unless I reload the page.
So my first idea was to reload the entire page every time someone clicks on submit, with javascript like this:
setTimeout(function() {
window.location.reload(1);
}, 2000);
But I don't think that is the way to go.
You have to show your message success-message first
$('#success-message').html(response).show();

ajax sends POST twice, receiving double/repetitive results from PHP

i found out my JS sends POST method twice to my PHP file, thats why i keep getting double/repetitive results from my PHP.
This JS event, upon .keyup() will execute an ajax.
$(document).ready(function() {
var getUrl = $('#url');
var youtube = regex here
var web = regex here
getUrl.keyup(function() {
if (youtube.test(getUrl.val())) {
var youtube_url = getUrl.val().match(youtube)[0];
$.ajax ({
type:"POST",
url:"getyoutube.php",
data: {youtube_url:youtube_url},
success: function(html) { $('.echotest').append(html); }
}); }
else if (web.test(getUrl.val())) {
var extracted_url = getUrl.val().match(web)[0];
$.post("curl_fetch.php?url="+ extracted_url, {
}, function(response){
$('#loader').html($(response).fadeIn('slow'));
$('#cur_image').val(1);
});}
});
});
the data will be received by getyoutube.php and should only print json result of a particular youtube video once.
//some code ommitted
$youtube ="https://gdata.youtube.com/feeds/api/videos/'.$matches[0].'?v=2&alt=jsonc";
$curl = curl_init($youtube);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$return = curl_exec($curl);
curl_close($curl);
$test = json_decode($return, true);
print_r($test);
i cant seem to figure out why my AJAX post keeps sending POSTS method twice
Couple of things to try:
1) Make sure you bind and unbind your key up event
2) Use a global variable to make sure only one ajax request gets sent at once
i.e.:
var ajaxrequest = false; //GLOBAL
function getyoutubedata(){
if(ajaxrequest != false){
return;
}
ajaxrequest = $.ajax ({
type:"POST",
url:"./includes/getyoutube.php",
data: {youtube_url:youtube_url},
success: function(html) { $('.echotest').append(html); ajaxrequest = false; }
});
}
Btw thing to note the youtube api supports jsonp callbacks so you might want to consider doing this through that
3) Try to check if the content of the input field has changed even before calling the above function
You should show us the code with the .keyup() event, probably that's the place of an error. The event handler could execute a wrapper function for the ajax, instead of the ajax directly. For example, if you the keyup event is triggered, try to check if the input content has changed. If so, run ajax, if not - do nothing.
coverted this
$.ajax ({
type:"POST",
url:"getyoutube.php",
data: {youtube_url:youtube_url},
success: function(html) { $('.echotest').append(html); }
}); }
to this.
$.post("./includes/getyoutube.php?url="+ youtube_url, {
}, function(response){
$('.echotest').append(response);
});
POST method is now being executed once. although i cant really explain technically why it worked.

jquery ajax form - how to get the redirect url?

i'm using ajax form jquery plugin to submit a form (in a dialog) via ajax.
this works fine and then i get the html response back from the server. the response comes from a standard redirect-after-post php page which i cannot modify.
is there a way to obtain the url of this redirect (the final GET location) using jquery (inside the ajax callback) ?
$j('span.sfAutocomplete a').click(function(e){
var url = this.href;
var $dialog = $j('<div id="ajaxDialog"></div>').appendTo('body')
.load(
url,
'sfAutocomplete=true',
function (responseText, textStatus, XMLHttpRequest) {
$dialog.dialog({ autoOpen: true });
//
// Ajax submit
//
$j('#ajaxDialog form').submit(function() {
function showResponse(responseText, statusText) {
// how to get the redirect url ?
}
$j(this).ajaxSubmit({
success: showResponse
});
return false;
});
}
);
return false;
});
I haven't used the plug-in you are using, but if you use the jQuery Ajax command, you receive the XMLHttpRequest object as a parameter to the complete event. You can then get the post URL from the HTTP header that returns. Try the following:
$.ajax({
url:'your.url',
data:'your data',
complete: function(xhr,textstatus) {
// xhr.responseText contains the response from the server
var allheaders = xhr.getAllResponseHeaders();
// this will get all headers as a string - if you want them as an object...
var eachheader = allheaders.split('\n');
var headers = {};
for(i = 0; i < eachheader.length; i++) {
if ($.trim(eachheader[i]) !== '') {
headersplit = eachheader[i].split(':');
headers[headersplit[0]]=$.trim(headersplit[1]);
}
}
}
});
This code was copied from this thread.

Categories

Resources