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",
});
});
Related
I am following a tutorial on YouTube showing how to get data from the myapifilms.com api and I am having trouble rendering the data to HTML. Currently my ajax call is working and the data is showing in the console. The problem I am having is getting the data to show on the page itself. I searched through the question already asked but had no luck. Here's my js code so far:
$(document).ready(function(){
$("#searchMovie").click(searchMovie);
var movieTitle = $("#movieTitle");
var table = $("#results");
var tbody = $("#results tbody"); //table.find("tbody");
function searchMovie() {
var title = movieTitle.val();
$.ajax({
url: "http://www.myapifilms.com/imdb/idIMDB?title="+ title +"&token= + token goes here +&format=json&language=en-us&aka=0&business=0&seasons=0&seasonYear=0&technical=0&filter=2&exactFilter=0&limit=1&forceYear=0&trailers=0&movieTrivia=0&awards=0&moviePhotos=0&movieVideos=0&actors=0&biography=0&uniqueName=0&filmography=0&bornAndDead=0&starSign=0&actorActress=0&actorTrivia=0&similarMovies=0&adultSearch=0&goofs=0"es=0&fullSize=0&companyCredits=0",
dataType: "jsonp",
success: renderMovies
})
function renderMovies(movies) {
console.log(movies);
tbody.empty();
for(var m in movies) {
var movie = movies[m];
var title = movie.title;
var plot = movie.simplePlot;
var posterUrl = movie.urlPoster;
var imdbUrl = movie.urlIMDB;
var tr = $("<tr>");
var titleTd = $("<td>").append(title);
var plotTd = $("<td>").append(plot);
tr.append(titleTd);
tr.append(plotTd);
tbody.append(tr);
}
}
}
});
I feel like I am so close but can't quite figure what I am missing. Again I was following a tutorial so if there's a better way to accomplish this goal I'm definitely open to suggestions.
Update:
I changed my code to this and I'm getting undefined in the browser. I changed the for loop to this
success: function (movies) {
console.log(movies);
tbody.empty();
for (var m in movies) {
$(".movies").append("<h3>"+ movies[m].title +"</h3>");
$(".movies").append("<h3>"+ movies[m].plot +"</h3>");
}
}
I figured out a solution, instead of using myapifilms, I used the tmdb api instead. Changing my code to this worked:
var url = 'http://api.themoviedb.org/3/',
mode = 'search/movie?query=',
input,
movieName,
key = 'myapikey';
//Function to make get request when button is clicked to search
$('button').click(function() {
var input = $('#movie').val(),
movieName = encodeURI(input);
$.ajax({
type: 'GET',
url: url + mode + input + key,
async: false,
jsonpCallback: 'testing',
contentType: 'application/json',
dataType: 'jsonp',
success: function(json) {
console.dir(json.results);
for (var i = 0; i < json.results.length; i++){
var result = json.results[i];
$(".moviesContainer").append('<div class="movies col-md-12">'+
'<img class="poster" src="http://image.tmdb.org/t/p/w500'+ result.poster_path +'" />'
+'<h3>'+ result.title +'</h3>'
+'<p><b>Overview: </b>'+ result.overview +'</p>'
+'<p><b>Release Date: </b>'+ result.release_date +'</p>'
+'</div>');
}
},
error: function(e) {
console.log(e.message);
}
});
});
I have constructed an app with push state. Everything is working fine. However in some instances my jquery function are fireing multiple times. That is because when I call push state I bind the particular js file for each page I call. Which means that the same js functions are binded many times to the html while I surf in my page.
Tip: I am using documen.on in my jquery funciton because I need my function to get bound to the dynamical printed HTML through Ajax.
I tried to use off in the push state before printing with no success!
Here is my code:
var requests = [];
function replacePage(url) {
var loading = '<div class="push-load"></div>'
$('.content').fadeOut(200);
$('.container').append(loading);
$.each( requests, function( i, v ){
v.abort();
});
requests.push( $.ajax({
type: "GET",
url: url,
dataType: "html",
success: function(data){
var dom = $(data);
//var title = dom.filter('title').text();
var html = dom.find('.content').html();
//alert(html);
//alert("OK");
//$('title').text(title);
$('a').off();
$('.push-load').remove();
$('.content').html(html).fadeIn(200);
//console.log(data);
$('.page-loader').hide();
$('.load-a').fadeIn(300);
}
})
);
}
$(window).bind('popstate', function(){
replacePage(location.pathname);
});
Thanks in advance!
simple bind new function with blank code
$( "#id" ).bind( "click", function() {
//blank
});
or
used
$('#id').unbind();
Try this,
var requests = [];
function replacePage(url) {
var obj = $(this);
obj.unbind("click", replacePage); //unbind to prevent ajax multiple request
var loading = '<div class="push-load"></div>';
$('.content').fadeOut(200);
$('.container').append(loading);
$.each(requests, function (i, v) {
v.abort();
});
requests.push(
$.ajax({
type: "GET",
url: url,
dataType: "html",
success: function (data) {
var dom = $(data);
//var title = dom.filter('title').text();
var html = dom.find('.content').html();
//alert(html);
//alert("OK");
//$('title').text(title);
obj.bind("click", replacePage); // binding after successfulurl ajax request
$('.push-load').remove();
$('.content').html(html).fadeIn(200);
//console.log(data);
$('.page-loader').hide();
$('.load-a').fadeIn(300);
}
}));
}
Hope this helps,Thank you
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.
I'm trying to do an autocomplete to my textbox, but it doesn't work. Follow my code.
$(function () {
var credenciada = '<%= credenciadaId %>';
xml_NomeCompleto = "";
var Nomes = "";
var retorno = '';
var count = 0;
var t = '';
$.ajax({
url: "../Xml/AcessoExterno.aspx?Credenciada=" + credenciada,
type: "get",
dataType: 'xml',
async: false,
success: function (data) {
$(data).find("REGISTRO").each(function () {
t = $(this).find("NOMECOMPLETOUSUARIO").text();
Nomes += ["\"" + t + "\","];
});
}
});
$("#ctl00_contentConteudo_txtNome").autocomplete({ source: Nomes });
});
The variable 't' receives all the names of my users, normally, but the autocomplete don't work.
Wait for ajax response to complete and then initialize the autocomplete because before you initialize the plugin data is not available. Also the way you are creating Nomes(source) is wrong. Declare it as an array and use push method to populate it.
Try this
var Nomes = [];
$.ajax({
url: "../Xml/AcessoExterno.aspx?Credenciada=" + credenciada,
type: "get",
dataType: 'xml',
async: false,
success: function (data) {
$(data).find("REGISTRO").each(function () {
Nomes.push($(this).find("NOMECOMPLETOUSUARIO").text());
});
$("#ctl00_contentConteudo_txtNome").autocomplete({ source: Nomes });
}
});
i have a page, wherein i am using a ajax for inserting records... now in javascript i am using a for each loop to loop the html table and insert the rows in database. but happens is as foreach loop executes fast, it sometime, does not insert some records.. so i want to make the loop sleep for sometime once it has executed first and thereafter...
is there any way to pause the for loop.. i used setTImeout.. but it just delay it first time and not consecutive times...
here's my code.
function AddTopStories() {
$("#tBodySecond tr").each(function (index) {
$.ajax({
type: "POST",
url: "AjaxMethods.aspx/AddTopStoriesPosition",
data: "{'articleID':'" + $("td:nth-child(1)", this).text() + "','siteID':1}",
dataType: "json",
contentType: "application/json",
success: function (data) {
window.setTimeout(showSuccessToast(data.d), 3000);
},
error: function (data) {
window.setTimeout(showSuccessToast("Error:" + data.reponseText), 3000);
}
});
});
}
Please help me to resolve this issue... its utmost important.
*************************************UPDATED CODE AS PER THE CHANGES BY jfriend00*********
function AddTopStories() {
var stories = $("#tBodySecond tr");
var storyIndex = 0;
function addNext() {
if (storyIndex > stories.length) return; // done, no more to get
var item = stories.get(storyIndex++);
alert($("td:nth-child(1)", item).text());
addNext();
}
}
This just does not do anything... does not alert...
I'd recommend you break it into a function that does one story and then you initiate the next story from the success handler of the first like this:
function AddTopStories() {
var stories = $("#tBodySecond tr");
var storyIndex = 0;
function addNext() {
if (storyIndex >= stories.length) return; // done, no more to get
var item = stories.get(storyIndex++);
$.ajax({
type: "POST",
url: "AjaxMethods.aspx/AddTopStoriesPosition",
data: "{'articleID':'" + $("td:nth-child(1)", item).text() + "','siteID':1}",
dataType: "json",
contentType: "application/json",
success: function (data) {
addNext(); // upon success, do the next story
showSuccessToast(data.d);
},
error: function (data) {
showSuccessToast("Error:" + data.reponseText);
}
});
}
addNext();
}
Ugly, but you can fake a javascript 'sleep' using one of the methods on this website:
http://www.devcheater.com/