I'm getting data from a remote server, that can produce JSONP but needs the callback-function name in a non-standard way.
For code structure & simpler error-handling, I'd prefer to use the default function. Is there a way for me to get the autogenerated function name, and give that as a data-parameter?
What I'd like to be able to do is something in the lines of:
$.ajax("http://mydomain.com/xxx",
{
dataType: "jsonp",
type : 'GET',
success : function(response) {
doSomething(response);
},
data: {
format_options : 'callback:' + jQueryAutoGeneratedCallbackFunction,
outputFormat : 'json'
}
}
);
Is this possible?
..So it turns out I thinking it from a wrong angle.
The answer is, that I can change the "callback"-parameter like this.
$.ajax("http://mydomain.com/xxx",
{
dataType: "jsonp",
jsonp: "format_options",
jsonpCallback:"callback:myFunction",
type : "GET",
success : function(response) {
doSomething(response);
},
data: {
foo : "bar"
}
}
);
Just as clarification, the "callback:"-part in "callback:myFunction" is needed just for the API i'm using, I included it here as i'd included it in the question.
Related
I'm trying to fetch the data of a JSONP, but it returns a Syntax error when the function is called. I'm really new to this topic and don't understand why. Probably because I didn't understand everything of JSONP requests. It would be nice if someone could help me out.
Executed code:
$.ajax({
url: "https://backpack.tf/api/IGetMarketPrices/v1?format=json&callback=JSONP&key=XXX&appid=730",
dataType: "jsonp",
data: {format: "json"},
type: "GET",
jsonp: "response",
jsonpCallback: "response",
success: function( response ) {
console.log( response ); // server response
}
});
(I had to censor my API key.)
Error: Uncaught SyntaxError: Unexpected token :
The response is:
{"response":{"success":1,"current_time":1486000891,"items":{"AK-47 | Aquamarine Revenge (Battle-Scarred)":{"last_updated":1485997229,"quantity":80,"value":1092},...
The first : is underlined by Chrome.
Here is the API documentation.
From trial and error - impressive as I have no API key
$.ajax({
url: "https://backpack.tf/api/IGetMarketPrices/v1?format=jsonp&key=XXX&appid=730",
dataType: "jsonp",
type: "GET",
success: function( response ) {
console.log( response ); // server response
}
});
or
$.ajax({
url: "https://backpack.tf/api/IGetMarketPrices/v1",
dataType: "jsonp",
type: "GET",
data: {
format: 'jsonp',
key: 'XXX',
appid: 730
},
success: function( response ) {
console.log( response ); // server response
}
});
To explain... jQuery automatically adds a query parameter called callback on jsonp requests... as the API states that you need to define the callback name in a parameter called callback, you can let jQuery use the default value of callback
Then, jQuery creates a function with a long random name, and sets the value of the callback parameter to that function - so you don't have to worry about the jsonp or jsonpCallback parameters - defaults are good
I must be missing something basic, because this should work!
I'm sending from view using jQuery to MVC post action
function DoSomething(passedId) {
$.ajax({
method: "POST",
dataType: 'text',
url: '/MyController/SomeAction/',
data: { id: passedId}
}).done(function (data) {
//
});
}
And inside MyController
[HttpPost]
public ActionResult SomeAction(int id)
{
...
}
In Firebug console I'm getting 404 error.
You didn't said which version of jquery you are using. Please check jquery version and in case that this version is < 1.9.0 you should instead of
method: "POST"
use
type: "POST"
this is an alias for method, and according to jquery official documentation you should use type if you're using versions of jQuery prior to 1.9.0.
function DoSomething(passedId) {
$.ajax({
type: "POST",
dataType: 'text',
url: '/MyController/SomeAction/',
data: { id: passedId}
}).done(function (data) {
...
});
}
Tested above code and it works (each request enter inside mvc controller http post SomeAction action).
In the RFC 2616 the code 404 indicates that the server has not found anything matching the Request-URI.
So you need to look at your URL parameter.
Try the MVC conventional call using :
url: '#Url.Action("SomeAction", "MyController")',
To resolve the 404 issue:
There are a few options to resolve this. You controller/action cannot be find the way it is describe.
-If you are in a view that is in the controller for which the action your are trying to call is located, then:
url: 'SomeAction',
-If you are trying to call an action from another controller, OtherController, for example, then:
url: 'Other/SomeAction',
-To add to another answer, if you are calling your ajax inside the view (and NOT in a javascript file) then you can also use (for a controller called SomeController):
url: '#Url.Action("SomeAction", "Some")',
Additional Items Of Note:
You do not specify a content type for json (contentType indicates what you are sending):
contentType: "application/json; charset=utf-8",
I can't tell, based on your action if you are expecting 'text' or something else. However, unless expecting 'json', I would remove the data part.
You need to stringify your data
JSON.stringify(data: { id: passedId}),
In the end, I would expect it to look something like:
function DoSomething(passedId) {
var url = "SomeAction"; //if action is in OtherController then: "Other/SomeAction"
$.ajax({
method: "POST",
url: url,
data: JSON.stringify({ id: passedId}),
contentType: "application/json; charset=utf-8"
}).done(function (data) {
//
});
}
The slash at the beginning of this designates an absolute path, not a relative one.
/MyController/SomeAction/
You should include a URL or relative path.. maybe
'MyController/SomeAction/ajax.php'
or the full URL
'http://example.com/myajaxcontroller/someaction/ajax.php'
or stolen from the other guys answer
url: '#Url.Action("SomeAction", "MyController")',
To address others on here, I don't think the datatype is the
problem... OP says "I'm getting 404 error."
contentType is the type of data you're sending, so
application/json; charset=utf-8 is a common one, as is
application/x-www-form-urlencoded; charset=UTF-8, which is the
default.
dataType is what you're expecting back from the server: json, html,
text, etc. jQuery will use this to figure out how to populate the success function's parameter.
Write the code this way:
function DoSomething(passedId) {
$.ajax({
url: 'yourController/SomeAction',
type: 'POST',
data: { id: passedId},
dataType: 'json',
error: function (ex) {alert(ex.responseText)},
success: function (data)
{
if (data.Results != null) {
//use the return values
});
}
}
});
}
and the controller
public JsonResult SomeAction(int id)
{
try
{
return Json(new { Results = "Text To return or send some object or an list, etc"}, JsonRequestBehavior.AllowGet);
}
catch (Exception)
{
throw;
}
}
Finally, check that the controller has its respective view. :)
and and the library of "jQuery" updated.
just in case.
use the following ajax call
var datum = { id: passedId };
$.ajax({
url: url, // your url
type: 'POST',
data: JSON.stringify(datum),
contentType: 'application/json; charset=utf-8',
beforeSend: function () {
},
complete: function () {
},
success: function (user, status, XHR) {
},
error: function (req, status, error) {
}
});
UpDated
public ActionResult SomeAction(int id){} should accept string parameter instead of int
I've been stuck from this issue in couple of days. I want to send some headers data in jQuery.load(). It seems that jQuery.load never send the headers, like ajax. Can somebody explain how to, or Is it necessary? Btw, sory my bad English.
This is the syntax :
$loadingBay.load(href, settings.data, function (data, status) {
prep(status === 'error' ? $tag(div, 'Error').html(settings.xhrError) : $(this).contents());
});
Many Thanks
You can not pass headers data to $.load() , but you can set default setup using $.ajaxSetup() like this :
$.ajaxSetup({
'headers':{
'header1':'value1',
'header2':'value2',
}
}
);
//give the load call here
$('selector').load('url',function(){
//do things
})
Disclaimer From jquery doc:
Its use is not recommended.
The best way is do the is thing using $.ajax() :
$.ajax({
url: "test.html",
headers : {header1 : "header1"}
}).done(function(data) {
$('selector').html(data);
});
You can use beforeSend option in jquery ajax , like as follows :
$.ajax({
url: "http://localhost/restTest",
data: { uname: "asdf" },
type: "GET",
beforeSend: function(xhr){xhr.setRequestHeader('X-TOKEN', 'xxxxx');},
success: function() { alert('Success!' + authHeader); }
});
or can also use headers like,
$.ajax({
url: "http://localhost/restTest",
data: { uname: "asdf" },
type: "GET",
headers:{ "X-TOKEN": 'xxxxx'},
success: function() { alert('Success!' + authHeader); }
});
let me start with some code:
function sendAjax(data, type)
{
$.ajax({
type : "GET",
dataType : "jsonp",
url : rest + type,
data : data,
});
}
$.when(sendAjax(someData, 'url')).then(function(data){
console.log(data); //undefined
});
$.when(sendAjax(someOtherData, 'url')).then(function(data){
console.log(data); //undefined
});
the issue i'm having is that data comes in as undefined
if i use success in the $.ajax the data comes in fine
The main idea here is that i should write the sendAjax() method once and use it through the application, but i don't think i set it up properly
ant ideas?
You need to return the promise return by $.ajax() from sendAjax
function sendAjax(data, type)
{
return $.ajax({
type : "GET",
dataType : "jsonp",
url : rest + type,
data : data,
});
}
How should I be passing query string values in a jQuery Ajax request? I currently do them as follows but I'm sure there is a cleaner way that does not require me to encode manually.
$.ajax({
url: "ajax.aspx?ajaxid=4&UserID=" + UserID + "&EmailAddress=" + encodeURIComponent(EmailAddress),
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
I’ve seen examples where query string parameters are passed as an array but these examples I've seen don't use the $.ajax() model, instead they go straight to $.get(). For example:
$.get("ajax.aspx", { UserID: UserID , EmailAddress: EmailAddress } );
I prefer to use the $.ajax() format as it's what I’m used to (no particularly good reason - just a personal preference).
Edit 09/04/2013:
After my question was closed (as "Too Localised") i found a related (identical) question - with 3 upvotes no-less (My bad for not finding it in the first place):
Using jquery to make a POST, how to properly supply 'data' parameter?
This answered my question perfectly, I found that doing it this way is much easier to read & I don't need to manually use encodeURIComponent() in the URL or the DATA values (which is what i found unclear in bipen's answer). This is because the data value is encoded automatically via $.param()). Just in case this can be of use to anyone else, this is the example I went with:
$.ajax({
url: "ajax.aspx?ajaxid=4",
data: {
"VarA": VarA,
"VarB": VarB,
"VarC": VarC
},
cache: false,
type: "POST",
success: function(response) {
},
error: function(xhr) {
}
});
Use data option of ajax. You can send data object to server by data option in ajax and the type which defines how you are sending it (either POST or GET). The default type is GET method
Try this
$.ajax({
url: "ajax.aspx",
type: "get", //send it through get method
data: {
ajaxid: 4,
UserID: UserID,
EmailAddress: EmailAddress
},
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
And you can get the data by (if you are using PHP)
$_GET['ajaxid'] //gives 4
$_GET['UserID'] //gives you the sent userid
In aspx, I believe it is (might be wrong)
Request.QueryString["ajaxid"].ToString();
Put your params in the data part of the ajax call. See the docs. Like so:
$.ajax({
url: "/TestPage.aspx",
data: {"first": "Manu","Last":"Sharma"},
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
Here is the syntax using jQuery $.get
$.get(url, data, successCallback, datatype)
So in your case, that would equate to,
var url = 'ajax.asp';
var data = { ajaxid: 4, UserID: UserID, EmailAddress: EmailAddress };
var datatype = 'jsonp';
function success(response) {
// do something here
}
$.get('ajax.aspx', data, success, datatype)
Note
$.get does not give you the opportunity to set an error handler. But there are several ways to do it either using $.ajaxSetup(), $.ajaxError() or chaining a .fail on your $.get like below
$.get(url, data, success, datatype)
.fail(function(){
})
The reason for setting the datatype as 'jsonp' is due to browser same origin policy issues, but if you are making the request on the same domain where your javascript is hosted, you should be fine with datatype set to json.
If you don't want to use the jquery $.get then see the docs for $.ajax which allows room for more flexibility
Try adding this:
$.ajax({
url: "ajax.aspx",
type:'get',
data: {ajaxid:4, UserID: UserID , EmailAddress: encodeURIComponent(EmailAddress)},
dataType: 'json',
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
Depends on what datatype is expected, you can assign html, json, script, xml
Had the same problem where I specified data but the browser was sending requests to URL ending with [Object object].
You should have processData set to true.
processData: true, // You should comment this out if is false or set to true
The data property allows you to send in a string. On your server side code, accept it as a string argument name "myVar" and then you can parse it out.
$.ajax({
url: "ajax.aspx",
data: [myVar = {id: 4, email: 'emailaddress', myArray: [1, 2, 3]}];
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
You can use the $.ajax(), and if you don't want to put the parameters directly into the URL, use the data:. That's appended to the URL
Source: http://api.jquery.com/jQuery.ajax/
The data parameter of ajax method allows you send data to server side.On server side you can request the data.See the code
var id=5;
$.ajax({
type: "get",
url: "url of server side script",
data:{id:id},
success: function(res){
console.log(res);
},
error:function(error)
{
console.log(error);
}
});
At server side receive it using $_GET variable.
$_GET['id'];