Get ID of element in jQuery autocomplete source function - javascript

I have a webservice method that takes the id of an element to determine the source for autocompletes.
In a nutshell, I'm doing this:
$("input[type='text']").autocomplete({
source: function(request, response) {
var id = $(this).attr('id');
var params = {'id': id, 'term': request.term};
var jsonParams = JSON.stringify(params);
$.ajax({
type: "POST",
url: "Page.aspx/GetAutoCompleteList",
data: jsonParams,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
response(JSON.parse(msg.d));
},
error: function() {
response([]);
}
});
}
});
But id isn't referring to the original selector.
What can I do to get the id of the selected input element? Or what is a better strategy for this?

You'd need to maintain a context of each input element, something like this:
$("input[type='text']").each(function (i, ele) {
ele = $(ele);
ele.autocomplete({
source: function (request, response) {
var id = ele.attr('id');
var params = {'id': id, 'term': request.term};
var jsonParams = JSON.stringify(params);
$.ajax({
type: "POST",
url: "Page.aspx/GetAutoCompleteList",
data: jsonParams,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// ...
},
error: function () {
// ...
},
async: false
});
}
});
});

Try
$(this.element).prop("id");
this.element[0].id;
$(this.element.get(0)).attr('id');
JSFIDDLE
$("input[type='text']").autocomplete({
source: function(request, response) {
var id = $(this.element).prop("id");
var id2=this.element[0].id;
var id3=$(this.element.get(0)).attr('id');
console.log(id);
console.log(id2);
console.log(id3);
var params = {'id': id, 'term': request.term};
var jsonParams = JSON.stringify(params);
$.ajax({
type: "POST",
url: "Page.aspx/GetAutoCompleteList",
data: jsonParams,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
response(JSON.parse(msg.d));
},
error: function() {
response([]);
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<input type="text" id="asd"></input>

Related

jQuery Ajax get value via function?

I have created a save(id) function that will submit ajax post request. When calling a save(id). How to get value/data from save(id) before going to next step. How to solve this?
For example:
function save(id) {
$.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success: function (data) {
return data;
},
error: function (error) {
return data;
}
});
}
Usage:
$('.btn-create').click(function () {
var id = 123;
data = saveArea(id); //get data from ajax request or error data?
if (data) {
window.location = "/post/" + data.something
}
}
You have two options, either run the AJAX call synchronously (not recommended). Or asynchronously using callbacks
Synchronous
As #Drew_Kennedy mentions, this will freeze the page until it's finished, degrading the user experience.
function save(id) {
return $.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
async: false,
data: JSON.stringify({
id: id,
})
}).responseText;
}
$('.btn-create').click(function () {
var id = 123;
// now this will work
data = save(id);
if (data) {
window.location = "/post/" + data.something
}
}
Asynchronous (recommended)
This will run in the background, and allow for normal user interaction on the page.
function save(id, cb, err) {
$.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success: function (data) {
cb(data);
},
error: err // you can do the same for success/cb: "success: cb"
});
}
$('.btn-create').click(function () {
var id = 123;
save(id,
// what to do on success
function(data) {
// data is available here in the callback
if (data) {
window.location = "/post/" + data.something
}
},
// what to do on failure
function(data) {
alert(data);
}
});
}
Just make things a bit simpler.
For starters just add window.location = "/post/" + data.something to the success callback.
Like this:
function save(id) {
return $.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success:function(data){
window.location = "/post/" + data.something
}
}).responseText;
}
Or by adding all your Ajax code within the click event.
$('.btn-create').click(function () {
var id = "123";
$.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success: function (data) {
window.location = "/post/" + data.something
},
error: function (error) {
console.log(error)
}
});
}

Looping through two JSON arrays Ajax

I'm trying to get data from a Json file using the id from a previous previous ajax call looping through the the second array based on the id gotten from the first
I have tried
$(document).on('click', '.stories', function(e) {
e.preventDefault();
var request = $.ajax({
url: 'includes/functions.php?job=front_title',
cache: false,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
type: 'get'
});
request.done(function (output) {
if (output.result === 'success') {
var n = output.data[0].title_count;
$('.blog').empty();
for (var i=0; i<n; i++) {
var storytitle = output.data[i].story_view;
var id = output.data[i].titleID;
var request2 = $.ajax({
url: 'includes/functions.php?job=story_episodes',
cache: false,
data: 'id=' + id,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
type: 'get'
});
request2.done(function (output2) {
if (output2.result === 'success') {
var n2 = output2.data[0].episode_count;
for (var i=0; i<n2; i++) {
var titles = output2.data[i].title;
console.log(storytitle + " " + titles);
}
}
else {
console.log('faileds');
}
});
}
} else {
console.log('failed');
}
});
});
The storyTitle has a single value and loops through all the titles when i check my console.
I tried debugging and found out the second for-loop was only executed once, after executing request2.done, it goes back to the first for-loop after the first has finish all its loop, it executes the second for-loop.
I don't know where am missing it.I need help with this.
Finally solved the problem...Changed my code to...
$(document).on('click', '.stories', function(e) {
e.preventDefault();
var request = $.ajax({
url: 'includes/functions.php?job=front_title',
cache: false,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
type: 'get'
});
request.done(function (output) {
if (output.result === 'success') {
var n = output.data[0].title_count;
var jsonArray = $(jQuery.parseJSON(JSON.stringify(output.data))).each(function() {
var id = this.titleID;
var CLASS = this.story_view;
var request2 = $.ajax({
url: 'includes/functions.php?job=story_episodes',
cache: false,
data: 'id=' + id,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
type: 'get'
});
request2.done(function (output2) {
if (output2.result === 'success') {
var jsonArray2 = $(jQuery.parseJSON(JSON.stringify(output2.data))).each(function() {
var id2 = this.id;
console.log(id + " " + id2);
})
}
})
})
} else {
console.log('failed');
}
});
})
And it worked fine....thanks to Swapnil Godambe

