this object reference not working inside $.each - javascript

Why won't foo get appended?
$.ajax({
type: 'GET',
dataType: 'json',
cache: false,
url: 'barfoochakalaka',
success:
function(response) {
$.each(response, function(index, val) {
$(this).parent().parent().append('foo');
});
}
})

Because inside each, this is set to the current element being iterated over (docs), so normally we define this to be something else before we enter the each loop:
var that = this;
$.each(response, function(index, val) {
var content = '<div class="link-history">'+ val.date + ', ' + val.userid + ', ' + val.status + '</div>';
$(that).parent().parent().append('foo');
});
However, in this circumstance, this in the success callback of an AJAX request is equal to the jqXHR object which launched the request, not the DOM element you're after, so we have to move the var that = this to even further away;
var that = this;
$.ajax({
type: 'GET',
dataType: 'json',
cache: false,
url: 'barfoochakalaka',
success: function(response) {
$.each(response, function(index, val) {
var content = '<div class="link-history">' + val.date + ', ' + val.userid + ', ' + val.status + '</div>';
$(that).parent().parent().append('foo');
});
}
})

var $this = $('#Selector').parent().parent();
$.ajax({
type: 'GET',
dataType: 'json',
cache: false,
url: 'barfoochakalaka',
success:
function(response) {
$.each(response, function(index, val) {
var content = '<div class="link-history">'+ val.date + ', ' + val.userid + ', ' + val.status + '</div>';
$this.append('foo');
});
}
})
EDIT:
added .parent().parent() to the original selector, so you are not calling this for each loop

Response may not be an array, just a string. Try assigning the response to an element and then using a selector to grab all children in that element before doing an .each()

Your response is not an object of elements, it's most likely a list of strings possibly with your selectors(?) if that's it then use $($(this)).

Related

How to prefill fields using jquery

Hi I'm trying to figure out how to fill all fields using ajax call, it successfully doing by selecting category, it loads all related sub_categories.
But sub_sub_category fields are empty. Only when I choose sub_category option it will load all sub_sub_categories, but I want all prefilled once category has been changed. I don't mind to leave like this, but problem is if I have only single sub_category I can not select any sub_sub_category even if they have any I tried to convert to function and call them but no success.
Code below:
<script>
$(document).ready(function() {
get_sub_sub_category();
$('select[name="category_id"]').on('change', function() {
var category_id = $(this).val();
if(category_id) {
$.ajax({
url: "{{ url('/category/sub-category/') }}/"+category_id,
type: "GET",
dataType: "json",
success: function(data) {
$('select[name="sub_sub_category_id"]').html('');
var d = $('select[name="sub_category_id"]').empty();
$.each(data, function(key, value) {
$('select[name="sub_category_id"]').append('<option value="'+ value.id +'">' + value.sub_category_name + '</option>');
});
get_sub_sub_category();
},
})
} else {
alert('danger');
}
});
function get_sub_sub_category() {
$('select[name="sub_category_id"]').on('load change', function () {
var sub_category_id = $(this).val();
if (sub_category_id) {
$.ajax({
url: "{{ url('/category/sub-sub-category/') }}/"+sub_category_id,
type: "GET",
dataType: "json",
success: function (data) {
var d = $('select[name="sub_sub_category_id"]').empty();
$.each(data, function (key, value) {
$('select[name="sub_sub_category_id"]').append('<option value="' + value.id + '">' + value.sub_sub_category_name + '</option>');
});
},
})
} else {
alert('danger');
}
});
}
});
</script>
You might want to consider the following.
$(function() {
$('select[name="category_id"]').on('change', function() {
var category_id = $(this).val();
if (category_id) {
$.ajax({
url: "{{ url('/category/sub-category/') }}/" + category_id,
type: "GET",
dataType: "json",
success: function(data) {
$('select[name="sub_sub_category_id"]').html('');
var d = $('select[name="sub_category_id"]').empty();
$.each(data, function(key, value) {
$('select[name="sub_category_id"]').append('<option value="' + value.id + '">' + value.sub_category_name + '</option>');
});
$('select[name="sub_category_id"]').trigger("change");
},
})
} else {
alert('danger');
}
});
$('select[name="sub_category_id"]').on('change', function() {
var sub_category_id = $(this).val();
if (sub_category_id) {
$.ajax({
url: "{{ url('/category/sub-sub-category/') }}/" + sub_category_id,
type: "GET",
dataType: "json",
success: function(data) {
var d = $('select[name="sub_sub_category_id"]').empty();
$.each(data, function(key, value) {
$('select[name="sub_sub_category_id"]').append('<option value="' + value.id + '">' + value.sub_sub_category_name + '</option>');
});
},
})
} else {
alert('danger');
}
});
});
This defined the callbacks for both. For category, when it is changed, it triggers change event on sub-category. This in turn will cascade the loading of the next Select.

