jQuery.ajax converter not called - javascript

I'm having trouble with jQuery.ajax converters - I can't get my converter to be called.
I've got this jQuery AJAX code (simplified for the question) :
$.ajax({
url: "http://myurl/myservice",
dataType: "JSONP",
cache: false,
success: function (data, textStatus, jqXHR) { /* do stuff */ },
error: function (jqXHR, textStatus, errorThrown) { /* do stuff */ },
timeout: 5000,
converters: { "JSONP": myConversionFunction }
});
When I use this code, the converter function myConversionFunction isn't being called. I want to use the converter to convert dates in the response as show in other SO questions but just can't get it firing.
Using fiddler I've checked the response and it is JSONP, with content type "application/x-javascript".
Any ideas what I'm doing wrong?
Thanks,
Chris.

I think you can't overwrite jQuery's default converters like json. Introduce your own converter instead (and include text in your specifier, as in this case it's a conversion from text to your output):
$.ajax({
url: "http://myurl/myservice",
dataType: "jsonp myConversion",
cache: false,
success: function (data, textStatus, jqXHR) { /* do stuff */ },
error: function (jqXHR, textStatus, errorThrown) { /* do stuff */ },
timeout: 5000,
converters: {
"text myConversion": function(value) {
console.log("pre-processing...");
/* do stuff */
return value;
}
}
});
​

I use code like this to manage the 'd' data of asp.net:
$.ajaxSetup({
data: "{}",
dataType: "jsonp",
type: "POST",
contentType: "application/json",
converters:
{
"json jsonp": function(msg)
{
return msg.hasOwnProperty('d') ? msg.d : msg;
}
},
error: function(xhr, textStatus, errorThrown)
{
var errorMessage = "Ajax error: " + this.url + " : " + textStatus + " : " + errorThrown + " : " + xhr.statusText +
" : " + xhr.status;
if (xhr.status != "0" || errorThrown != "abort")
{
alert(errorMessage);
}
}
});
perhaps you need to make it lower case like:
converters:
{
"json jsonp": function(msg)
{
return yourfunction(msg);
}
}

Related

executing function after function with ajax call has completed

I want to know which way is the best way to execute a function when a function with the ajax call has completed.
My code:
jQuery.when(AjaxCallToBokningar()).done(function () {
console.log("AjaxCallComplete");
});
function AjaxCallToBokningar() {
var url = `${_spPageContextInfo.webAbsoluteUrl}/_api/web/lists/getbytitle('Bokningar')/items
var call = jQuery.ajax({
url: url,
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
});
//Done
call.done(function (data, textStatus, jqXHR) {
//Filling globalArray
window.globalBokningsArray = data.d.results;
});
//Fail
call.fail(function (jqXHR, textStatus, errorThrown) {
console.log('Loading Bokningar content faild: ' + textStatus + jqXHR.responseText);
});
}
Am I on the right track or is there a better way?
If you want to be able to make the Ajax call and then call a function when it's complete you can use a function reference as a parameter and do it like this...
function AjaxCallToBokningar(doneCallback) {
var url = `${_spPageContextInfo.webAbsoluteUrl}/_api/web/lists/getbytitle('Bokningar')/items
var call = jQuery.ajax({
url: url,
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
});
//Done
call.done(function (data, textStatus, jqXHR) {
//Filling globalArray
window.globalBokningsArray = data.d.results;
doneCallback();
});
//Fail
call.fail(function (jqXHR, textStatus, errorThrown) {
console.log('Loading Bokningar content faild: ' + textStatus + jqXHR.responseText);
});
}
Then you can call it like this...
function ajaxCallComplete1() {
// this is executed after the 1st call is done - do something here
}
function ajaxCallComplete2() {
// this is executed after the 2nd call is done - do something here
}
AjaxCallToBokningar(ajaxCallComplete1);
AjaxCallToBokningar(ajaxCallComplete2);
or...
AjaxCallToBokningar(function() {
// this is executed after the call is done - do something here
});
You can also try something like this: (not tested)
function ajaxCallToBokningar() {
var url = `${_spPageContextInfo.webAbsoluteUrl}/_api/web/lists/getbytitle('Bokningar')/items`;
var options = {
url: url,
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
};
return jQuery.ajax(options);
}
function updateBoknigarArray(data) {
window.globalBokningsArray = data.d.results;
}
function showError(jqXHR, textStatus, errorThrown) {
console.log('Loading Bokningar content faild: ' + textStatus + jqXHR.responseText);
}
ajaxCallToBoknigar()
.done(updateBoknigarArray)
.fail(showError)

c# - Problems during AJAX call with Jquery

Good evening,
I'm trying to do a AJAX call in a C# page and I'm dealing with some problems.
My jQuery code is:
$(document).ready(function () {
$.ajax({
type: "POST",
url: "conteudo.aspx/GetNewPost",
data: { ids: "<%=Request.QueryString["idconteudo"]%>" },
contentType: 'application/json; charset=utf-8',
dataType: 'json',
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function (data) {
alert("ok");
}
});
});
And my code-behind is:
[WebMethod]
public static string GetNewPost(string ids)
{
// some code
return ids;
}
Does someone know what is going on?
PS: The error is Internal Server Error.
Please use code as below
Because you are using text data type from query string, you can make datatype as text
$(document)
.ready(function () {
var q = "<%=Request.QueryString["idconteudo"]%>";
alert(q);// just to check the value
// assuming that you had passed query string value
$.ajax({
type: "POST",
url: "conteudo.aspx/GetNewPost",
data: { "ids": q },
//contentType: 'application/json; charset=utf-8',
dataType: 'text',// data type should be text
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " +
XMLHttpRequest.toString() +
"\n\nStatus: " +
textStatus +
"\n\nError: " +
errorThrown);
},
success: function(data) {
alert("ok");
}
});
});
Edit 1 : If the Web Method is on ASPX page, you shall use below code, so that you get result in Json format
$(document)
.ready(function () {
var q = "<%=Request.QueryString["idconteudo"]%>";
//alert(q);
// just to check the value
// assuming that you had passed query string value
$.ajax({
type: "POST",
url: "conteudo.aspx/GetNewPost",
data: '{ids: "' + q + '" }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " +
XMLHttpRequest.toString() +
"\n\nStatus: " +
textStatus +
"\n\nError: " +
errorThrown);
},
success: function (result) {
alert("ok" + result.d);
}
});
});
try:
var idconteudo = "<%=Request.QueryString["idconteudo"]%>";
...
...
url: "conteudo.aspx/GetNewPost",
data: "{ids: \"" + idconteudo + "\"" }",
contentType: 'application/json; charset=utf-8',
...
...
From what you have given us with your post, I see two things that are incorrect and one other thing that may have just not been posted in your question, but it is in fact in your real source.
1) Your data is written wrong. It should be:
$(document).ready(function () {
var test = "<%=Request.QueryString["idconteudo"]%>";
$.ajax({
type: "POST",
url: "conteudo.aspx/GetNewPost",
data: { 'ids' : test }, // the ids needs to have quotes to be correct syntax
dataType: 'text',
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function (data) {
alert("ok");
}
});
});
2) You say it's a POST but your method isn't decorated with the [HttpPost] Annotation.
3) Your dataType is set to 'json' but your method is returning a string.. so 'json' should be changed to 'text'.
Hope this helps!

