I need help to write a if statement using jquery. So if results.d.ProductName is empty do not show `$(prdHtml).html(html);
$.ajax({
type: "POST",
url: "Services.asmx/GetProduct",
data: '{ "fieldName": "' + id + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(results) {
var html = '<h3>' + results.d.ProductName + '<h3>'
+ '<a href=""' + results.d.Url + '</a>';
$(prdHtml).html(html);
success: function(results) {
if(results.d.ProductName.length) {
var html = '<h3>' + results.d.ProductName + '<h3>'
+ '<a href=""' + results.d.Url + '</a>';
$(prdHtml).html(html);
} else {
$(prdHtml).hide();
}
}
try:
success: function(results) {
if (results.d.ProductName!="") {
var html = '<h3>' + results.d.ProductName + '<h3>'
+ '<a href=""' + results.d.Url + '</a>';
$(prdHtml).html(html);
}
}
success: function(results) {
// should probably test if d exists before testing for productname
if (typeof(results.d) == "undefined" || typeof(results.d.ProductName ) != "string")
return;
...code
}
Related
I am new to javascript and I jquery and I am trying to take the id of element and the value of the element.
So this is the first ajax request:
$.ajax({
type: "POST",
url: "Home/AddText",
data: JSON.stringify({ text: newText }),
contentType: "application/json",
success: function (result) {
idRow = result.id;
$("#myTable").append("<tr id = row" + idRow + "><td id = text>" +
result.text + "</td><td>" +
"<input type=checkbox id=checkbox onclick=CrossOut(" + idRow + ")>" + " " +
"<a class=btnEdit onclick=Edit(" + idRow + ")>Edit</a>" + " " +
//show this buttons only if the edit button is clicked
"<a class=btnSave onclick=Save(" + idRow + ")>Save</a>" + " " +
"<a class=btnCancel onclick=Cancel(" + idRow + ")>Cancel</a>" + " " +
"<a class=btnDelete onclick=Delete(" + idRow + ")>Delete</a>"
+ "</td> </tr>");
idRow++;
$(document).find('#text').attr('contenteditable', 'true');
$(document).find('.btnSave').hide();
$(document).find('.btnCancel').hide();
}
})
And this is the function:
function Save(idRow) {
var newText = $("#text").val();
console.log(newText);
$.ajax({
type: "POST",
url: "Home/Update",
data: JSON.stringify({ id: idRow, text: newText }),
contentType: "application/json",
success: function (result) {
$("#text").add(newText);
$(document).find('.btnSave').hide();
$(document).find('.btnCancel').hide();
$(document).find('.btnEdit').show();
}
})
}
So when I log the newText variable it doesn't display anything.
Since you are working with td you need to use .text()
var newText = $("#text").text();
Also note that you might have more than one unique id if you keep adding rows and the $(#text) would only get you the first one.
I have nested callabcks but resulted output is not ordered correctly. My ajax results are in ascending orders of id but html generated is random. can someone help me out pls?
var formatedhtml = '';
$.ajax({
type: "POST",
url: BASE_URL + 'index.php/orders/read',
dataType: 'json',
success: function(data) {
$.each(data, function(key, value) {
console.log(value);
getdetails(value['id'], function(output) {
formatedhtml = formatedhtml +
'<div class="col-md-4 col-sm-4 col-lg-3 col-xs-6">' +
' <div class="row">' +
' <div class="orderno">' + value['id'] + '</div>' +
'<div class="tableno">' + value['tableno'] + '</div>' +
'<div class="ordertype">' + value['type'] + '</div>' +
'<div class="timestamp">' + value['created'] + '</div>' +
' </div>' +
'<hr>';
$.each(JSON.parse(output['items']), function(k, val) {
formatedhtml = formatedhtml + '<div class="row">' +
'<div class="quantity">' + val[3] + '</div>' +
'<div class="item">' + '</div>' +
'</div>';
});
formatedhtml = formatedhtml +
'<div class="row">' +
'<div class="notes">' + value['id'] + '</div>' +
'</div>' +
'</div>';
$("#orderlist").html(formatedhtml);
console.log(output);
});
});
}
});
edit:
Here is getdetails function. its an ajax request.
function getdetails(id, callback) {
var result;
$.ajax({
type: "POST",
url: BASE_URL + 'index.php/orders/readdetails',
dataType: 'json',
data: {
id: id,
},
success: function(data) {
callback(data[0]);
}
});
};
There are a lot of ways to achieve this, one is to use a promise and sort by id when all requests are done. Another you could create the template and append the details on callback as each detail request has an id you can define in your template a class like 'id-'+value['id'] and use jquery selector and append detail template.
Another solution would be to create a function loop that calls itself untill orderCount == orderLoaded.
Job is done synchronously (takes more time)
//Mock ajax function
$.ajax = function (param) {
if(param.url.indexOf('readdetails') != -1){
param.success(itemsData);
} else {
param.success(ordersData);
}
};
//Mock data
var ordersData = [
{ id : 1, tableno : 'xyz', type: 'invoice', created: '01/01/2001' },
{ id : 2, tableno : 'xyz', type: 'invoice', created: '01/01/2001' },
{ id : 3, tableno : 'xyz', type: 'invoice', created: '01/01/2001' }
];
var itemsData = [
{ id : 1, orderid: 1, quantity: 5 },
{ id : 2, orderid: 1, quantity: 2 },
{ id : 3, orderid: 1, quantity: 1 }
];
// Globals
var formatedhtml = [];
var orders = [];
var lastOrderLoaded = 0;
var BASE_URL = 'localhost/';
function tpl(order, items) {
var html = '<tr class="col-md-4 col-sm-4 col-lg-3 col-xs-6">' +
' <td class="orderno">' + order['id'] + '</td>' +
'<td class="tableno">' + order['tableno'] + '</td>' +
'<td class="ordertype">' + order['type'] + '</td>' +
'<td class="timestamp">' + order['created'] + '</td>' +
' </tr>';
$.each(items, function(key, item) {
html += '<tr class="row">' +
'<td class="item">item: ' + item.id + '</td>' +
'<td class="quantity">quantity: ' + item.quantity + '</td>' +
'</tr>';
});
html +=
'<tr class="row">' +
'<td class="notes"> notes </td>' +
'<td class="notes"> order id ' + order['id'] + '</td>' +
'</tr>' +
'</tr>';
formatedhtml.push({ id: order.id, html : html });
}
$.ajax({
type: "POST",
url: BASE_URL + 'index.php/orders/read',
dataType: 'json',
success: function(data) {
lastOrderLoaded = 0;
orders = data;
getdetails(orders[0]);
}
});
function getdetails(order) {
$.ajax({
type: "POST",
url: BASE_URL + 'index.php/orders/readdetails',
dataType: 'json',
data: {
id: order.id,
},
success: function(data) {
tpl(order, data);
if(lastOrderLoaded < orders.length - 1){
lastOrderLoaded++;
getdetails(orders[lastOrderLoaded]);
} else {
formatedhtml.forEach(function(element){
$("#orderlist").append(element.html);
}); // end each
}
}
});
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="orderlist" border="1">
<tr><th>id</th><th>no</th><th>type</th><th>date</th></tr>
</table>
Promise Solution:
Job is done asynchronously (might take less time also bombards the server with many requests at once)
var formatedhtml = [];
function tpl(order, items) {
var html = '<div class="col-md-4 col-sm-4 col-lg-3 col-xs-6">' +
' <div class="row">' +
' <div class="orderno">' + order['id'] + '</div>' +
'<div class="tableno">' + order['tableno'] + '</div>' +
'<div class="ordertype">' + order['type'] + '</div>' +
'<div class="timestamp">' + order['created'] + '</div>' +
' </div>' +
'<hr>';
$.each(JSON.parse(items['items']), function(key, item) {
var html += '<div class="row">' +
'<div class="quantity">' + item[3] + '</div>' +
'<div class="item">' + '</div>' +
'</div>';
});
html +=
'<div class="row">' +
'<div class="notes">' + order['id'] + '</div>' +
'</div>' +
'</div>';
formatedhtml.push({ id: order.id, html : html });
}
$.ajax({
type: "POST",
url: BASE_URL + 'index.php/orders/read',
dataType: 'json',
success: function(data) {
var syncLoad = [];
$.each(data, function(key, value) {
syncLoad.push(getdetails(value, tpl));
});
$.when.apply($, syncLoad).done(function() {
formatedhtml.sort(function(a, b){
return a.id - b.id;
});
formatedhtml.forEach(function(element){
$("#orderlist").append(element.html);
});
});
}
});
function getdetails(order, callback) {
return $.ajax({
type: "POST",
url: BASE_URL + 'index.php/orders/readdetails',
dataType: 'json',
data: {
id: order.id,
},
success: function(data) {
callback(order, data[0]);
}
});
};
Use async:false in your getDetails() ajax call.
function getdetails(id, callback) {
var result;
$.ajax({
type: "POST",
url: BASE_URL + 'index.php/orders/readdetails',
dataType: 'json',
async: false,
data: {
id: id,
},
success: function (data) {
callback(data[0]);
}
});
Actually i got alert message display before saving data so please help me out
below my code is there
for (var i = 0; i < rows_count; i++) {
var count = 0;
$.ajax({
type: "POST", url: "Default.aspx/update_extraHoursWorked", cache: false, data: "{'empID':'" + $("#emp_id" + i).text() + "','emp_code': '" + $("#emp_code" + i).text() + "','emp_category':'" + $("#emp_category" + i).text() + "','g1': '" + $("#txtgen_Three" + i).val() + "','f1': '" + $("#txtfirst_Three" + i).val() + "','s1': '" + $("#txtsecond_Three" + i).val() + "','t1': '" + $("#txtthrid_Three" + i).val() + "','g2': '" + $("#txtgen_Four" + i).val() + "','f2': '" + $("#txtfirst_Four" + i).val() + "','s2': '" + $("#txtsecond_Four" + i).val() + "','t2': '" + $("#txtthrid_Four" + i).val() + "','g3': '" + $("#txtgen_Five" + i).val() + "','f3': '" + $("#txtfirst_Five" + i).val() + "','s3': '" + $("#txtsecond_Five" + i).val() + "','t3': '" + $("#txtthrid_Five" + i).val() + "','contracortName': '" + $('#ddlContractorNames>option:selected').text() + "'}", contentType: "application/json; charset=utf-8", dataType: "json",
success: function (data) { }, error: function (e) { alert('Error, Update att.'); }
});
} enableLastTwoDays(true);
alert('Saved Successfully');
}
You can count every success and finally alert ..
count_success= 0;
for (var i = 0; i < rows_count; i++) {
//---
//--
success: function (data) { count_success++; },
error: function (e) { alert('Error, Update att.'); }
});
} enableLastTwoDays(true);
alert(count_success +'Record Saved Successfully');
}
Try this, the alert should be within the success function, which is called if the ajax request was successful. You can also get the response data from server within this the success function. Try console.log(data) to display data in the browser console if data is returned from the server.
for (var i = 0; i < rows_count; i++) {
var count = 0;
$.ajax({
type: "POST", url: "Default.aspx/update_extraHoursWorked", cache: false, data: "{'empID':'" + $("#emp_id" + i).text() + "','emp_code': '" + $("#emp_code" + i).text() + "','emp_category':'" + $("#emp_category" + i).text() + "','g1': '" + $("#txtgen_Three" + i).val() + "','f1': '" + $("#txtfirst_Three" + i).val() + "','s1': '" + $("#txtsecond_Three" + i).val() + "','t1': '" + $("#txtthrid_Three" + i).val() + "','g2': '" + $("#txtgen_Four" + i).val() + "','f2': '" + $("#txtfirst_Four" + i).val() + "','s2': '" + $("#txtsecond_Four" + i).val() + "','t2': '" + $("#txtthrid_Four" + i).val() + "','g3': '" + $("#txtgen_Five" + i).val() + "','f3': '" + $("#txtfirst_Five" + i).val() + "','s3': '" + $("#txtsecond_Five" + i).val() + "','t3': '" + $("#txtthrid_Five" + i).val() + "','contracortName': '" + $('#ddlContractorNames>option:selected').text() + "'}", contentType: "application/json; charset=utf-8", dataType: "json",
success: function (data) { alert('Saved Successfully'); }, error: function (e) { alert('Error, Update att.'); }
});
} enableLastTwoDays(true);
}
The modified code is below, the below code is to give u an idea, ideally this code should not be used in your production site as such. Here for every row that is successfully saved the save function is called which inturn increases the count of the count_successful. After the loop is completed the count of count_successful is checked if its equal to the row count
var count_successful = 0;
for (var i = 0; i < rows_count; i++) {
var count = 0;
$.ajax({
type: "POST", url: "Default.aspx/update_extraHoursWorked", cache: false, data: "{'empID':'" + $("#emp_id" + i).text() + "','emp_code': '" + $("#emp_code" + i).text() + "','emp_category':'" + $("#emp_category" + i).text() + "','g1': '" + $("#txtgen_Three" + i).val() + "','f1': '" + $("#txtfirst_Three" + i).val() + "','s1': '" + $("#txtsecond_Three" + i).val() + "','t1': '" + $("#txtthrid_Three" + i).val() + "','g2': '" + $("#txtgen_Four" + i).val() + "','f2': '" + $("#txtfirst_Four" + i).val() + "','s2': '" + $("#txtsecond_Four" + i).val() + "','t2': '" + $("#txtthrid_Four" + i).val() + "','g3': '" + $("#txtgen_Five" + i).val() + "','f3': '" + $("#txtfirst_Five" + i).val() + "','s3': '" + $("#txtsecond_Five" + i).val() + "','t3': '" + $("#txtthrid_Five" + i).val() + "','contracortName': '" + $('#ddlContractorNames>option:selected').text() + "'}", contentType: "application/json; charset=utf-8", dataType: "json",
success: function (data) { count_successful = count_successful+1; }, error: function (e) { alert('Error, Update att.'); }
});
} enableLastTwoDays(true);
}
if(count_successful == rows_count){
alert('Saved all rows successfully');
}
Have a hidden field respective to this function and increment/change the value of it on each success. Finally if the successCount value equals the total rows count, then the alert is shown.
function someFunction() {
for (var i = 0; i < rows_count; i++) {
var count = 0;
$.ajax({
type : "POST",
url : "Default.aspx/update_extraHoursWorked",
cache : false,
data : "{}",
contentType : "application/json; charset=utf-8",
dataType : "json",
success : function(data) {
$('#successCountID').val(i); // changed i+1 to i
},
error : function(e) {
alert("Error, Update att.");
}
});
}
enableLastTwoDays(true);
$(document).ajaxStop(function() {
// place code to be executed on completion of last outstanding ajax call here
var count = $('#successCountID').val();
if (count == rows_count) {
alert("Saved Successfully");
$('#successCountID').val(0);
}
});
}
Add a hidden field in the form
<input type="hidden" name="successCount" id="successCountID" value="0">
Code:
function fillChooseCompInAddDeviceDiv(){
$.ajax({
url: "${pageContext.request.contextPath}/StoreServlet",
type: "get",
data: {ajaxId: "2"},
dataType: "json",
success: function(data) {
$("table#choseComponentAddDeviceDiv").find("td").remove();
for(var i = 0; i<data.length; i++) {
$("table#choseComponentAddDeviceDiv").append("<tr>" + "<td>" + data[i].name + "</td>" + "<td>" + data[i].price + "</td>" + "<td>" + data[i].amount + "</td>" + "<td>" + data[i].description + "</td>" + "<td>" + data[i].categoryName + "</td>" + "<td>" + "<a href='" + data[i].link + "'>" + data[i].link + "</a>" + "</td>" + "<td>" + "<img src = '" + data[i].imagePath + "' />" + "</td>" + "<td>" + "<input type='checkbox' class='checkBoxCol' value='" + data[i].name + "'>" + "</td>" + "</tr>");
}
alert("ALERT 1");
},
error: function(status) {
//Do something
}
});
}
//any edit clicked in eny table
function anyEditOnCLick(buttonId, buttonVal){
window.editIsClicked = true;
$("input.nameInput").attr("readonly", true);
if (buttonId === "device"){
$("#addDeviceDiv").css("visibility", "visible");
window.location.hash = "#addDeviceDiv";
fillChooseCompInAddDeviceDiv();
$.ajax({
url: "${pageContext.request.contextPath}/StoreServlet",
type: "get",
data: {ajaxId: "11", toEdit: buttonVal},
dataType: "json",
success: function(data) {
// puni text area
$("#addDeviceFieldName").val(data.name);
$("#addDeviceFieldDescription").val(data.description);
// cekira odgovarajuce komponente, jedan samo data se ocekuje, ne data[]
//fillChooseCompInAddDeviceDiv();
for (var i = 0; i<data.components.length; i++){
$("table#choseComponentAddDeviceDiv td input").filter(function(){return this.value == data.components[i].name}).attr("checked", true);
}
alert("ALERT 2");
},
error: function(status) {
//Do something
}
});
//name is unique - cannot be changed
$("#addDeviceDiv input#addDeviceFieldName").attr("readonly", true);
} else if (buttonId === "component"){
$("#addComponentDiv").css("visibility", "visible");
window.location.hash = "#addComponentDiv";
fillCategorySelection();
$.ajax({
url: "${pageContext.request.contextPath}/StoreServlet",
type: "get",
data: {ajaxId: "21", toEdit: buttonVal},
dataType: "json",
success: function(data) {
$("#addComponentFieldName").val(data.name);
$("#addComponentFieldPrice").val(data.price);
$("#addComponentFieldAmount").val(data.amount);
$("#addComponentFieldDescription").val(data.description);
$("#addComponentFieldLink").val(data.link);
$("#form#uploadForm #imageFile").attr("value", data.imagePath);
//fillCategorySelection();
$("#addComponentDiv select.categorySelect option").filter(function(){return this.value == data.categoryName}).attr("selected", "selected");
},
error: function(status) {
//Do something
}
});
//name is unique - cannot be changed
$("#addComponentDiv input#addComponentFieldName").attr("readonly", true);
} else if (buttonId === "category"){
$("#addCategoryDiv").css("visibility", "visible");
window.location.hash = "#addCategoryDiv";
fillChoseSubCategoriesinAddCategoriesDiv();
$.ajax({
url: "${pageContext.request.contextPath}/StoreServlet",
type: "get",
data: {ajaxId: "31", toEdit: buttonVal},
dataType: "json",
success: function(data) {
$("#addCategoryFieldName").val(data.name);
$("#addCategoryFieldDescription").val(data.description);
//fillChoseSubCategoriesinAddCategoriesDiv();
for (var i = 0; i<data.subCategories.length; i++){
$("table#choseSubCategoriesinAddCategoriesDiv td input").filter(function(){return this.value == data.subCategories[i].name}).attr("checked", true);
}
},
error: function(status) {
//Do something
}
});
//name is unique - cannot be changed
$("#addCategoryDiv input#addCategoryFieldName").attr("readonly", true);
}
}
Function anyEditOnCLick(arg1, arg2) is event function and is placed in onClick tag of a button.
When I click on this button browser always first shows ALERT 2 message and after that go execute fillChooseCompInAddDeviceDiv() and shows ALERT 1. Can someone explain what is really happend here and how can I "persuade" javascript first execute fillChooseCompInAddDeviceDiv()? Before this, i thought function call provides executing whole function body before resuming execution of outer code.
I would like to post the variable var projectid=data.projectid, the same as i did with:
url: "rapportage/rapport_detail?idKlant=" + klant,
the ajax call look like this:
$.ajax({
type: "POST",
url: "rapportage/rapport_detail?idKlant=" + klant,
dataType: 'json',
error: function(){ alert("Onvoldoende gegevens beschikbaar om rapportage to genereren."); },
success: function(data){ // Plaats data op de juiste plek in de tabel
var projectid=data.projectid,
titel=data.titel,
projecttype =data.projecttype,
projectleider =data.projectleider,
projecttype =data.projecttype,
statusproject =data.statusproject,
startproject =data.startproject,
deadlineproject =data.deadlineproject,
omzetproject =data.omzetproject,
kostenproject =data.kostenproject,
margeproject =data.margeproject,
totaalurenproject =data.totaalurenproject,
totaalminutenproject =data.totaalminutenproject,
urenkostenproject =data.urenkostenproject;
var str='';
for(var i=0,len=titel.length;i<len;i++){
str+="<tr>"+"<td>" + titel[i] + "</td>";
str+="<td>" + projectleider[i] + "</td>";
str+="<td>" + projecttype[i] + "</td>";
str+="<td>" + statusproject[i] + "</td>";
str+="<td>" + startproject[i] + "</td>";
str+="<td>" + deadlineproject[i] + "</td>";
str+="<td>" + "€" + omzetproject + "</td>";
str+="<td>" + "€" + kostenproject + "</td>";
str+="<td>" + "€" + margeproject + "</td>";
str+="<td>" + totaalurenproject + ":" + totaalminutenproject + "</td>";
str+="<td>" + "€" + urenkostenproject + "</td>"+"</tr>";
}
alert(JSON.stringify(data));
$("#details tbody").append(str);
}
});
You can use this;
$.ajax({
type: "POST",
url: "rapportage/rapport_detail?idKlant=" + klant,
dataType: 'json',
success: function(data) {
var projectid=data.projectid;
........
$.ajax({
type: "POST",
url: "rapportage/rapport_detail?idKlant=" + klant,
data: "projectid=" + projectid,
dataType: 'json',
success: function(response) {
}
}
.....
i didn't get what you are asking, but if you want to post a variable by POST then you can
type: "POST",
url: "rapportage/rapport_detail",
data : {"idKlant" : klan},
add this in ajax