Nested ajax call with an value from the first into the seconds Ajax call's url

I want to do live search and I need to use an id value from the first ajax call inside the second one.
I get the info when I type fast into the search, but if I search again or continue, I get this and the outer ajax wont be called again.
GET
http://api.themoviedb.org/3/movie/366924/videos?api_key=KEYHERE…9a6ebe&callback=jQuery1102017797202615180896_1472038138300&_=1472038138301
$('#movie-search')
.keyup(function() {
var input = $('#movie-search').val(),
movieName = encodeURI(input);
if (input.length > 3) {
$("#myList").empty();
$.ajax({
url: url + searchMode + apiKey + '&query=' + movieName,
dataType: 'jsonp',
success: function(data) {
console.log(data.results);
resultArray = data.results;
}
})
.then(function() {
$.each(resultArray,
function (index, value) {
console.log(value.id);
var searchVideo = 'movie/' + value.id + '/videos';
$.ajax({
url: url + searchVideo + apiKey,
dataType: 'jsonp',
success: function () {
$("#myList").append("stuffs");
}
});
});
});
}
$(this).change();
});
Try This -
$('#movie-search')
.keyup(function() {
var input = $('#movie-search').val();
var movieName = encodeURI(input);
if (input.length > 3) {
$("#myList").empty();
$.ajax({
url: url + searchMode + apiKey + '&query=' + movieName,
dataType: 'jsonp',
success: function(data) {
console.log(data.results);
resultArray = data.results;
$.each(resultArray,
function(index, value) {
console.log(value.id);
var searchVideo = 'movie/' + value.id + '/videos';
$.ajax({
url: url + searchVideo + apiKey,
dataType: 'jsonp',
success: function() {
$("#myList").append("stuffs");
}
});
});
}
});
}
$(this).change();
});

JSON object length is returning a big value instead of expected 750 records

I'm trying to append records to my table which are being loaded from an AJAX request which returns JSON, but if I try to use output.length it returns a big number instead of 750 records. This causes the for loop to be run for 10000 times instead of 750. Why is this?
$(document).ready(function() {
getData();
});
function getData() {
$.ajax({
data: {
action: 'getData'
},
url: "api/ajaxcall.php",
type: 'post',
async: false,
dataType: 'html',
success: function(output) {
console.log(output.length);
// buildTable(result);
}
});
}
function buildTable(output) {
for (var i = 0; i < output.length; i++) {
$('<tr>').append(
$('<td>').text(output[i].naam),
$('<td>').text(output[i].perc),
$($('<input id="' + output[i].id + '" onclick="editData(this)" type = "button" value = "Edit" />')),
$($('<input id="' + output[i].id + '" onclick="readData(this)" type = "button" value = "Read" />')),
$($('<input id="' + output[i].id + '" onclick="deleteRow(' + output[i].id + ')" type = "button" value = "Delete" />'))
).appendTo('#tableA');
}
}
Check with this probably
function getData() {
$.ajax({
data: {
action: 'getData'
},
url: "api/ajaxcall.php",
type: 'post',
async: false,
dataType: 'html',
success: function(output) {
output = JSON.parse(output.d); //May it need to parse the string
console.log(output.length);
// buildTable(result);
}
});
}

Jquery not working while process dynamically