jQuery - failing to submit username password and causing 401 unauthorized

When i open using the Google chrome browser this url http://www.site.nl/a/b/c/d/e?niss=f, it first ask for username password:
Manually when i put the username password i get some data.
Now, using jQuery how can i submit that username password? following is not working, always after submit its failing with "401 unauthorized"
$(document).ready(function() {
$.ajax({
type: "GET",
url: "http://www.site.nl/a/b/c/d/e?niss=f",
dataType: 'json',
async: false,
headers: {
"Authorization": "Basic Username1:password1234"
},
data: '{ "test" }',
success: function (data, textStatus, jqXHR){
console.log(data, textStatus, jqXHR);
}
});
});
Please try following code
$(document).ready(function() {
$.ajax({
type: "GET",
url: "http://www.site.nl/a/b/c/d/e?niss=f",
dataType: 'json',
async: false,
data: '{ "test" }',
beforeSend: function(xhr)
{
xhr.setRequestHeader('Authorization', make_base_auth("Username1", "password1234"));
},
success: function (data, textStatus, jqXHR){
console.log(data, textStatus, jqXHR);
}
});
});
function make_base_auth(user,password)
{
var tok = user + ':' + password;
var hash = btoa(tok);
return "Basic " + hash;
} // ends

Ajax HTTP POST method fail on Firefox but work well on Safari and Others Browser

