I have more than three TextBoxes. I want to send this data as in the code. The "indeks " value is always the last click. How do I keep the index?
click:function(e) {
var item = e.itemElement.index();
indeks = item;
}
var field= "";
onl: function () {
$.ajax({
type: "GET",
cache:true,
url: MYURL,
success: function (msg, result, status, xhr) {
var obje = jQuery.parseJSON(msg)
var i = 0;
field = " ";
$('#wrapper *').filter(':input').each(function () {
if (txtvalue != "") {
if (i)
field += " and ";
field = field + "[" + obje[indeks]+ "]" $(this ).val() + "'";
i++;
}
});
});
},
As I wasn't sure if I got your question right, I prefered to comment on your topic - but now it seems that my answer helped you, so I decided to post it as an actual answer:
1st step: declare an array outside your success handler
2nd step: push the index and the value for the element into this array
3rd step: loop through all entries of the array and build your 'select' statement
Here is your edited example:
https://jsfiddle.net/Lk2373h2/1/
var clickedIndexes = [];
click:function(e) {
var item = e.itemElement.index();
indeks = item;
}
var field= "";
onl: function () {
$.ajax({
type: "GET",
cache:true,
url: MYURL,
success: function (msg, result, status, xhr) {
var obje = jQuery.parseJSON(msg)
var i = 0;
field = " ";
$('#wrapper *').filter(':input').each(function () {
$(this).attr('id', i);
var txtvalue=$(this).val();
if (i)
clickedIndexes.push({
index: indeks,
value: $(this ).val()
});
var selectString = "";
for (var u = 0; u < clickedIndexes.length; u++) {
selectString += "[" + obje[clickedIndexes[u].index].ALAN + "]" + "=" + "'" + clickedIndexes[u].value + "'";
}
field = selectString;
i++;
});
});
},
Related
I am using for loop get all the data place in a div. I have following code in javascript so far:
<script type="text/javascript">
function callback(){
$.getScript("/frontend/vendor/jquery/jquery.min.js", function() {
$('input').on('change', function(){
var qty = $(this).attr('id');
var price = $('#'+qty+'_price').attr('value');
var subtotal = qty * price;
$('#'+qty+'_total').html('€ '+subtotal);
})
});
}
function checkout(callback){
let eventDate = JSON.parse(localStorage.getItem("events"));
var unique = eventDate.filter(function(itm, i, eventDate) {
return i == eventDate.indexOf(itm);
});
let items = [];
for (var n = 0; n < unique.length; n++){
var eventId = unique[n];
$.ajax({
"url":"/get_my_product/"+ eventId,
"type":"GET",
"dataType":"json",
"contentType":"application/json",
success:function(response){
let party = 'Party name';
let html = "<tr class='product-row'><td class='product-col'><h5 class='product-title'><a>"+party+"</a></h5></td><td class='product-col'><h5 class='product-title'><a>"+response.date+"</a></h5></td><td value='"+response.price+"' id='"+n+"_price'>€ "+response.price+"</td><td><div class='input-group'><input class='vertical-quantity form-control dataqty' id='"+n+"' type='number'><span class='input-group-btn-vertical'></span></div></td><td id='"+n+"_total'>€ "+response.price+"</td></tr>";
$('#data').append(html);
}
})
}
callback && callback();
}
checkout();
</script>
When I am trying to call the function after the loop completion it does not work. What is wrong here?
Change
function checkout(callback){
to
function checkout() {
I think the argument callback to the function checkout "shadows" the previously defined callback function. Then, when you call the function checkout you are passing nothing to the function, and callback will be undefined.
Or, in the last line, pass the function as an argument:
checkout(callback);
Makes no sense to add another version of jQuery to add events. You are not passing the callback to the method so it is always going to be undefined. And you are not waiting for the Ajax calls to complete before calling the callback.
// No reason for loading the JQuery version here
function addMyEvents() {
$('input').on('change', function() {
var qty = $(this).attr('id');
var price = $('#' + qty + '_price').attr('value');
var subtotal = qty * price;
$('#' + qty + '_total').html('€ ' + subtotal);
})
}
function checkout(callback) {
// hold the ajax calls
const myAjaxCalls = []
let eventDate = JSON.parse(localStorage.getItem("events"));
var unique = eventDate.filter(function(itm, i, eventDate) {
return i == eventDate.indexOf(itm);
});
let items = [];
for (var n = 0; n < unique.length; n++) {
var eventId = unique[n];
// push the ajax calls to an array
myAjaxCalls.push($.ajax({
"url": "/get_my_product/" + eventId,
"type": "GET",
"dataType": "json",
"contentType": "application/json",
success: function(response) {
let party = 'Party name';
let html = "<tr class='product-row'><td class='product-col'><h5 class='product-title'><a>" + party + "</a></h5></td><td class='product-col'><h5 class='product-title'><a>" + response.date + "</a></h5></td><td value='" + response.price + "' id='" + n + "_price'>€ " + response.price + "</td><td><div class='input-group'><input class='vertical-quantity form-control dataqty' id='" + n + "' type='number'><span class='input-group-btn-vertical'></span></div></td><td id='" + n + "_total'>€ " + response.price + "</td></tr>";
$('#data').append(html);
}
}))
}
// if we have a callback
if (callback) {
// wait for all the ajax calls to be done
$.when.apply($, myAjaxCalls).done(callback)
}
}
// pass the function to the method.
checkout(addMyEvents);
Now the best part is you do not even need to worry about the callback to bind events. You can just use event delegation and it would work. This way whenever an input is added to the page, it will be picked up.
$(document).on('change', 'input', function() {
var qty = $(this).attr('id');
var price = $('#' + qty + '_price').attr('value');
var subtotal = qty * price;
$('#' + qty + '_total').html('€ ' + subtotal);
})
function checkout() {
let eventDate = JSON.parse(localStorage.getItem("events"));
var unique = eventDate.filter(function(itm, i, eventDate) {
return i == eventDate.indexOf(itm);
});
let items = [];
for (var n = 0; n < unique.length; n++) {
var eventId = unique[n];
$.ajax({
"url": "/get_my_product/" + eventId,
"type": "GET",
"dataType": "json",
"contentType": "application/json",
success: function(response) {
let party = 'Party name';
let html = "<tr class='product-row'><td class='product-col'><h5 class='product-title'><a>" + party + "</a></h5></td><td class='product-col'><h5 class='product-title'><a>" + response.date + "</a></h5></td><td value='" + response.price + "' id='" + n + "_price'>€ " + response.price + "</td><td><div class='input-group'><input class='vertical-quantity form-control dataqty' id='" + n + "' type='number'><span class='input-group-btn-vertical'></span></div></td><td id='" + n + "_total'>€ " + response.price + "</td></tr>";
$('#data').append(html);
}
})
}
}
checkout();
I am getting rows of content via jQuery AJAX and then populating the table with new content as it is being added. The problem is that some content may be deleted from the database, in which case I also want it removed in real-time from the table.
I suspect I need to loop through the table div IDs and remove any IDs that don't exist in the AJAX response but I'm unsure how to compare them to the data response and then remove them:
function startRecords() {
$.ajax({
url: URL,
dataType: 'json',
success: function(data) {
var res = data;
for (var i = 0, len = res.length; i < len; i++) {
if ($("#records-row-" + res[i].id).length == 0) {
$("#records-content tbody").prepend('<tr class="table-wrapper" id="records-row-' + res[i].id + '"><td class"" style="">' + res[i].content_1 + '</td><td class"" style="">' + res[i].content_2 + '</td></tr>');
}
}
var delay = 3000;
setTimeout(function() {
startRecords();
}, delay);
},
cache: false
}).fail(function(jqXHR, textStatus, error) {
var delay = 3000;
setTimeout(function() {
startRecords();
}, delay);
});
}
Any recommendations on how to achieve this?
you are prepending to "records-content" div without clearing it first.
you need to add
$("#records-content tbody").html('')
before starting your for loop.
this way only current data in you database table will populate in table.
Use empty() to clear the records, before prepending new ones.
function startRecords() {
$.ajax({
url: URL,
dataType: 'json',
success: function(res) {
$("#records-content tbody").empty();
for (var i = 0, len = res.length; i < len; i++) {
if ($("#records-row-" + res[i].id).length == 0) {
$("#records-content tbody").prepend('<tr class="table-wrapper" id="records-row-' + res[i].id + '"><td class"" style="">' + res[i].content_1 + '</td><td class"" style="">' + res[i].content_2 + '</td></tr>');
}
}
var delay = 3000;
setTimeout(function() {
startRecords();
}, delay);
},
cache: false
}).fail(function(jqXHR, textStatus, error) {
var delay = 3000;
setTimeout(function() {
startRecords();
}, delay);
});
}
To remove elements that are not in the response from server.
Add the following right after success: function(res) {
var currentRows = $("[id^=records-row-]").toArray()
var currentRowsId = currentRows.map(function(row) { return row.id })
var resRows = res.map(function(row) { return "records-row-" + row.id })
var removeRows = currentRowsId.filter(function(rowId) { return resRows.indexOf(rowId) === -1 })
removeRows.forEach(function(rowId) { $("#" + rowId).remove() })
So that it looks like this
function startRecords() {
$.ajax({
url: URL,
dataType: 'json',
success: function(res) {
var currentRows = $("[id^=records-row-]").toArray()
var currentRowsId = currentRows.map(function(row) { return row.id })
var resRows = res.map(function(row) { return "records-row-" + row.id })
var removeRows = currentRowsId.filter(function(rowId) { return resRows.indexOf(rowId) === -1 })
removeRows.forEach(function(rowId) { $("#" + rowId).remove() })
for (var i = 0, len = res.length; i < len; i++) {
if ($("#records-row-" + res[i].id).length == 0) {
$("#records-content tbody").prepend('<tr class="table-wrapper" id="records-row-' + res[i].id + '"><td class"" style="">' + res[i].content_1 + '</td><td class"" style="">' + res[i].content_2 + '</td></tr>');
}
}
var delay = 3000;
setTimeout(function() {
startRecords();
}, delay);
},
cache: false
}).fail(function(jqXHR, textStatus, error) {
var delay = 3000;
setTimeout(function() {
startRecords();
}, delay);
});
}
With comments
var currentRows = $("[id^=records-row-]").toArray() // get rows with id starting with "records-row-"
var currentRowsId = currentRows.map(function(row) { return row.id }) // extract ids from rows
var resRowsId = res.map(function(row) { return "records-row-" + row.id }) // extract ids from response that will be added to DOM
var removeRows = currentRowsId.filter(function(rowId) { return resRowsId.indexOf(rowId) === -1 }) // remove every element that is added to DOM and in response from server
removeRows.forEach(function(rowId) { $("#" + rowId).remove() }) // remove elements that are not in response and is added to DOM
Alternative solution
$("#records-content tbody").empty(); to remove every element each time the client fetches new data from server.
I have values that come from a dynamically created table from it's selected rows. inside each selected row i want all the td.innerText values that belong to be sent to a C# page, but i don't know how to. I was using JSON but I dont know if i used it properly.
function selectedRows()
{
var selectedItems = $('#ScannedLabelTable').find(':checkbox:checked').parents('tr');
var serial, kanbanNumber, customer, description, quantity;
$.each(selectedItems, function (i, item) {
var td = $(this).children('td');
for (var i = 0; i < td.length; ++i)
{
serial = td[1].innerText;
kanbanNumber = td[2].innerText;
customer = td[3].innerText;
description = td[4].innerText;
quantity = td[5].innerText;
}
console.log(serial + ' ' + kanbanNumber + ' ' + customer + ' ' + description + ' ' + quantity);
});
$.ajax({
url: SEND_TO_TEXTFILE_PAGE
, data: "labelSerial=" + serial + "&kanbanNumber=" + kanbanNumber + "&customer="
+ customer + "&description=" + description + "&quantity=" + quantity
, dataType: 'json'
, success: function (status) {
if (status.Error) {
alert(status.Error);
}
}
, error: Hesto.Ajax.ErrorHandler
});
}
EDIT: sorry I must have read this too quickly. This should do it. create an array and add the data object to it in the loop.
If you just create a json object using key value pairs you can send that object to your c# controller.
function selectedRows() {
var selectedItems = $('#ScannedLabelTable').find(':checkbox:checked').parents('tr');
var serial, kanbanNumber, customer, description, quantity;
var dataArray = new Array();
$.each(selectedItems, function (i, item) {
var td = $(this).children('td');
for (var i = 0; i < td.length; ++i)
{
var InfoObject = {
serial: td[1].innerText;
kanbanNumber: td[2].innerText;
customer: td[3].innerText;
description: td[4].innerText;
quantity: td[5].innerText;
};
dataArray.push(InfoObject);
}
});
$.ajax({
url: SEND_TO_TEXTFILE_PAGE
, data: dataArray
, dataType: 'json'
, success: function (status) {
if (status.Error) {
alert(status.Error);
}
}
, error: Hesto.Ajax.ErrorHandler
});
}
I've been trying to get this right for quite some time, I'm trying to append the object from the first ajax call after the second ajax call. But the for loop seems to iterate the changing of the value to the last result before appending the information, having the last post appended every time.
var scribjson =
{
"user_id" : localStorage.viewing,
};
scribjs = JSON.stringify(scribjson);
var scrib = {json:scribjs};
$.ajax({
type: "POST",
url: "getScribbles.php",
data: scrib,
success: function(result)
{
var obj = jQuery.parseJSON(result);
for(var i = 0; i < obj.length; i+=1)
{
var userjson =
{
"user_id" : obj[i].user_id
};
userjs = JSON.stringify(userjson);
var user = {json:userjs};
localStorage.post = obj[i].post;
$.ajax({
type: "POST",
url: "getRequestsInfo.php",
data: user,
success: function(result)
{
var obj2 = jQuery.parseJSON(result);
$('#listOfScribbles').append("<tr><td><img id = 'small_pic' src = '" + obj2[0].profileImage + "'/></td><tr><td>" + obj2[0].firstname + " " + obj2[0].lastname + "</td></tr> ");
$('#listOfScribbles').append("<tr><td>" + obj[i].post + "</td></tr>");
},
error: function()
{
alert('An Error has occured, please try again.');
}
});
}
},
error: function()
{
alert('An Error has occured, please try again.');
}
});
Since ajax calls It looks like the all success functions of the inner ajax call are being called after the loop has ended, so i will always be the last iterated value.
Try this:
(function(i)
{
$.ajax({
type: "POST",
url: "getRequestsInfo.php",
data: user,
success: function(result)
{
var obj2 = jQuery.parseJSON(result);
$('#listOfScribbles').append("<tr><td><img id = 'small_pic' src = '" + obj2[0].profileImage + "'/></td><tr><td>" + obj2[0].firstname + " " + obj2[0].lastname + "</td></tr> ");
$('#listOfScribbles').append("<tr><td>" + obj[i].post + "</td></tr>");
},
error: function()
{
alert('An Error has occured, please try again.');
}
});
})(i);
This will create a closure on i, which will give each ajax call its own copy of the current value.
Use an IIFE:
success: (function(i){return function(result) {
var obj2 = jQuery.parseJSON(result);
$('#listOfScribbles').append("<tr><td><img id = 'small_pic' src = '" + obj2[0].profileImage + "'/></td><tr><td>" + obj2[0].firstname + " " + obj2[0].lastname + "</td></tr> ");
$('#listOfScribbles').append("<tr><td>" + obj[i].post + "</td></tr>");
}})(i),
etc. Currently your loop generated ajax success handlers contain a direct reference to the counter itself, which (by the time they are called) has reached its final value.
I Am using the jquery below and witht he addition of .replace(",", " ") to the var video_tags=data.tags doesn't return a value. how can i replace the commas with spaces.
http://jsfiddle.net/hJGe4/1/
$(document).ready(function () {
$(".search_input").focus();
$(".search_input").keyup(function () {
$("#video").html('');
var search_input = $(this).val();
var keyword = encodeURIComponent(search_input);
var yt_url = 'http://gdata.youtube.com/feeds/api/videos?q=' + keyword + '&format=5&max-results=6&v=2&alt=jsonc';
$.ajax({
type : "GET",
url : yt_url,
dataType : "jsonp",
success : function (response) {
if (response.data.items) {
$.each(response.data.items, function (i, data) {
var video_title = data.title;
var video_tags = data.tags.replace(",", " ");
var final = video_title + '<br/>' + video_tags + '<br/><br/><br/>';
$("#video").append(final);
});
} else {
$("#video").html("<div id='no'>No Video</div>");
}
}
});
});
});
var video_tags=data.tags.replace(",", " ");
should be
var video_tags=data.tags.join(" ");
DEMO