.attr selector wont work in a each loop? - javascript

Here's the code:
$.ajax({
url: 'AEWService.asmx/previewAsset',
type: "GET",
contentType: "application/json; charset=utf-8",
data: json,
success: function (json) {
var prevObj = jQuery.parseJSON(json.d);
setInterval(function () {
var pId = $('#previewIframe').contents().find('[preview-id]');
$.each(prevObj, function (i, item) {
pId.each(function () {
var pElem = this.attr("preview-id");
if (pElem == item.Id) {
$(this).html(item.Value);
}
});
});
}, 3000);
}
});

this is a DOM node, not a jQuery object. Please read the .each() documentation and have a look at the examples.
Actually you already seem to know that, since you are calling $(this).html()...

Try to change this.attr("preview-id") to $(this).attr("preview-id")
like you use this in $(this).html(item.Value)
Hope this help you.

Related

Javascript jQuery not executing after .is(":checkbox") check?

So I have a click event that loops through the items of an html table and saves them to an array. I am attempting to identify if the passed value is a checkbox which seems to be working correctly. However when I add the check the code won't fully execute after it hits the check? (The ajax code is never reached.) Am I missing something here? Searching other posts one suggestion was to move the declaration of my checked variable outside the each statement which I did. Any help is greatly appreciated.
$("#btnSubmit").click(function () {
var valueArray = [];
var headers = [];
var dataToSend;
var checked = null;
var arrayItem = {};
$('#table th').each(function (index, item) {
headers[index] = $(item).html();
});
$('#table tr').has('td').each(function () {
$('td', $(this)).each(function (index, item) {
arrayItem[headers[index]] = $(item).html();
checked = $(arrayItem[headers[index]]).is(":checkbox");
});
valueArray.push(arrayItem);
dataToSend = JSON.stringify(valueArray);
});
$.ajax({
type: "POST",
url: '#Url.Action("SaveTable", "Home")',
dataType: "json",
data: dataToSend,
contentType: "application/json; charset=utf-8",
});
});

How get a variable from HTML in JavaScript/Ajax Call

I'm using Zend Framework 2.
I would like to know how to get data defined in html in my javascript code.
html
<tr class="MyClass" data-MyData="<?php echo json_encode($array);?>">
javascript
$(document).on('click','.MyClass', function () {
var temp =document.getElementsByClassName("data-MyData");
$.ajax({
url: path_server + "pathDefinedInMyConfig",
type: 'post',
encode: true,
dataType: 'json',
data: {
'temp ': temp
},
success: function (data) {
//some code
},
error: function () {
alert("ERROR");
}
});
});
The problem is I don't have access to row in my Controller method. And i want to have access to My $array defined in html in my Controller.
Problem is that you are trying to find a class by the name data-MyData, but the object you "want" to look for is "MyClass"
Try something like var temp =document.getElementsByClassName("MyClass").attr("data-MyData");
Even better is that since you click on the object with MyClass you can use $(this).attr('data-MyData');
then result will look like: var temp = $(this).attr('data-MyData');
Simply replace temp var assignment line:
var temp =document.getElementsByClassName("data-MyData");
with this one:
var temp = this.getAttribute("data-MyData");
Since you use jQuery use the following:
$('.MyClass').data('MyData')
or
$('.MyClass').attr('data-MyData')
use like this-
$(document).on('click','.MyClass', function () {
var temp =$(this).attr('data-MyData');
$.ajax({
url: path_server + "pathDefinedInMyConfig",
type: 'post',
encode: true,
dataType: 'json',
data: {
'temp ': temp
},
success: function (data) {
//some code
},
error: function () {
alert("ERROR");
}
});});
You have a wrong selector. document.getElementsByClassNames() returns the collections so you have to loop through to get the target element:
var temp =document.getElementsByClassName('MyClass');
[].forEach.call(temp, function(el){
console.log(el.dataset['MyData']);
});
or as you are using jQuery then you can use .data():
var temp =$(this).data("MyData");
and with javascript:
var temp =this.dataset["MyData"];
// var temp =this.dataset.MyData; // <---this way too.

Change label text on mouse over with ajax

