calling method in javascript, but error throws? - javascript

I need to call ajax method couple of places. So want to try to minimize the code by creating separate method for it. If use directly, it works perfect. but when I separate it won't work.
data: columns[5],
type: 'autocomplete',
options: { items: 100 },
source: function (query, process) {
$.ajax({
url: "/EditInitiatives.svc/GetLocationData?clientId=" + $value.val(),
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: {
query: query
},
success: function (response) {
process(response.d);
}
});
},
strict: true
}
it doesn't work, if I call this way. It says Microsoft JScript runtime error: 'query' is undefined, how to fix it?
{
data: columns[4],
type: 'autocomplete',
options: { items: 100 },
source: callAutoCompleteAjaxMethod(query, process, "/EditInitiatives.svc/GetLocationData?clientId=" + $value.val()),
strict: true
},
callAutoCompleteAjaxMethod = function (query, process, url) {
$.ajax({
url:url,
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: {
query: query
},
success: function (response) {
process(response.d);
}
});
},

You call
source: callAutoCompleteAjaxMethod(query, ...
But you never gave 'query' a value, give it a value and it will work.

You are calling the function instead of assigning it to the source property. And at this moment the variable query is not defined.
You have to assign a function, so that the plugin can call it later:
source: function (query, process) {
callAutoCompleteAjaxMethod(
query,
process,
"/EditInitiatives.svc/GetLocationData?clientId=" + $value.val()
);
}
(I hope $value is defined somewhere)
Parenthesis ( () ) after a function reference always calls the function immediately. If you want to pass a reference to the function, you don't put parenthesis after it.

Related

AutoComplete inside keyup jquery weird behaviour

I've a conditional ajax function call. On receiving response, data is binded to the autocomplete. The problem is that, on entering first key, Autocomplete list doesn't shows up even though it has values binded to it. The list shows up only after entering the subsequent letter(s).
$("#AutoComplete").on('keyup', function (event)
{
if ($("#AutoComplete").val().length <= 5 )
{
GetData();
}
});
function GetData()
{
$.ajax({
type: "POST",
url: "../Controller/function",
contentType: "application/json; charset=utf-8",
data: '{"key":"' + $("#AutoComplete").val() + '"}',
dataType: "json",
success: function (data)
{
var output= $.map(data, function (item)
{
return {
label: item.Name,
value: item.ID
};
});
$("#AutoComplete").autocomplete({
source: output,
autoFocus: true,
});
}
});
}
Consider the following example.
$("#AutoComplete").autocomplete({
source: function(req, resp) {
if (req.term.length <= 5) {
$.ajax({
type: "POST",
url: "../Controller/function",
contentType: "application/json; charset=utf-8",
data: {
key: req.term
},
dataType: "json",
success: function(data) {
var output = $.map(data, function(item) {
return {
label: item.Name,
value: item.ID
};
});
resp(output);
}
});
}
},
autoFocus: true,
});
You can use a Function for the Source:
Function: The third variation, a callback, provides the most flexibility and can be used to connect any data source to Autocomplete, including JSONP. The callback gets two arguments:
A request object, with a single term property, which refers to the value currently in the text input. For example, if the user enters "new yo" in a city field, the Autocomplete term will equal "new yo".
A response callback, which expects a single argument: the data to suggest to the user. This data should be filtered based on the provided term, and can be in any of the formats described above for simple local data. It's important when providing a custom source callback to handle errors during the request. You must always call the response callback even if you encounter an error. This ensures that the widget always has the correct state.
https://api.jqueryui.com/autocomplete/#option-source

IE 9, 10, 11 - Ajax calls not returning

I am having an issue with IE related to jQuery and ajax. Chrome and Firefox work just fine, but my ajax calls are disappearing in IE.
After making the ajax call, neither the success nor the fail functions are being called. I can see the response in the IE console, and I know my controller action is being hit.
$.ajax({
url: controllerUrl
type: 'POST',
dataType: 'json',
cache: false,
data: {
id: customerId
},
success: function () {
alert('success!');
},
error: function () {
alert('failed!');
}
});
Has anyone else seen this issue?
fail: function () {
alert('failed!');
}
fail is not a valid jQuery ajax setting. I believe you are looking for error.
Also, cache: false, does nothing with POST requests.
Note, jQuery does not append the time stamp with POST requests.
The source code clearly demonstrates this. (summarized from https://github.com/jquery/jquery/blob/master/src/ajax.js)
var rnoContent = /^(?:GET|HEAD)$/;
s.hasContent = !rnoContent.test( s.type );
if ( !s.hasContent ) {
/* code to append time stamp */
}
You are missing a comma , after your URL parameter:
$.ajax({
url: controllerUrl, // <--- you were missing this comma!
type: 'POST',
dataType: 'json',
cache: false,
data: {
id: customerId
},
success: function () {
alert('success!');
},
error: function () {
alert('failed!');
}
});

How to call json object from AJAX?

Here is my script:
$.ajax({
type: "Get",
url: "Sample.js",
datatype: 'json',
data: JSON.stringify({ key:key }),
success: function (data) {
var sample = data.name;
$("#html").html(sample);
},
error: function () {
alert("Error");
}
});
This is my Sample.js file:
{ "name": "user" }
When I run this code I get a blank screen. This is my script using getJSON():
$.getJSON("Sample.js", function (data) {
var sample = data.name;
$("#html").html(sample);
})
This produces "user" perfectly. What is the problem with $.ajax code?
In the getJSON version your don't send any data. Could this be the reason why that works? To me it looks like this could be sth. on the server side that delivers an empty JSON object when you pass the key parameter.
As the jQuery documentation states:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
Try modifying the dataType param.
change your datatype to dataType. Its case sensitive. Refer http://api.jquery.com/jQuery.getJSON/
Remove JSON.Stringify and change Get to GET
$.ajax(
{ type: "GET",
url: "Sample.js",
dataType: "json",
data: {key:key },
success: function (data)
{ var sample = data.name; $("#html").html(sample); },
error: function () { alert("Error"); }}
);

Event Handlers in a JavaScript "class"

I am working at fully understanding class definitions in JavaScript. Currently, I have a class defined like the following:
function Item() { this.init(); }
Item.prototype = {
init: function () {
this.data = {
id: 0,
name: "",
description: ""
}
},
save: function() {
$.ajax({
url: getUrl(),
type: "POST",
data: JSON.stringify(this.data),
contentType: "application/json",
success: save_Succeeded,
error: save_Failed
});
}
}
My problem is, I'm not sure how, or where, to define my save_Succeeded and save_Failed event handlers. Can someone please help me out? Thank you!
Add a context: to your $.ajax call pointing to this so that the correct object is passed as this when the handlers are called.
Something like:
save: function() {
$.ajax({
context: this,
url: getUrl(),
type: "POST",
data: JSON.stringify(this.data),
contentType: "application/json",
success: this.save_Succeeded,
error: this.save_Failed
});
(assuming that you also put save_Succeeded and save_Failed into the prototype)
}

"undefined" for alerting an ajax call response , why?

i am trying to alert the return value captured by the ajax request. The web method it is refering is returning a boolean value of true or false, and when i am trying to access it outside the ajax method it gives a message "undefined" :?
<script type="text/javascript" language="javascript">
$(document).ready(function () {
var authInfo;
$.ajax({
type: "POST",
url: "service.asmx/getAuthInfo",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
authInfo = msg.d;
},
});
alert(authInfo);
});
</script>
why is the alert(authInfo) giving me as "undefined" ?? Please help !
where does this piece of code fit on the above context ?
if(auhthInfo){
$(".ansitem").editable('FetchUpdate.aspx', {
style: 'background-color:inherit;',
type: 'textarea',
indicator: '<img src="spinner.gif">',
event: 'dblclick',
onblur: 'submit',
submitdata: function (value, settings) {
return { orgval: value};
},
});
};
Your "$.ajax()" call is asynchronous, and thus the results are not available until the response is returned from the server.
If you put your "alert()" inside the "success" callback, it should work (if the HTTP transaction works).
EDITED TO HANDLE YOUR NEW CODE:
<script type="text/javascript" language="javascript">
$(document).ready(function () {
var authInfo;
$.ajax({
type: "POST",
url: "service.asmx/getAuthInfo",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// alert(msg.d); // here it will work as it is only called when it succeeds.
MyHanlder(msg);
},
});
// alert(authInfo); // here authinfo has no value as the AJAX call may not have returned.
});
function MyHandler(msg) {
if(msg.d){
$(".ansitem").editable('FetchUpdate.aspx', {
style: 'background-color:inherit;',
type: 'textarea',
indicator: '<img src="spinner.gif">',
event: 'dblclick',
onblur: 'submit',
submitdata: function (value, settings) { return { orgval: value}; },
});
};
}
</script>
The request and the response that you get via ajax calls are asynchronous. I think it is not possible to alert the value that you get in response at the end of ready function because you are not assured that you will be getting your response before the function completes execution.
You are alerting the authInfo variable before the actual ajax call have returned. If you try this:
success:function(msg) {
authInfo = msg.d;
alert(authInfo);
}
I think you will get the correct result.
Because the AJAX call is done asynchronously, the alert does not have the value at the time of execution. If you place the alert inside the success function you should see the appropriate results. I also noticed you have an extra comma in the $.ajax parameters after the success function parameter.
It appears:
alert(authInfo);
Is running immediately when your document is ready.
However, the variable is not being initialized until after the AJAX call completes.
Try moving the alert to:
$.ajax({
type: "POST",
url: "service.asmx/getAuthInfo",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
authInfo = msg.d;
alert(authInfo);
},
});
If you need to do anything more complex with the value, you can try re-factoring the code into another function:
function onSuccess(msg)
{
if(msg.d)
{
window.alert('The value is true!');
}
else
{
window.alert('The value is false!')
}
}
$.ajax({
type: "POST",
url: "service.asmx/getAuthInfo",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: onSuccess,
});

Categories