How to address data from external url?

Now I have that code:
$(document).ready(function() {
$.ajax({
type: "POST",
url: "http://steamcommunity.com/market/priceoverview/?currency=3&appid=730&market_hash_name=StatTrak%E2%84%A2%20P250%20%7C%20Steel%20Disruption%20%28Factory%20New%29",
data: {},
dataType: "jsonp",
crossDomain: true,
success: function(data) {
console.log(data)
} });
});
and get this error:
Uncaught SyntaxError: Unexpected token :
I can see the right response from the url in my console and tried different dataTypes. What could be wrong?
Please try this. On my end this works.
$.ajax({
type: "POST",
url: "http://steamcommunity.com/market/priceoverview/?currency=3&appid=730&market_hash_name=StatTrak%E2%84%A2%20P250%20%7C%20Steel%20Disruption%20%28Factory%20New%29",
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
// an example of using result
var myVar1 = result.lowest_price;
var myVar2 = result.median_price;
var myVar3 = result.success;
var myVar4 = result.volume;
alert(result.success);
},
error: function (result) {
},
fail: function (arg1, arg2, arg3) {
}
});

Can I use jquery's .done() more than once?

I have 2 JS literals:
var obj1 = {
Add: function (id) {
$.ajax({
type: "POST",
data: JSON.stringify({
"id": id
}),
url: "Page.aspx/add",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
return jQuery.parseJSON(data.d || "null");
}
});
}
};
var obj2 = {
List: function (id) {
$.ajax({
type: "POST",
data: JSON.stringify({
"id": id
}),
url: "Page.aspx/list",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
return jQuery.parseJSON(data.d || "null");
}
});
}
};
And this is my document.ready:
$(document).ready(function () {
obj1.Add(1).done(function (data) {
alert('you added ' + data);
});
obj2.List().done(function (data) {
$.each(jQuery.parseJSON(data), function (i, item) {
// fill a combo box
});
});
});
jQuery just executes the first call and obj2.List() ain't called at all.
How to properly use the deffered objects in this case?
Change your Add and List function to RETURN the ajax object.
Add: function (id) {
return $.ajax({..
and
List: function (id) {
return $.ajax({...
This way - it will return the jqXHR obj which will return the deferred object.
This implement the Promise interface which has : the callbacks you are looking for.
edit :
look at this simple example which does work :
var obj1 = {
Add: function (id) {
return $.ajax({
type: "get",
data: JSON.stringify({
"id": 1
}),
url: "http://jsbin.com/AxisAmi/1/quiet",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("at success --"+data.data)
}
});
}
};
obj1.Add(2).done(function (a){alert("at done --"+a.data);});

Dynamically get URL for JQuery Ajax request from Data Attribute

I have a JQuery Autocomplete function that I need to be able to pass a url into. I'm trying to pull the url from the html data-url attribute, however I'm currently getting a variable is undefined message in the JavaScript console, so I know I'm not getting the values I expect. I've included my code below. Any help would be greatly appreciated.
JQuery Function:
$(function () {
$(".autocomplete").autocomplete({
delay: 0,
source: function (request, response) {
var baseURL = $(this).data("url");
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: baseURL + request.term,
dataType: "json",
success: function (data) {
response(data)
}
});
},
minLength: 1,
});
HTML Element:
<td style="width: 90%">
<label for="tag_Name" class="inline">Server Tags: </label>
<input class="fixed autocomplete" type="text" id="tag_Name" placeholder="Type tags to add..." data-url="/RequestFieldValues/GetLikeResourceTags/?prefix=" />
</td>
Try this instead...
$(function () {
$(".autocomplete").each(function() {
var baseURL = $(this).data("url");
$(this).autocomplete({
delay: 0,
source: function (request, response) {
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: baseURL + request.term,
dataType: "json",
success: function (data) {
response(data)
}
});
},
minLength: 1,
});
});
});
I've put the .autocomplete() inside an each() function so you can refer to this to get the base url from the data attribute. You can then pass that into the source function.
Incidentally, if there is more than 1 input then you need to make each one have a unique ID. You shouldn't have elements with the same ID :)
Another way to change the URL in a ajax request
$.ajax({
url: "http://static.url/",
beforeSend: function (xhr) {
this.url = "http://dyn.url/" + "here"
}
});
i think what you should be doing is :
$(function () {
var baseURL = $(".autocomplete").data('url');
$(".autocomplete").autocomplete({
delay: 0,
source: function (request, response) {
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: baseURL + request.term,
dataType: "json",
success: function (data) {
response(data)
}
});
},
minLength: 1,
});

Categories