I'm writing a dynamic js that should send a request to an action, that is defined in the href attribute in a link.
The link look like that:
show something
As you can see the link has a get param named callback. That is defined, because the request method should be as generic as possible and the element should know by itself, what it has to do with the response.
Now i send the request with jquery ajax function to the action, looking like that:
jQuery('#mylink').live("click", function() {
jQuery.ajax({
type: 'GET',
dataType:"jsonp",
error: ErrorHandler.catchXhrError,
url: jQuery('#mylink').attr('href');
});
});
That works very well, in principle. But my problem is, that jquery defines its own callback get param and i don't know, how i can tell the method, that the callback param in my links href is the right one and the request-uri is looking like that:
http:/example.com/module/action?callback=MyCallback&callback=jsonp1279196981233
The only way out i see, is to define my own callback-param named mycallback and interpret mycallback in the action instead of callback:
show something
But i don't like this solution, because my request uri has a param that will not be used:
http:/example.com/module/action?mycallback=MyCallback&callback=jsonp1279196981233
Please attend, that i could not define the name of the callback method inside the ajax method
jQuery('#mylink').live("click", function() {
jQuery.ajax({
type: 'GET',
dataType:"jsonp",
jsonpCallback: 'MyCallback',
error: ErrorHandler.catchXhrError,
url: jQuery('#mylink').attr('href');
});
});
because the send Method should be generic and will be used across our whole side and the response has to be processed in many different ways by different js methods.
Hope i could describe my problem sufficiently and would be happy about any help.
You should use the jQuery.ajax version but not hardcode the callback name. Instead parse the href attribute and extract the name of the callback to use..
and here is the parsing..
jQuery('#mylink').live("click", function() {
var href = jQuery('#mylink').attr('href');
jQuery.ajax({
type: 'GET',
dataType:"jsonp",
jsonpCallback: href.match(/([?&]callback[a-zA-Z0-9=]+)/)[0].split('=')[1],
error: ErrorHandler.catchXhrError,
url: href;
});
});
Have you looked into http://code.google.com/p/jquery-jsonp/ ?
Related
I have this javascript code that performs an ajax request on button click.
$('#allinea').click(function(e){
e.preventDefault();
var password = $('#password').val();
$.ajax({
type: "POST",
url: "db_align.php",
data: {password:password},
complete: function(data){
data1=data.split("|");
if(data1[0]=="Successo"){
$("#per_all").fadeTo(200,0.1,
function(){
$(this).find('img').attr("src",'../images/ok.png');
$(this).find('.right').html(data1[1]).promise().done(function(){
$(this).fadeTo(900,1);
});
});
}else if(data1[0]=="Errore"){
$("#per_all").fadeTo(200,0.1,
function(){
$(this).find('img').attr("src",'../images/alert.png');
$(this).find('.right').html(data1[1]).promise().done(function(){
$(this).fadeTo(900,1);
});
});
}
}
}); //chiudo $.ajax
});
The php page returns "Successo|Allineamento riuscito" and I see it correctly in firebug but the js returns an error:
Type error: data.split is not a function
data1=data.split("|");
I use this code everywhere in my app without any inconvenient. What am I doing wrong this time?
For what I see btw this is not an array so this should work without any inconvenient!
jQuery will return a jqXHR here, which means that instead of accessing data directly, you will probably need to do data.responseText.
Exo's answer is perfect. It will allow you to edit the raw text.
If you know the type of data returning, you can (must) set it explicitly. jQuery will then programmatically convert data for you in the correct format.
dataType: json for JSON,
dataType: text for plain text
More can be found in the documentation.
You should update your complete method to done for success condition and fail for when the request fails.
complete is deprecated as of version 1.8, it's replaced with always, which returns a data or jqXHR object. When success complete will return a data object according to the functionality of done.
I am new in the area of jQuery/Ajax and my little test function doesn't work. And my page is also refreshingcan any one help me
<script type="text/javascript" >
$(document).ready(function() {
$("#ser_itm").change(function() {
var id=$(this).val();
var dataString = 'id='+ id;
alert(dataString);
$.ajax({
type: "POST",
url: "bar_pull.php",
data: dataString,
cache: false,
success: function(html) {
$("#tbl").html(html);
}
});
});
});
Pass the function, not the result of the function call:
$('.linkDetails').on('click', getDetailsFromServer);
Apply the same to your AJAX success callback:
success: postToPage
Also, the getDetailsFromServer() function needs to be defined before you bind it to an event. Move the function declaration before your .on('click', ...) call.
So I'm going to try and explain these points more clearly:
You cannot access C:\Users\yah\Desktop\text.txt. This is a server side path, your javascript runs on the client side. So this needs to be a path you can browse to in your browser, something like /pathinURL/text.txt. How you do this is dependant on your hosting technology, etc.
Your call backs are also wrong,
$('.linkDetails').on('click', getDetailsFromServer());
&
success: postToPage()
these will execute the function when they are hit, (well it actually binds the function result) not when the event happens. To make these work you need to remove the braces:
$('.linkDetails').on('click', getDetailsFromServer);
&
success: postToPage
this then hooks up the actual functions as function pointers and thus the actual functions will be fired when you want them to be.
so your final code will look like:
$('.linkDetails').on('click', getDetailsFromServer);
function getDetailsFromServer() {
$.ajax({
type: 'GET',
url: '/someURL/text.txt',
success: postToPage
});
}
function postToPage(data) {
$('.textDetails').text(data);
console.log(data);
}
what Arun P Johny said is right! but your code has another probloem
$('.linkDetails').on('click', getDetailsFromServer);
try above
The same origin policy implemented by browsers prevents local file system urls... if the page and the files are in same folders it might work.
See SOP for file URI for FF
I'm having trouble pulling a specific element from an API call using jQuery's getJSON function. I'm trying to use SunlightLab's congress API to pull specific info about legislators. In the example below I'm trying to pull a legislator's website:
$.getJSON("http://services.sunlightlabs.com/api/legislators.get.json?apikey=[api key]&lastname=Weiner&jsonp=?" , function(data) {
alert("hello from sunlight");
alert(data.response.legislator.website);
});
Using the above code, the first alert shows up but the second alert does not even occur. I understand that getJSON should be using JSONP in this instance, and I think I have that set up correctly, ending my URL with '&jsonp=?'.
Putting the URL in my getJSON function into a web browser gives me this:
?({"response": {"legislator":
{"website":
"http://weiner.house.gov/", "fax":
"202-226-7253", ... etc.
I'm a little thrown by the '?' showing up at the beginning of this, but if the first alert is showing up then the request must be succeeding...
The URL you're using is setting the JSONP callback to be equal to ?, which means its injecting a JavaScript function called ? with an argument of a JavaScript object. This is invalid. So, the request is succeeding, but the wrapper function you've defined isn't being called (and isn't valid).
You could change the URL so that its jsonp=callback (or some other handler function name), and then define a function called callback that handles an argument that expects the object.
One way to (automatically) trigger JSONP support in jQuery is to switch the key to be called 'callback' so that it signals to jQuery that you're doing a JSONP call. ie, callback=callback.
EDIT: As Drackir points out, jQuery provides a setting in $.ajax for letting it define it's own callback function name, but you need to signal to it that its a JSONP call by setting dataType: 'jsonp' in the $.ajax call.
The question mark is there because you specified the JSONP callback function to be ? in your query string (ie. &jsonp=?). Due to security concerns (specifically the same-origin policy) you cannot do an AJAX request to a site outside the same domain as the page you're on. To get around this, JSONP works by creating a script tag, with the SRC set to the URL of the script on the other site. This will load the external JavaScript file and run whatever code is there. Now, in order to link that external code with your JavaScript, the external API takes the name of a function to call (&jsonp=functionnametocall). The returned JavaScript calls that function and passes in the data it's trying to return as a JSON object as the first argument.
So, the reason you see the question mark when you go there is because you're passing a question mark to the jsonp query string parameter. jQuery will automatically convert the question mark in a url such as http://www.test.com/api/apikey=292929&callback=? to a uniquely named function. This is handled in the background by jQuery so you don't have to think about it.
Now, that said, I don't know if jQuery detects if the name of the callback parameter as being something other than callback=?. $.getJSON() however is a short form for the longer:
$.ajax({
url: url,
dataType: 'json',
data: data,
success: callback
});
I suggest you try using $.ajax() directly and set the jsonp setting equal to "jsonp". This tells the $.ajax() method that the query string parameter is called jsonp and not callback. So like this essentially:
$.ajax({
url: url,
dataType: 'json',
data: data,
success: callback,
jsonp:"jsonp"
});
More information: $.getJSON | $.ajax()
OK, OK, so it was a rather simple fix, adding a line to the the example given by #Drackir. The missing piece was 'cache: true' within the ajax settings. The final working code looked like this:
$.ajax({
url: 'http://services.sunlightlabs.com/api/legislators.get.json?apikey=[api key]7&lastname=Weiner',
dataType: 'jsonp',
cache: true,
jsonp: 'jsonp',
success: function(data) {
alert("hello from ajax") ;
alert(data.response.legislator.website);
}
});
I'm not sure why 'cache: true' is needed in this case. Thanks for the help.
It seems, at the first glass, that we can use either of those. I'm wondering, however, when should we use one or the other, assuming a scenario where we can do the same thing with any of those two.
Thanks in advance,
MEM
jQuery.post is a shorthand method which calls jQuery.ajax.
If you don't need any functionality not supported by the shorthand, you might as well use it.
It's defined like this:
post: function( url, data, callback, type ) {
// shift arguments if data argument was omited
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = {};
}
return jQuery.ajax({
type: "POST",
url: url,
data: data,
success: callback,
dataType: type
});
},
The $.post is actually derived from $.ajax. You can use $.post when you want want to set the POST method in your request. $.ajax allows you to set both GET and POST request methods.
Using $.ajax allows you to set callbacks for failure, and completion, while $.post has callback only for success. Also, $.ajax allows to set a callback to be invoked before the sending of the request and set other useful parameters as timeout time , username or password if the target script needs authentication.
In short, $.post is a useful shortcut to use in the simpler situation, while $.ajax offers full control on the request.
Here's the thing, I have a jquery click event handler, that calls a post on click.
The type that it expects (4th parameter of $.post()) is "json". However, on the
server side; there are two responses to the post: it's either json or html response. The problem is, if it returns html, the callback function isn't called (because the $.post expects a json?).
How can I react to this? I want something that if the server side script returns a json, execute callback, otherwise do another. Is that possible? Can I check the response type with $.post?
You'll most likely want to use the generic jquery.ajax function. In particular the dataType: 'text' property should allow you to parse your return value in whatever method works for you. You can also use the parseJSON function
$.ajax({
url: 'url',
type: 'post'
dataType: 'text',
success: function(text) {
if (json) {
var obj = $.parseJSON(text);
} else {
var html = $(text);
}
}
});