Cannot get the substring of a String in JavaScript - javascript

I am trying to get the substring from a variable when the content length is longer than 120 chars.
$.ajax({
url: url,
dataType: 'json',
async: false,
success: function(data){
$.each(data, function(i, item) {
var name = item.name;
var itemId = item.itemId;
if(name.length >= 120) {
selectHTML += '<option value=' + itemId + '>' + name.substr(0, 120) + '</option>';
} else {
selectHTML += '<option value=' + itemId + '>' + name + '</option>';
}
});
}
});
But as a result, I always get this:
name is undefined
When I do it without substring(), it works without problems. Any suggestions?
Edit:
Error is thrown on this line:
if(name.length >= 120) {

Try changing if (name.length >= 120) to if (name && name.length >= 120)

The error means that one of the items does not contain a name.
Use console.log(data) to figure out what you actually receive - nothing is wrong with your JavaScript code.
If you cannot change the server-side code, you could fallback to an empty name:
var name = item.name || '';

Related

How to modify javascript to have html result instead of show out the html code in a comment system?

Currently,
when i input test,
the comment system directly show my typing, "test"
Modify to,
I would like the modify the javascript code that when i input test,
it convert to html result "test" (a hyperlink to "#").
How can i modify following code? Many thanks!
function fetchComments(leaveRequestId) {
$('#existingComments').html(lang_Loading);
params = 'leaveRequestId=' + leaveRequestId;
$.ajax({
type: 'GET',
url: getCommentsUrl,
data: params,
dataType: 'json',
success: function(data) {
var count = data.length;
var html = '';
var rows = 0;
$('#existingComments').html('');
if (count > 0) {
html = "<table class='table'><tr><th>" + lang_Date + "</th><th>" + lang_Time + "</th><th>" + lang_Author + "</th><th>" + lang_Comment + "</th></tr>";
for (var i = 0; i < count; i++) {
var css = "odd";
rows++;
if (rows % 2) {
css = "even";
}
var comment = $('<div/>').text(data[i]['comments']).html();
html = html + '<tr class="' + css + '"><td>' + data[i]['date'] + '</td><td>' + data[i]['time'] + '</td><td>' +
data[i]['author'] + '</td><td>' + comment + '</td></tr>';
}
html = html + '</table>';
} else {
}
$('#existingComments').append(html);
}
});
}
<div id="existingComments">
<span><?php echo __('Loading') . '...';?></span>
</div>
var comment = $('<div/>').text(data[i]['comments']).html();
You're explicitly escaping the data from the Ajax request so that it shows up as text and isn't treated as HTML source code.
If you don't want to do that, then just don't do it!
(Do be careful not to expose yourself to stored XSS attacks though)
$('#existingComments').html(html);

JQuery : How to add list of objects in Ajax

It's one of my first time I using JQuery/AJAX and I would like to get your help in order to give a list of objects in my dropdown field.
I have this function :
function get_sub_method_options(keep_cur) {
var sel_option = $('select#id_method-group').find("option:selected");
var sel_val = sel_option.val();
console.log(sel_val);
if (sel_val === '') {
console.log('none sorting group');
$("select#id_method-sub_method").empty();
$("select#id_method-sub_method").append('<option value=""> test </option>'); //here add list of all submethods
return;
}
data = {
'test_method': $('select#id_method-test_method').find("option:selected").val(),
'group': sel_val
};
$.ajax({
method: "GET",
url: '{% url 'ajax_method_submethod' %}',
data: data
}).done(function (result) {
reset_select('id_method-sub_method');
for (var i = 0; i < result['results'].length; i++) {
if (keep_cur > 0 & keep_cur == result['results'][i].id)
$("select#id_method-sub_method").append('<option value="' + result['results'][i].id + '" selected>' + result['results'][i].text + '</option>');
else
$("select#id_method-sub_method").append('<option value="' + result['results'][i].id + '">' + result['results'][i].text + '</option>');
}
;
});
}
And I have a Python/Django function :
def ajax_method_submethod(request):
test_method_id = request.GET.get("test_method", "")
group_id = request.GET.get("group", "")
sub_methods_all = SubMethod.objects.all()
sub_methods = Method.objects.filter(test_method_id=test_method_id).filter(
group_id=group_id
)
results2 = []
for item in sub_methods_all:
results2.append({'id': item.id, 'text': item.name})
print(results2)
results = []
for item in sub_methods:
results.append({'id': item.sub_method.id, 'text': item.sub_method.name})
return HttpResponse(json.dumps({'err': 'nil', 'results': results, 'results2': results2}), content_type='application/json')
I would like to import into my dropdown field values from results2 (python file) when I have sel_val is empty :
if (sel_val === '') {
...
}
So how I could rewrite this part :
if (sel_val === '') {
console.log('none sorting group');
$("select#id_method-sub_method").empty();
$("select#id_method-sub_method").append('<option value=""> test </option>'); //here add list of all submethods
return;
}
Like this :
if (sel_val === '') {
$("select#id_method-sub_method").empty();
for (var i = 0; i < result['results2'].length; i++) {
$("select#id_method-sub_method").append('<option value="' + result['results2'][i].id + '">' + result['results2'][i].text + '</option>'); //here add list of all submethods
}
return;
}
with for loop and append all elements from results2 to my dropdown field ? The issue is actually with result['results2']
Hopfully it's readable and understandable.
Thank you !
EDIT :
As #Darren Crabb said, it's a possible out of scope.
So I rewrote my JS like this :
if (!sel_val) {
reset_select('id_method-sub_method');
$("select#id_method-sub_method").empty();
var all = "{{ results2 }}";
for (var i = 0; i < all.length; i++) {
$("select#id_method-sub_method").append('<option value="' + all[i].id + '">' + all[i].text + '</option>'); //here add list of all submethods
}
return;
}
And I defined in my python file : context['results2'] = SubMethod.objects.all()
I get this :

JavaScript jquery.ajax in success after loop nothing working

I need to pass some values to other function in Javascript. I have got the values from another PHP file but I can not pass it to any other Javascript Function. Nothing is working in SUCCESS after FOR LOOP. Need Help?
url1 = 'http://localhost:81/Dashboard/admin/inc/dashboard.php';
$.ajax({
url: url1,
type: "POST",
dataType: "json",
success: function(data)
{
for(var i = 0; i <= 11; i++)
{
Month = data[i].Month;
Sales = data[i].Sales;
if (i == 0) global_ij = "[" + Month + "," + Sales + "]";
else global_ij = global_ij + "," + "[" + Month + "," + Sales + "]";
}
alert ("hello"); // this alert is also not working
}
});
looks like your php is returning 8 elements and in your success method your loop iterates over 11 items, causing error.
I separated the success function and tried it with the data you posted and replaced the 11 in the loop with data.length. take a look at the following codepen:
http://codepen.io/anon/pen/OyXzGb?editors=011
note that I added
var Month;
var Sales;
to keep those temporary variables inside the scope of the function.
You might need to check Data to see if it is a proper array, to catch errors. before this line:
for(var i = 0; i < data.length; i++)
final output and something to try out:
var global_ij="";
function processData(data) {
var Month;
var Sales;
for(var i = 0; i < data.length; i++)
{
Month = data[i].Month;
Sales = data[i].Sales;
if (i == 0) global_ij = "[" + Month + "," + Sales + "]";
else global_ij = global_ij + "," + "[" + Month + "," + Sales + "]";
console.log(global_ij);
}
return global_ij;
}
try out this function without the ajax first:
processData([{"Month":"1","Year":"2015","Sales":"19746.81"},
{"Month":"2","Year":"2015","Sales":"17902.26"},{"Month":"3","Year":"2015","Sales":"19223.84"},{"Month":"4","Year":"2015","Sales":"18840.88"},{"Month":"5","Year":"2015","Sales":"19889.97"},{"Month":"6","Year":"2015","Sales":"18509.85"},{"Month":"7","Year":"2015","Sales":"1886.81"},{"Month":"8","Year":"2015","Sales":"1740.34"}]);
you might want to use .done()
That's because you are performing an asynchronous AJAX operation. In other words, the assignments on variables Month, Sale, global_ij that you are making are only available in that particular success function's scope and NOT outside of it.
One workaround for you is to add async: false to your AJAX call which will force it out of asynchronous behavior, therefore allowing you to make the values assigned to those variables available to all the remaining block of code:
$.ajax({
url: url1,
async: false,
type: "POST",
dataType: "json",
success: function(data)
{
for(var i = 0; i <= 11; i++)
{
Month = data[i].Month;
Sales = data[i].Sales;
if (i == 0) global_ij = "[" + Month + "," + Sales + "]";
else global_ij = global_ij + "," + "[" + Month + "," + Sales + "]";
}
}
});
jQuery's AJAX calls return promise objects which enforce methods such as .done(), .fail(), etc.
On the other hand, you could also get a promise from the AJAX call (which you can pass around anywhere in your Javascript code) and when the promise gets resolved invoke it's .done() handler.
var promise = $.ajax({/* settings */});
/* --- */
// promise passed to some other block of code
promise.done(function(){
//execute the block of code after the promise was resolved
});
Read more about this here.
The response from the PHP file is:
[
{"Month":"1","Year":"2015","Sales":"19746.81"}, // 1
{"Month":"2","Year":"2015","Sale‌​s":"17902.26"}, // 2
{"Month":"3","Year":"2015","Sales":"19223.84"}, // 3
{"Month":"4","Year"‌​:"2015","Sales":"18840.88"}, // 4
{"Month":"5","Year":"2015","Sales":"19889.97"}, // 5
{"Mont‌​h":"6","Year":"2015","Sales":"18509.85"}, // 6
{"Month":"7","Year":"2015","Sales":"1886‌​.81"}, // 7
{"Month":"8","Year":"2015","Sales":"1740.34"} // 8
]
Yet you are looping
for(var i = 0; i <= 11; i++)
So when i >= 8, data[i].Month will throw an "data[i] is undefined" error.
Simply use the .length property instead:
for(var i = 0; i < data.length; i++)
Example Fiddle
Modify your code to declare the gloabla_ij variable outside the loop. somehting like below..
var global_ij='0';
url1 = 'http://localhost:81/Dashboard/admin/inc/dashboard.php';
$.ajax({
url: url1,
type: "POST",
dataType: "json",
success: function(data)
{
for(var i = 0; i <= 11; i++)
{
Month = data[i].Month;
Sales = data[i].Sales;
if (i == 0) global_ij = "[" + Month + "," + Sales + "]";
else global_ij = global_ij + "," + "[" + Month + "," + Sales + "]";
}
}
});
If you declare the var at the top of the file, it can be used by any function within the file:
var global_ij; // declare variable in global scope of module/file
$.ajax({
url: 'http://localhost:81/Dashboard/admin/inc/dashboard.php',
type: "POST",
dataType: "json",
success: function(data) {
var i, month, sales, len = data.length;
for(i=0; i<=len; i++) {
month = data[i].Month;
sales = data[i].Sales;
if (i===0) global_ij = "[" + month + "," + sales + "]";
else global_ij = global_ij + "," + "[" + month + "," + sales + "]";
}
doSomething(); // can now call function after loop finished
}
});
func doSomething() {
// global_ij is now populated
}

How to use Delay for method execution in jquery

I am using jquery in my one of the form. where on click of submit button i call one function QuoteDetailValidation(). In which i validate fields. But after validate that fields i try to get all fields which have errorActive class. But unfortunately i can't get it.
See my code
$('#saveQuote').on('click', function(event) {
var descriptionData1 = $('input[name=\"QuoteDetail[description][]\"]');
QuoteDetailValidation(descriptionData1);
var selectors = document.querySelectorAll('#quote-quoteItems-form .errorActive').length;
alert(selectors);
return false;
});
function QuoteDetailValidation(descriptionData1) {
for (var i = 0; i < descriptionData1.length; i++) {
var id = descriptionData[i].id;
var value = descriptionData[i].value;
var costid = costData[i].id;
var costValue = costData[i].value;
$.ajax({
type: 'GET',
url: "<?php echo Yii::app()->createUrl('QuoteData/validatedata'); ?>",
data: 'descvalue=' + value + '&Descname=description&costValue=' + costValue + '&costName=cost&descId=' + id + '&costId=' + costid,
success: function(data) {
var obj = $.parseJSON(data);
var cost = obj.cost;
var desc = obj.desc;
if (desc != '' || cost != '') {
if (cost != '') {
$('#' + costid).addClass('errorActive');
$('#' + costid).prev().addClass('error');
$('#' + costid).next().remove();
$('#' + costid).after(cost);
$('#' + costid).parent().removeClass('success');
$('#' + costid).parent().addClass('error');
}
}
},
error: function(data) {
alert('Your data has not been submitted..Please try again');
}
});
}
}
Now What happens, When there is error QuoteDetailValidation() append errorActive class to fields.
By var selectors = document.querySelectorAll('#quote-quoteItems-form .errorActive').length; i try to get length of the fields which have errorActive class. but in alert of selectors, it always gives 0. But when i alert something before getting all errorActive Class then alert selectors give me perfect count. i think there is delay because of alert before getting class errorActive. so that it give me count. How to use it. Any help please. Thanks in advance.
You can determine the exact delay required for selectors to be initailized properly. Whatever we add as delay will be assumption and can be short for some scen
One options using below in your ajax request
async: false
like below:-
$.ajax({
type: 'GET',
async: false,
url: "<?php echo Yii::app()->createUrl('QuoteData/validatedata'); ?>",
data: 'descvalue=' + value + '&Descname=description&costValue=' + costValue + '&costName=cost&descId=' + id + '&costId=' + costid,
success: function(data) {}});
Setting async to false means that the statement you are calling has to complete before the next statement in your function can be called. If you set async: true(it is default) then that statement will begin it's execution and the next statement will be called regardless of whether the async statement has completed yet. Helpful question
But I still will advise you to move selectors part in success of ajax like below:-
$.ajax({
type: 'GET',
url: "<?php echo Yii::app()->createUrl('QuoteData/validatedata'); ?>",
data: 'descvalue=' + value + '&Descname=description&costValue=' + costValue + '&costName=cost&descId=' + id + '&costId=' + costid,
success: function(data) {
var obj = $.parseJSON(data);
var cost = obj.cost;
var desc = obj.desc;
if (desc != '' || cost != '') {
if (cost != '') {
$('#' + costid).addClass('errorActive');
$('#' + costid).prev().addClass('error');
$('#' + costid).next().remove();
$('#' + costid).after(cost);
$('#' + costid).parent().removeClass('success');
$('#' + costid).parent().addClass('error');
}
}
var selectors = document.querySelectorAll('#quote-quoteItems-form .errorActive').length;
alert(selectors);
//some logice here or move the above in some function and call it here
},
error: function(data) {
alert('Your data has not been submitted..Please try again');
}
});
or use call back functions.
Update: try something like below It will keep async as true and keep the count logic outside $.ajax.
function QuoteDetailValidation(descriptionData1,submitFormOrAddError) {
for (var i = 0; i < descriptionData1.length; i++) {
var id = descriptionData[i].id;
var value = descriptionData[i].value;
var costid = costData[i].id;
var costValue = costData[i].value;
$.ajax({
type: 'GET',
url: "<?php echo Yii::app()->createUrl('QuoteData/validatedata'); ?>",
data: 'descvalue=' + value + '&Descname=description&costValue=' + costValue + '&costName=cost&descId=' + id + '&costId=' + costid,
success: function(data) {
var obj = $.parseJSON(data);
var cost = obj.cost;
var desc = obj.desc;
if (desc != '' || cost != '') {
if (cost != '') {
$('#' + costid).addClass('errorActive');
$('#' + costid).prev().addClass('error');
$('#' + costid).next().remove();
$('#' + costid).after(cost);
$('#' + costid).parent().removeClass('success');
$('#' + costid).parent().addClass('error');
}
}
submitFormOrAddError(data);
},
error: function(data) {
alert('Your data has not been submitted..Please try again');
}
});
}
}
Call it like this:
$('#saveQuote').on('click', function(event) {
var descriptionData1 = $('input[name=\"QuoteDetail[description][]\"]');
QuoteDetailValidation(descriptionData1);
QuoteDetailValidation(descriptionData1,function(output){
// here you use the output
var selectors = document.querySelectorAll('#quote-quoteItems-form .errorActive').length; //This line is excuted only after call completes
alert(selectors);
//form submit here if error is zero.
});
alert("hii");//this line is executed without waiting for above call..
return false;
});
You need to do this on your success callback of the QuoteDetailValidation method, because the $.ajax runs async and after invoking the method it still hasn't completed.
$.ajax({
type: 'GET',
url: "<?php echo Yii::app()->createUrl('QuoteData/validatedata'); ?>",
data: 'descvalue=' + value + '&Descname=description&costValue=' + costValue + '&costName=cost&descId=' + id + '&costId=' + costid,
success: function(data) {
var obj = $.parseJSON(data);
var cost = obj.cost;
var desc = obj.desc;
if (desc != '' || cost != '') {
if (cost != '') {
$('#' + costid).addClass('errorActive');
$('#' + costid).prev().addClass('error');
$('#' + costid).next().remove();
$('#' + costid).after(cost);
$('#' + costid).parent().removeClass('success');
$('#' + costid).parent().addClass('error');
}
}
// Here you know that the elements will have the necessary classes.
var selectors = $('#quote-quoteItems-form .errorActive').length;
alert(selectors);
},
error: function(data) {
alert('Your data has not been submitted..Please try again');
}
});

Getting index number of element of array

I have json with array of objects in it. I build my page depends on elements in this array. If there is no duplicate values of key called points, i render page with some info and description, using value of points to find this element in array. However if i have 2 and more duplicate values of key called points i render list of these elements. In this case i cant use value of points to find element in array. I know i can use index number of array element, and then pass it as parameter to my function that find and build info and description, but i'm not sure how to do that. How do i get index number of element in array?
P.S. Can provide my code if needed
Code that i'm using
var allRewards = null;
$("#reward").live('pagecreate', function(e) {
var request = $.ajax({
type: "GET",
url: "example.com/test.json"
dataType: "json",
error: function (data, textStatus){
console.log( "it`s error" );
console.log( status );
console.log( data );},
success: function (data, textStatus){
console.log( "success" );
console.log( status );
console.log( data );
}
})
request.success(function(data, textStatus){
var lis = "";
var arr = [];
var iter = 0;
allRewards = data
$.each(data.rewards, function(key, val){
if ($.inArray(val.points, arr) == -1)
{
lis += "<div data-points='"+ val.points +"'align=CENTER class = 'rewards-block ui-block-" + String.fromCharCode(97 + iter%3) + "'><a href ='#' class ='ui-link-inherit' onclick='showreward("+val.points+")'><img src ='./img/reward-icon.png'/><span>" + val.points + " pts</span></a></div>";
arr.push(val.points);
iter += 1;
}
});
$("#rewards_table").html(lis);
})
});
function showreward(point)
{
$.mobile.changePage('show-rewards.html')
console.log(allRewards);
$("#showrewards").live('pagecreate', function(e) {
var items = "";
var arr = [];
var counter = 0;
var result = $.grep(allRewards.rewards, function(e){ return e.points == point; });
if (result.length > 1)
{
$.each(result, function(key, val){
items += "<div style='color:white;'>" + val.title + "</div>"
console.log(val.title);
})
}
else if (result.length == 1)
{
// $.each(result, function(key, val){
// items += "div style='color:white;'"+ val.points + "></div>"
// console.log(val.points);
// })
$.each(result, function(key, val){
items += "<div style='background:white; padding:5px 5px 20px 5px;'><img style ='float:right; width:45%; margin-top:22px; padding: 0 0 10px 10px;' src ='" + val.main_photo_url + "'/><h3>"+ val.title + "</h3><p>" + val.description + "</p><p style='font-weight:bold; font-size:13px;'>Reedem below for " + val.points + " Zingle Points</p><table class='pagemenu' style='width:200px;'><tr><td class='width_5'><input type='submit' data-theme='w' value='Reedem Now' data-inline='true'></td><td><a data-role='button' data-icon='pagemenu-share' data-iconpos='notext' href='index.html' data-shadow='false' data-corners='false'></a></td></tr></table></div>"
});
}
console.log(items);
$("#rewards-list").html(items);
});
}
I think you're looking for Array.indexOf.
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf
PS. This is available in Underscore as _.indexOf.

Categories

Resources