I want to change the value of a label on mouse over. This is what I have done so far:
$(function () {
var hoverOff = "";
$("[id*=GV] td").hover(function () {
hoverOff = $("label", $(this).closest("td")).text();
$.ajax({
type: "POST",
url: "MyMethode.aspx/GetNewValue?text=" + hoverOff,
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("label", $(this).closest("td")).html(data.d);
}
});
},
function () {
$("label", $(this).closest("td")).html(hoverOff);
}
);});
At the beginning I save the current text in hoverOff and send that value to the method GetNewValue wich returns the new value and inside ajax success I want to apply that value to the label. The problem is that the text for label never changes, although data.d contains the new text. Should I use something else instead of .html()?
this inside ajax callback isn't referring to the current hovered TD but to the jqXHR object. You can use $.ajax context option:
context: this,
BTW, $(this).closest("td") is quite unrelevant because obviously, even you have nested TDs, $(this).closest("td") will always return the current TD, so you could just use this:
hoverOff = $("label", this).text();
And data: "{}", could be data: {},, no point of setting a string here. >> because you are setting contentype to JSON
It's a context problem you can't use this inside success function, try this code:
$(function () {
var hoverOff = "";
$("[id*=GV] td").hover(function () {
var label = $("label", $(this).closest("td"));
hoverOff = label.text();
$.ajax({
type: "POST",
url: "MyMethode.aspx/GetNewValue?text=" + hoverOff,
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
label.html(data.d);
}
});
},
function () {
label.html(hoverOff);
}
);});
You could use this solution from https://stackoverflow.com/a/10701170/3421811
$('.btn').hover(
function() {
var $this = $(this); // caching $(this)
$this.data('initialText', $this.text());
$this.text("I'm replaced!");
},
function() {
var $this = $(this); // caching $(this)
$this.text($this.data('initialText'));
}
);

What's the error in following function code of jQuery?

I've written one jQuery function to get the city and state code based upon the zip code value but facing some issue with some errors. Can someone please help me in correcting the mistakes I'm making here.
Following is my code :
$(document).ready(function() {
$("#zip_code").keyup(function() {
var el = $(this);
var module_url = $('#module_url').val();
if (el.val().length === 5) {
$.ajax({
url : module_url,
cache: false,
dataType: "json",
type: "GET",
data: {'request_type':'ajax', 'op':'get_test_category_list','zip_code =' + el.val()},
success: function(result, success) {
$("#city").val(result.city);
$("#state_code").val(result.state);
}
});
}
});
});
Thanks in advance.
The issue is in your data object, you have invalid syntax. Change this:
'zip_code =' + el.val()
To this:
'zip_code': el.val()
The full object should look something like this:
data: {
'request_type': 'ajax',
'op': 'get_test_category_list',
'zip_code': el.val()
},
I think the problem is with data part of the ajax
Change it like this
data: {request_type:"ajax", op:"get_test_category_list",zip_code : el.val()},

Javascript/jquery iterate async problems

I would like to iterate through a certain amount of pages, and populate them with content using ajax calls. The problem is, when I put the ajax calls inside the iteration function it has problems with the synchronous nature of javascript. The iteration has already continued before the ajax call is completed. So I made a workaround where I made the ajax call in a setTimeout, which works fine. But I don't really like this method, and was wondering if there is an alternative (better) solution. (I know that jQuery provides a async: true option, however that did not work)
function populatePages(i) {
pageId = PageIds[i];
containerId = pageIdContainer[i];
$j.ajax({
type: 'GET',
dataType: 'html',
url: url,
data: { pageid: pageId, containerid: containerId },
success: function(data) {
//populate the DIV
}
});
}
i = 0;
x = 50;
$j.each(pagesIds, function(){
setTimeout("populatePages("+i+")", x);
x = x + 50;
i++;
});
Try this (not tested)
function populatePages(i) {
console.log('populatePages', i)
pageId = PageIds[i];
return $.ajax({
type: 'GET',
dataType: 'html',
url: '/echo/html',
data: { pageid: pageId},
success: function(data) {
}
});
}
function messy(index){
console.log('messy', index)
if(index >= PageIds.length){
return;
}
populatePages(index).always(function(){
console.log('complete', index)
setTimeout(function(){
messy(index + 1)
});//to prevent possible stackoverflow
})
}
PoC: Fiddle

Categories

Resources