My app is based substantially on CRUD operations. All operation work great on Safari and other browsers, but not in Firefox. I can not understand what could be the problem. I'm new on js because I come from obj-c whose environment provides an excellent debugging. When i post data from a form to server, I get a 500 internal server error.
I looked for information everywhere, but the suggested solutions do not work for my case. Any help is largely appreciated.
My code:
function save() {
var url;
if (save_method == 'add') {
alert('Method Add');
var ids = $('input[name="id"]').val();
var disciplinaNome = $('[name="disciplinaNome"]').val();
console.log(ids + disciplinaNome);
url = "http://SERVER.me/Api/v5/create/discipline";
$.ajax({
url: url,
type: "POST",
data: "disciplinaNome=" + disciplinaNome,
contentType: "application/x-www-form-urlencoded",
success: function(responseData, textStatus, jqXHR) {
$('#modal_form').modal('hide');
alert("data saved")
console.log("Data: " + responseData + "\nStatus: " + textStatus);
//if success close modal and reload ajax table
$('#example').dataTable().fnClearTable();
$('#example').DataTable().ajax.reload();
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Error adding data');
}
});
} else {
url = "http://server/Api/v5/update/discipline";
alert('Method update');
}
$('[name="disciplinaNome"]').val());
var ids = $('input[name="id"]').val();
var disciplinaNome = $('[name="disciplinaNome"]').val();
console.log(ids + disciplinaNome);
var ajaxLock = 1;
// ajax adding data to database
$.ajax({
url: url,
type: "POST",
data: "id=" + ids + "&disciplinaNome=" + disciplinaNome,
contentType: "application/x-www-form-urlencoded",
success: function(responseData, textStatus, jqXHR) {
alert("data edited")
console.log("Data: " + responseData + "\nStatus: " + textStatus);
//if success close modal and reload ajax table
$('#modal_form').modal('hide');
$('#example').dataTable().fnClearTable();
$('#example').DataTable().ajax.reload();
// reload_table();
ajaxLock = 0;
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Error update data');
}
});
}
UPDATE with disciplinaNome

jquery autocomplete - save data to DB when list item is clicked (select event)

i've read a lot about jq autocomplete, but it seems, there is no way to make an ajax request while the select event is fired.
I will write the search query into an DB-Table only when the element is clicked.
Firebug shows the url in redGET http://server.ccc/api/my/logSearchQuery?a=searchquery&b=11&v=0
$(document).ready(function(e){
var results = [];
var _request = null;
$("#input").autocomplete({
source: function( request, response ) {
_request = request;
$.ajax({
url: "http://dataserver",
dataType: "jsonp",
jsonp: 'json.wrf',
data: {
q: GenerateSearchQuery(request.term)
},
success: function( data ) {
results = $.map(data.response.docs, function(item) {
return {
label: item.Name,
value: {
id:cid
}
};
});
response(results);
}
});
},
minLength: 3,
select: function( event, ui ) {
event.preventDefault();
// ---------------- here is what i've tried, but it fails----------------------
$.ajax({
url: "api/my/logSearchQuery",
type: "get",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: {"a": encodeURIComponent(_request.term), "b": results.length, "v": 0},
success: function(data){
console.log(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(XMLHttpRequest+ " : "+ errorThrown + " : " + textStatus);
}
});
if (ui.item.value != "searchAll") {
self.location = "/list/"+ui.item.value.id;
} else {
$('#searchForm').submit();
}
}
});});
The Ajax call works into the source event, but thats not the right place i think.
The ajax errors are empty.
Please help.
Yes, i am a beginner;-)
The problem was, that the code under the ajax call...
select: function( event, ui ) {
event.preventDefault();
// ---------------- here is what i've tried, but it fails----------------------
$.ajax({
url: "api/my/logSearchQuery",
type: "get",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: {"a": encodeURIComponent(_request.term), "b": results.length, "v": 0},
success: function(data){
console.log(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(XMLHttpRequest+ " : "+ errorThrown + " : " + textStatus);
}
});
//----------this part---------------
if (ui.item.value != "searchAll") {
self.location = "/list/"+ui.item.value.id;
} else {
$('#searchForm').submit();
}
}
gets fired during the ajax call is working (asynchronous).
So i've putted the this part into the complete: event of $.ajax
complete: function(xhr, status){
if (ui.item.value != "searchAll") {
self.location = "/some /"+ui.item.value.pflnr;
} else {
$('#seachBar_searchForm').submit();
}
}
now it works fine.

Categories