I have this code that adds value to different parts of my html page based on the ID of that element,
the code works perfectly no issue but what I'm looking for is a better and efficient solution to replace all the getelementbyid feature, if there is one of course
which mean if there is another methode to reduce the size of the code below and change it with another one
my code is below :
$('#public-event').modal('show');
$.ajax({
type: 'GET',
dataType: 'json',
url: '/envoi/update/' + id,
})
.done(function (data) {
var html = ""
console.log(data);
for (let i = 0; i < data.length; i++) {
if (id === data[i].events._id) {
console.log(data[i].events.title)
document.getElementById("title").innerHTML = data[i].events.title;
document.getElementById("eventDateTime").innerHTML = `${data[i].events.eventDate} at ${data[i].events.targetReminder} | ${data[i].events.targetAmPM}`;
document.getElementById("createBy").innerHTML = data[i].events.author;
document.getElementById("dateCreation").innerHTML = data[i].events.author;
document.getElementById("description").innerHTML = data[i].events.caption;
document.getElementById("pubpriv").innerHTML = data[i].events.category;
document.getElementById("location").innerHTML = data[i].events.location;
$('#monImage').attr('src', 'img/sam.jpg');
$('#eventImage').attr('src', 'uploads/' + data[i].events.img);
document.getElementById("deleteButtn").setAttribute('data-id', data[i].events._id);
document.getElementById("completeButtn").setAttribute('data-id', data[i].events._id);
document.getElementById("CommentButtn").setAttribute('data-id', data[i].events._id);
document.getElementById("CommentButtn").setAttribute('data-content', data[i].events.author);
document.getElementById("likeButton").setAttribute('data-id', data[i].events._id);
document.getElementById("likeButton").setAttribute('data-content', data[i].events.author);
document.getElementById("showComment").setAttribute('data-id', data[i].events._id);
document.getElementById("comment-number").innerHTML = data[i].events.comments.length +' Comments';
//to modify imges with dynamic
}
Thank you for any suggestion,
Best Regards,
Your code comprises of both native JS and jQuery, native being the more verbose. jQuery's own slogan is: "write less, do more" – so that's one note to take away from. But also, some elements require a particular type of formatting, so this shouts for explicit statements. You could also combine the repetitive values into one statement.
$('#title').text(data[i].events.title)
$('#eventDateTime').text(`${data[i].events.eventDate} at ${data[i].events.targetReminder} | ${data[i].events.targetAmPM}`)
$('#createBy, #dateCreation').text(data[i].events.author)
$('#description').text(data[i].events.caption)
$('#pubpriv').text(data[i].events.category)
$('#location').text(data[i].events.location)
$('#monImage').attr('src', 'img/sam.jpg')
$('#eventImage').attr('src', 'uploads/' + data[i].events.img)
$('#deleteButtn, #completeButtn, #CommentButtn, #likeButton, #showComment').attr('data-id', data[i].events._id)
$('#CommentButtn, #likeButton').attr('data-content', data[i].events.author)
$('#comment-number').text(`${data[i].events.comments.length} Comments`)
It's also noteworthy to make use of .text over .html if your values are genuinely just text and do not contain HTML. Otherwise, no harm in replacing with .html.
Related
I am currently working on a combo offer on NopCommerce. So I need to add multiple product to cart at a single click. The built in NopCommerce format is for adding single product into cart is
AjaxCart.addproducttocart_catalog('/addproducttocart/catalog/' + productId + '/1/1'
and
AjaxCart.addproducttocart_details('/addproducttocart/details/' +productId + '/1', '#product-details-form')
Both of them work fine for adding single product. But when I want to add multiple product then the it just add single product to the cart. Mention that I am sending a string with a coma separative value which is list of products and inside Javascript it is parsing as a single prodcut Id. However, it is adding only single product in the cart. Which Product Id is the the lowest that product is adding to the cart.
Here is my piece of javascript code
function addComboProductToCart(ids) {
var arrayOfStrings = ids.split(',');
for (var i = 0; i < arrayOfStrings.length; i++) {
AjaxCart.addproducttocart_catalog('/addproducttocart/catalog/' + arrayOfStrings[i] + '/1/1');
}
}
But it is not showing a single error too. So where is the problem?
At the first you need to change in public.ajaxcart.js as below as there is an ajax call on every Add to Cart we need to set it async:false for this you have to add a parameter called async for more clear take a look at below code
//add a parameter async
addproducttocart_catalog: function (urladd,async) {
if (this.loadWaiting != false) {
return;
}
this.setLoadWaiting(true);
$.ajax({
cache: false,
async:async,
url: urladd,
type: 'post',
success: this.success_process,
complete: this.resetLoadWaiting,
error: this.ajaxFailure
});
},
Now i have modified your function by addding just a parameter false
function addComboProductToCart(ids) {
var arrayOfStrings = ids.split(',');
for (var i = 0; i < arrayOfStrings.length; i++) {
AjaxCart.addproducttocart_catalog('/addproducttocart/catalog/' + arrayOfStrings[i] + '/1/1',false);
}
}
To know what async:false is doing kindly find this answer as well for more clarification
Let me know if you need any further assistance.
I am Using iQuery to make AJAX Calls to the server and return a set of values. The Values returned are dynamic. The Result count being dynamic I am not able to look the result set and assign values to HTML Elements to show in Web Page.
Kindly advice how I could look if there is a value in the result set and use the same in my system. The Maximum count in result set is 16 and i have manually assigned values in the Script.
Calling the AJAX Method in the document ready of my Web Page.
$(document).ready(function () {
CallAJAX('../Forms/Send.aspx/refreshDash', '', 'FillMethod', 'FillMethodE');
});
AJAX Call Definition
function CallAJAX(ServerMethod, Parameters, SuccessMethod, ErrorMethod) {
$.ajax({
type: "POST",
url: ServerMethod,
data: Parameters,
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (xhr, status, errorThrown) {
Error = xhr; Result.d.ResultSet[0].TRCOUNT
eval(ErrorMethod + "()");
},
success: function (msg) {
Result = msg;
var rr = SuccessMethod + "();";
eval(rr);
}
});
}
Using Two jQuery Functions to Show Details and prompt Message when error is Raised. Note Error Function is not Shown.
function FillMethod() {
if ($.isEmptyObject(Result.d.ResultSet)) {
}
else {
$('[id$=lblCode1]').html(Result.d.ResultSet[0].DASH_NAME);
$('[id$=lblNot1]').html(Result.d.ResultSet[0].TRCOUNT);
$('[id$=lblCode2]').html(Result.d.ResultSet[1].DASH_NAME);
$('[id$=lblNot2]').html(Result.d.ResultSet[1].TRCOUNT);
$('[id$=lblCode3]').html(Result.d.ResultSet[2].DASH_NAME);
$('[id$=lblNot3]').html(Result.d.ResultSet[2].TRCOUNT);
$('[id$=lblCode4]').html(Result.d.ResultSet[3].DASH_NAME);
$('[id$=lblNot4]').html(Result.d.ResultSet[3].TRCOUNT);
$('[id$=lblCode5]').html(Result.d.ResultSet[4].DASH_NAME);
$('[id$=lblNot5]').html(Result.d.ResultSet[4].TRCOUNT);
$('[id$=lblCode6]').html(Result.d.ResultSet[5].DASH_NAME);
$('[id$=lblNot6]').html(Result.d.ResultSet[5].TRCOUNT);
$('[id$=lblCode7]').html(Result.d.ResultSet[6].DASH_NAME);
$('[id$=lblNot7]').html(Result.d.ResultSet[6].TRCOUNT);
$('[id$=lblCode8]').html(Result.d.ResultSet[7].DASH_NAME);
$('[id$=lblNot8]').html(Result.d.ResultSet[7].TRCOUNT);
$('[id$=lblCode9]').html(Result.d.ResultSet[8].DASH_NAME);
$('[id$=lblNot9]').html(Result.d.ResultSet[8].TRCOUNT);
$('[id$=lblCode10]').html(Result.d.ResultSet[9].DASH_NAME);
$('[id$=lblNot10]').html(Result.d.ResultSet[9].TRCOUNT);
$('[id$=lblCode11]').html(Result.d.ResultSet[10].DASH_NAME);
$('[id$=lblNot11]').html(Result.d.ResultSet[10].TRCOUNT);
$('[id$=lblCode12]').html(Result.d.ResultSet[11].DASH_NAME);
$('[id$=lblNot12]').html(Result.d.ResultSet[11].TRCOUNT);
$('[id$=lblCode13]').html(Result.d.ResultSet[12].DASH_NAME);
$('[id$=lblNot13]').html(Result.d.ResultSet[12].TRCOUNT);
$('[id$=lblCode14]').html(Result.d.ResultSet[13].DASH_NAME);
$('[id$=lblNot14]').html(Result.d.ResultSet[13].TRCOUNT);
$('[id$=lblCode15]').html(Result.d.ResultSet[14].DASH_NAME);
$('[id$=lblNot15]').html(Result.d.ResultSet[14].TRCOUNT);
$('[id$=lblCode16]').html(Result.d.ResultSet[15].DASH_NAME);
$('[id$=lblNot16]').html(Result.d.ResultSet[15].TRCOUNT);
}
};
function FillMethodE() {
}
Issue is being raised in the FillMethod function when only Result.d.ResultSet[0].DASH_NAME has a valid value and the following indexes does not have any values.
NOTE: Results are returned in pairs, if DASH_NAME is available then TRCOUNT will also be available for the same index.
All I need to do is irrespective of the result count i need to display in the labels in order values from the result set dynamically. Here are are two sets of result sets which could be obtained.
I'm afraid it's still really, really unclear what the specific problem is (and the sample result sets you posted don't provide any clarity on why you can't simply loop over them), but I'm willing to take a guess...
Is the problem that you're trying to write a dynamic set of results to a static set of placeholders for the output?
If that's the case, don't make the placeholders static. Just keep an empty space where you want the results to show and when you have the results, write them to that part of the page. You don't need HTML elements in place already, you can create them dynamically. For example:
success: function (msg) {
// let's assume msg is an array of data
for(var i = 0; i < msg.lengh; i++) {
$('#output').append(
'<div>' + msg[i].DASH_NAME + ' - ' + msg[i].DASHSTATUS + '</div>'
);
}
}
So if your #output is just a div, the result would look like this:
<div id="output">
<div>SEND CONFIRMED - 1</div>
<div>RECV HO RESPONDED - 4</div>
<div>RECV HO PAID - 3</div>
<!-- etc... -->
</div>
How you define and style that markup is entirely up to you, of course. The point is that you can create the markup on the fly from your JavaScript code, so it can be created dynamically based on the results from the AJAX request.
Try this
if (Result.d.ResultSet.length > 0) {
for (i = 0; i < Result.d.ResultSet.length; i++) {
$('[id$=lblCode'+i+']').html(Result.d.ResultSet[i].DASH_NAME);
$('[id$=lblNot1'+i+']').html(Result.d.ResultSet[i].TRCOUNT);
}
I have a AJAX response something like this.
[{"label":"label","label1":"67041","label2":"745","label3":"45191","label4":"11464"}]<table id="table"></table>
It has both JSON and HTML in the response.
I wanted to separate those two things.
And use the JSON for a chart function I've created.
And then append that table to a div.
Any suggestions will be very much fruitful.
Thanks in advance.
In php
$array = 'Your json array';
$html = 'Your html codes';
Make a single array with two keys
$newArray = array();
$newArray['json'] = $array;
$newArray['html'] = $html;
echo json_encode($newArray);
In Jquery
DataType: 'JSON',
success:function(response){
response.json = 'This is your json';
response.html = 'This is your html';
}
Add the HTML to the JSON response and use it like you would your other values (make sure to escape your html). Also use JSONLint to make sure your JSON is valid.
[
{
"label": "label",
"label1": "67041",
"label2": "745",
"label3": "45191",
"label4": "11464",
"html": "<table id=\"table\"></table>"
}
]
While I recommend you not to do that, because is to geeky and hard to maintain, You can solve id by detecting the JSON object using regex, like this:
var data = '[{"label":"label","label1":"67041","label2":"745","label3":"45191","label4":"11464"}]<table id="table"></table>';
var json_pattr = /\[.*\]/g;
var json_str = json_pattr.exec(data)[0];
var json_data = eval( '(' + json_str.substr(1, json_str.length-2) + ')') ;
var html_pattr = /\}\].*/g;
var html_text = html_pattr.exec(data)[0];
var html_data = html_text.substr(2);
//json_data = [object] {"label":"label","label1":"67041","label2":"745","label3":"45191","label4":"11464"}
//html_data = [text] <table id="table"></table>
The Best Solution would be to use a template engine like jquery templates to define your html, and then get your data via $.json and evaluate it agains your desired template already on the client, no need to be sending it right along with your data and be doing that kind of processing in run time.
JavaScript
// assuming you keep receiving this
var data =
'[{"label":"label","label1":"67041","label2":"745","label3":"45191","label4":"11464"},'
+'{"label":"label2","label1":"0000","label2":"222","label3":"333","label4":"11333"}]'
+'<table id="table"></table>';
// parse the data with regex
var json_pattr = /\[.*\]/g;
var json_str = json_pattr.exec(data)[0];
var json_data = eval( '(' + json_str + ')') ;
var html_pattr = /\}\].*/g;
var html_text = html_pattr.exec(data)[0];
var html_data = html_text.substr(2);
//json_data = [object] {"label":"label","label1": ...
//html_data = [text] <table id="table"></table> ...
// then use jquery templates to render it
var data = json_data;
$('body').append(html_data);
$('#trTemplate').tmpl(data).appendTo('#table');
HTML
<script id="trTemplate" type="text/x-jquery-tmpl">
<tr>
<td>${label}</td>
<td>${label1}</td>
<td>${label2}</td>
<td>${label3}</td>
<td>${label4}</td>
</tr>
</script>
CSS
#table, td{ border:1px solid #000; padding:5px; }
Here is an working JSFiddle example for you to test it.
Note how this works when you have more than one {json object, it's creates more lines in the table :) }
If you use jquery templates only, and now assuming that you can actually modify your output than the best thing to do is:
New JavaScript Version of Code with template only and no HTML on 'data'
$.json('http://server.com/url/service/someservice.something', function(data){
$('body').append(<table id="#table></table>");
$('#trTemplate').tmpl(data).appendTo('#table');
})
Much more simple don't you think?! Hope this helps guiding you on the right path.
Link to jquery tmpl: http://knockoutjs.com/downloads/jquery.tmpl.min.js.
Although after understanding my example, if you are building a system to scale on, and you are not just doing a simple widget app, I would recommend you to check something more robust in terms of functionalities and support like Knockoutjs as jquery tmpl has been deprecated, unfortunately.
I have found the #Olegs answer for FORM based select2 integration to jQgid, but I need help to get it to work in inline mode,, this jsfiddle is my attempt to get my problem online somehow I'm new with fiddle so please be patient :)
http://jsfiddle.net/mkdizajn/Qaa7L/58/
function(){ ... } // empty fn, take a look on jsfiddle
On this fiddle I can't make it to work to simulate the issue I have in my local network but the problem with this select2 component is that when I update some record(via local or ajax), the grid does not pick up my change and it sends null for values where select2 fields are!
I'm sorry that I can't make jsfiddle to work like on my PC :(
Thanks for any help you can think off that may be the issue here..
P.S. one veeeery strange thing is that when I console.log( select2-fields ), before, and after the value is picked up correctly but I suspect that the grid loose that value somewhere in between .. and send null values to server..
I'm posting this in a good will that I think will help anyone if come to close incounter with similar problem like me..
I'll try to bullet this problem out step by step..
first, on my server side I generate one html tag somewhere near grid table that holds info what columns, fields are lookup type.. like this:
<div id="hold_lookup_<?=$unique_id?>" style="display: none"><?php echo $lokki; ?></div>
that gives me output like this:
<div id="hold_lookup_table1" style="display: none">col1+++col2+++col3</div>
define onselectrow event somewhere
$onSelectRow = "function(){
f = $(this).attr('id'); // grid name
try{
n = $('#hold_lookup_' + f).text().split('+++');
}catch(e){
console.log(e)
}
rez = ''; // results
temp = 'textarea[name='; // template
$.each(n, function(index, item){
rez += temp + item + '],'
});
rez = rez.slice(0,-1); // rezemo zadnji zarez
$( rez ).select2({ .. define my ajax, my init etc.. });
}";
$dg->add_event("jqGridInlineEditRow", $onSelectRow);
last but very tricky part is here.. I destroy select2 columns before sending to database in jqgrid.src file where function for SAVE inline method is.. like this
if (o.save) {
$($t).jqGrid('navButtonAdd', elem, {
caption: o.savetext || '',
title: o.savetitle || 'Save row',
buttonicon: o.saveicon,
position: "first",
id: $t.p.id + "_ilsave",
onClickButton: function() {
var sr = $t.p.savedRow[0].id;
rez = rez.split(',');
rez1 = '';
$.each(rez, function(index, item) {
rez1 += item + ','
})
rez1 = rez1.slice(0, -1);
rez1 = rez1.split(',');
$.each(rez1, function(index, item) {
$(item).select2('destroy');
});
you can see that I inserted the code onclickbutton event via same 'rez' variable that was defined in my php file where I created grid..
That's it, I hope that helped someone, event if not in this particular problem, but with methods that was used here :)
cheers, kreso
I am fetching some json and returning it out, creating a new div for each object. I am now trying to add one final div (not from json) that just says something along the lines of 'This could be yours!'.
I have tried to insert
$('section#fans').append('<div class="fan">new div</div>');
or several variations of that (after, appendChild etc) and cannot get it to perform as i wish. Currently it adds one new div but before the foreach kicks in and it doesn't follow the fadeIn delay pattern that for the foreach does.
How can i get it to add the div with the same effect after the foreach. as one final div? As if it belonged to the json, altough it wont be the same template as the previous.
function get_fans(){
$.ajax('http://localhost/facebook_app/selectFans/', {
type : 'get',
dataType: 'json',
success : function (data) {
$.each(data, function(index) {setTimeout(function(){
var first_name = data[index].first_name;
var location = data[index].location;
var imagePath = data[index].image_path;
var d = $('<div class="fan"><img src="http://localhost/uploads/' + imagePath + '" width="170" height="160" />' + first_name + ', ' + location +'</div>');
$('section#fans').append(d);
d.hide();
d.fadeIn('50');
}, 250*(index +1));
});
$('section#fans').append('<div class="fan">new div</div>');
},
});
}
Your "final" insert is done immediately, while the other ones are done after a timeout.
You could replace
$('section#fans').append('<div class="fan">new div</div>');
with
setTimeout(function(){
$('#fans').append('<div class="fan">new div</div>');
}, 250*(data.length +2));
so that the final insert would be done after all others have been done.
A side note : don't use $('section#fans') but $('#fans'). This will be faster as jQuery will use the fast document.getElementById function.