jquery get request error - javascript

I am trying to make a get request once the user enters an value and pass that value as parameter however nothing happens. The alert outside theget function works fine. here is my code
$(document).ready(function(){
$( "input[type='text']" ).change(function() {
$.get("http://example.com/get.php?number=1234", function(data, status){
alert("Data: " + data + "\nStatus: " + status);
$("#result").html( data );
});
alert("end of script");
});
});
https://jsfiddle.net/4rrous4y/3/

To send a parameter along to get.php you need to append a query string.
In your $.get after the URL add ?parameter=value and change the values accordingly.

I think you are having a cross origin issue here. Basically if the resource you are trying to load is in a different domain than the origin of the request, it won't let you access to it.
Check the console in Google Chrome, some error should be appearing there.

Related

$http.jsonp retrieves data correctly but does not pass it to .success function

Working with the Instagram API trying to do pagination correctly.
I have the following function, getMoreUsers, which, when fired, should push the next set of users into my $scope.followers variable, and then set the pagination variable to the new pagination URL provided in the returned JSON.
$scope.getMoreUsers = function() {
console.log("i have been clicked");
console.log('pagination: ' + pagination);
$http.jsonp(pagination).success(function(result){
console.log(result);
debugger;
$scope.followers.push(result.data);
pagination = result.pagination.next_url;
console.log("followers" + $scope.followers);
})
.error(function(result) {
console.log('uh-oh', result);
});
};
When I click on the link with the corresponding ng-click attribute, the "i have been clicked" and pagination logs are correctly sent to the console. The next log in the console is "uh-oh", undefined, suggesting that there was an error in the jsonp call. However, in Chrome's network tab, I see a GET request to the url specified by the pagination variable, with a 200 status.
So, for some reason, the jsonp call is reaching and retrieving the right information, but the error function is being called instead of the success function. Any ideas?
Try appending ?callback=JSON_CALLBACK to the end of your url.

Jquery ajax get method not working

I am using the following code but it seems to be not working. Sorry for asking this simple question but I want to know why this code is not working
$(document).ready(function(){
$("button").click(function(){
$.get("smiley1.html",function(data,status){
alert("Data: " + data + "\nStatus: " + status);
});
});
});
<button>Send an HTTP GET request to a page and get the result back</button>
Please help me to solve it. Thanks
Code is fine but, it matter from where you are running it.
If you are trying to run from snippet runner of this page, if will fail because of 2 reasons
it doesn't find $ (i.e. jQuery)
it is trying to do cross domain call, which I believe is not allowed from target page. smiley1.html is not present on stackoverflow.com domain,
you can see error in developers console
If try it in jsfiddle
$(document).ready(function(){
$("button").click(function(){
$.get("x2rmptu3/show/",function(data,status){
alert("Data: " + data + "\nStatus: " + status);
});
});
});
here is my fiddle http://jsfiddle.net/x2rmptu3/2/

How to properly use load()?