The below code works for me
function gethotelsbydestination(dest_id) {
$.ajax({
url: "controller/gethotels.php",
dataType: "json",
data: "id=" + dest_id,
success: function(data) {
$("#divid").html("");
$.each(data, function(index, item) {
var val = item.id;
var text = item.name;
$("#divid").append(
$('<option></option>').val(val).html(text)
);
})
}
});
}
But when i use below code not returns anything.divv is the id of an dropdown passed from php page
function gethotelsbydestination(dest_id, divv) {
var divdrp = "$('#" + divv + "')";
$.ajax({
url: "controller/gethotels.php",
dataType: "json",
data: "id=" + dest_id,
success: function(data) {
divdrp.html("");
$.each(data, function(index, item) {
var val = item.id;
var text = item.name;
divdrp.append(
$('<option></option>').val(val).html(text)
);
})
}
});
}
The problem is var divdrp="$('#"+divv+"')";
Any Solution please
You can't concatenate directly. Use this:
divdrp = $('#' + divv);
instead of this:
var divdrp = "$('#" + divv + "')"; // it is not a jquery object

what is [object Object]?

why instead giving data(value) of database give me the [object Object]?
var dataObj = $(this).closest('form').serialize();
$.ajax({
type: "POST",
url: url,
data: dataObj,
cache: false,
dataType: 'json',
success: function (data) {
$(".list_name").show().html('');
$(".list_name").append('<p>' + data + '</p>');
$('.list_name p a').click( function(e) {
e.preventDefault();
$('<b>' + b + '، </b><input type="text" name="hotel[]" value="' + b + '" style="border: none; display: none;" />').appendTo($('.auto_box span'));
$(this).remove();
return false;
});
});
results url is:(json_encode()) :
[{"name":"333333"},{"name":"\u0633\u0644"},{"name":"\u0633\u0644\u0627\u0633\u06cc"},{"name":"\u0633\u0644\u0627\u0633\u0633"},{"name":"\u0633\u0644\u0627\u0645"}]
update: full code:
$('.auto_complete').keyup(function () {
var id = '#' + this.id;
var alt = $(id).attr('alt'); var id = $(this).attr('id'); var name = $(this).attr('name');
var url = alt + id + '/' + name;
var dataObj = $(this).closest('form').serialize();
$.ajax({
type: "POST",
url: url,
data: dataObj,
cache: false,
dataType: 'json',
success: function (data) {
$(".list_name").show().html('');
for (i in data) {
var obj = $('' + data[i].name + '');
obj.click(function(e) {
e.preventDefault();
$('<b>' + b + '، </b><input type="text" name="hotel[]" value="' + b + '" style="border: none; display: none;" />').appendTo($('.auto_box span'));
$(this).remove();
return false;
});
var p = $('p');
p.append(obj);
$(".list_name").append(p);
}
},
"error": function (x, y, z) {
// callback to run if an error occurs
alert("An error has occured:\n" + x + "\n" + y + "\n" + z);
}
});
});
data is not a string, but a JSON object, which is basically a Javascript Object. You access it as you would any JS object/array (looks like your result string is an array)
So you can do something like this: data[1].name
data is a list (It is javascript object).
toString( list ) in javascript gives "object Object"
data[0].name will return "333333"
To make a string from a complex object write your own function.
It looks like your Ajax call is returning an array of structures. Each element in the array is a name-value pair. Given that data is an array, the first element is data[0] so you might do something like:
var firstElem = data[0];
var firstName = firstElem.name;
alert("The first name is: " + firstName);
If you want to add all of the names into your html, you would need to loop through the array, each time appending the current element.
If you wanted to show all names, you could do
var names = "";
for (var i=0; i<data.length; i++) {
var elem = data[i];
names = names + elem.name + ", ";
}
I would rewrite it in the following way
var dataObj = $(this).closest('form').serialize();
$.ajax({
type: "POST",
url: url,
data: dataObj,
cache: false,
dataType: 'json',
success: function (data) {
$(".list_name").show().html('');
for (i in data) {
var obj = $('' + data[i].name + '');
obj.click(function(e) {
e.preventDefault();
$('<b>' + b + '، </b><input type="text" name="hotel[]" value="' + b + '" style="border: none; display: none;" />').appendTo($('.auto_box span'));
$(this).remove();
return false;
});
var p = $('p');
p.append(obj);
$(".list_name").append(p);
}
}
});

Categories