In page I use jQuery .load() to apply database changes without reloading, have 2 steps:
load change.php?id=1&change=delete
reload list of items
Its simply illustration, I have more options (change rank, change text...), but all is implemented identically.
Problem: someone script doesn't show list, if I have in list.php console.log('text'), text shows in console, but list of items are not in div.
It happens more when I have 1+ requests per second.
It is possible to reach absolute reliability?
Thank you, Rob.
PS. I use simply onclick=func() in button and the
function func(){
$('#div1').load('change.php?id=1&change=delete');
$('#div2').load('list.php');
}
did you check the response you get from the server?
If not try this snippet
$( "#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 );
}
});
I have solution.
Problem: delay in db update
Solution:
function func(){
$('#div1').load('change.php?id=1&change=delete', function (){
$('#div2').load('list.php');
});
It is good solution?

AJAX and JSON error handling

I have a form which submits data via AJAX to an external server.
The data which gets sent is then validated and if correct the user can then advance onto the next step of the form.
If the data is not valid, then the server returns an error which is outputted as a JSON object.
I can see the JSON object in FIDDLER.
My aim is to grab that JSON data and output it on the page and notify the user.
Ideally, i would do this as part of an error handler on the AJAX request(found below).
Is this achievable?
PS:
Unfortunately, I can't set up a demo because the link that the data is posted to is only available on my network.
It is also worth pointing out that the error that the back-end script outputs is actually stored in the link that the data is posted to.
AJAX REQUEST:
var setUpVrmData = function() {
$("#getvrmdata").click(function () {
var p_vrm = $('#p_vrm').val();
$.ajax({
dataType: "JSON",
type: "POST",
url: "http://217.35.33.226:8888/l4_site/public/api/v1/BC8F9D383321AACD64C4BD638897A/vdata",
data: {
vrm: p_vrm,
},
success: function(data) {
//Empty the dropdown box first.
$("#p_model").empty();
appendString = "<option value='none'>-- Select your model --</option>";
$.each(data['vehiclemodel'], function (k, v) {
// += concatenate the string
appendString += "<option value='" + k + "'>" + v + "</option>";
});
$("#p_model, #ent_mileage").show();
$('.js-find-my-car').hide();
$('.js-get-price').show();
$("#p_model").append(appendString);
$("#p_model").prop("disabled", false);
$('#skey').val(data['skey']);
},
error: function() {
console.log("We return error!");
}
});
});
The Error function will return an XHR object that you may be able to parse to get the message you want. I don't know what is serving the data so depending on how that's setup your mileage may vary. I've done this using PHP as well as C# and writing to Console, but in both cases I was able to control the returned data.
I used this article : http://encosia.com/use-jquery-to-catch-and-display-aspnet-ajax-service-errors/ as a starting point.
You'll need to update:
error: function() {
console.log("We return error!");
}
to
error: function(xhr, status, error) {
console.log("We return error!");
}
Set a break point there in Firebug to check if an XHR object is passed, if not you'll need to find a way to get it.. You mention you can see the JSON in fiddler, it should be available to you. If it is, just use the eval posed in the article and you should be okay. If not you'll have to go and figure out how to get it, depending on your platform difficulty will vary.
A few things to note, eval is messy and can get you into trouble. In the cases I've done this, I removed the eval in production.
Also as of jQuery 1.8 success error and complete are deprecated. Use done fail and always if you plan on updating jQuery in the future.
jQuery API reference, for reference.
http://api.jquery.com/jquery.ajax/

Why doesn't simple google web search through getJSON always work?

This simple web search through google API is shaky. Sometimes it returns the 4 first findings (as it should), sometimes JSON thinks its a "success" but the responseData is null. Why am I getting these inconsistencies? Is it a asyncronic problem? How do I make it more stable? (When I search for images on google it is rock stable)
var baseUrl = "https://ajax.googleapis.com/ajax/services/search/web?v=1.0&start=0&q=";
var searchTerm = "obama"; //Lots of hits
$(document).ready(function() // don't do anything until the document is loaded.
{
$.getJSON(baseUrl + searchTerm + "&callback=?", function(json) // call getJSON providing the complete url with search term and a JSONP callback
{
$.each(json.responseData.results, function(i, gResults){
console.log("title: " + gResults.titleNoFormatting);
});
});
});
When it fails I find this in the json data structure:
json.responseDetails: "Suspected Terms of Service Abuse. Please see
http://code.google.com/apis/errors"
So Google think I'm attacking it with too many requests. Do I have to set an API key? right now I just include the
<meta name="google-site-verification" content="myAPIkey-Herevbng66r" />
But I'm running on my local computer so maybe it doesn't help…
Try this:
function(json) // call getJSON providing the complete url with search term and a JSONP callback
{
if (json.responseData === null)
console.log("json returned nothing");
else
$.each(json.responseData.results, function(i, gResults){
console.log("title: " + gResults.titleNoFormatting);
});
});
});

Categories

Resources