Issues with Javascript For and Arrays - javascript

I'm trying to dynamically hide specific photos on a page, through Javascript, by selecting their data-id attribute and hiding the photo. This is being achieved through Ajax grabbing the IDs from a TXT file, splitting them in to an Array, and then using jQuery to hide the img with that ID. Note that this function is being passed through a setInterval every 3 seconds...
function getBlockedIDs() {
var stringData = $.ajax({
url: "http://s61892.gridserver.com/zone/twitter2/blocked.txt",
async: false
}).responseText;
var blockedArray = new Array();
blockedArray = stringData.split(",");
var length = stringData.length
for (var i = 0; i < length; i++) {
$('img.tweetphoto[data-id="' + stringData[i] + '"]').hide();
}
}
My problem is, it's not working! No errors are thrown from the console. What's wrong with my code? The idea behind this is to block specific (inappropriate) photos without reloading the page.
Any help is appreciated!

Are you sure you want to use stringData inside the for loop and not blockedArray? If so change the assignment to length also.
My version would look something like :
function getBlockedIDs() {
var blockedArray = $.ajax({
url: "http://s61892.gridserver.com/zone/twitter2/blocked.txt",
async: false
}).responseText.split (/\s*,\s*/);
for (var i = blockedArray.length; i--;) {
$('img.tweetphoto[data-id="' + blockedArray[i] + '"]').hide();
}
}

I would do something like:
function getBlockedIDs() {
$.get("http://s61892.gridserver.com/zone/twitter2/blocked.txt", function(stringData) {
var blockedArray = stringData.split(/\s*,\s*/);
for (var i = 0; i < blockedArray.length; i++) {
$('img.tweetphoto[data-id="' + blockedArray[i] + '"]').hide();
}
});
}

Related

How to correctly populate a drop down list via ajax and MVC controller

I've searched quite a bit for this answer and can't find much that covers what I need.
I have some data stored in a db table I want to populate certain drop down lists with. On the document.ready I have an AJAX call to the controller requesting the data based on a parameter I send it. The controller returns the data as Json. I'm new to the process of Json so, figuring out what to with it once it returns is where I'm stuck.
I'm able display the data returned from the controller in an alert or console.log when it returns, so I know the right values are there, but I can't figure out how to populate the dropdown list with those values. All the data is, is about 5 to 10 ints. (not returned as ints, I know, but they're things like 65, 70, 2, 10, 11) I've tried some various options and nothing seems to work.
I can static the values in an array and that actually will populate the drop down list. I've tried populating that same array with the returned data, but no success that way. Here is the ajax call:
//Fill symbols drop down list
function returnSymbols(cc) {
var sendData = JSON.stringify({ 'ul': cc });
$.ajax({
url: '/Trucking/returnSymbols',
type: 'POST',
contentType: 'application/json',
data: sendData,
success: function (data) {
//alert('success');
console.log('success, yes');
alert(data);
var numbers = [];
var obj = jQuery.parseJSON(data);
/* If I do this and static these, it does work
var numbers = [1, 2, 3, 4, 5] */
var option = '';
for (var i = 0; i < numbers.length; i++) {
option += '<option value="' + numbers[i] + '">' + numbers[i] + '</option>';
}
$('#ddlMcalSymbols').append(option); //fill ddl with these values.
},
error: function () {
//alert('Error');
console.log('Error');
}
});
}
To reiterate I have tried things like numbers.push(obj) or even. .push(data), but those aren't working.
Since the controller returns a Json value I was under the impression I needed to parse that Json in order to do anything with it. Here is the controller if it helps at all:
[HttpPost]
public ActionResult returnSymbols(string ul)
{
List<Get_CIF_SymbolsVM> symbols;
Guid newGuid = Guid.Parse(ul); //parse param as Guid
using (TruckingDb db = new TruckingDb())
{
symbols = db.GetSymbols.ToArray().OrderBy(x => x.RID).Select(x => new Get_CIF_SymbolsVM(x)).ToList();
}
var syms = (from s in symbols
where s.UniqLineType == newGuid
select s.SymbolCode).Distinct();
return Json(syms, JsonRequestBehavior.AllowGet);
}
Any help would be greatly appreciated.
EDIT: Updating the process to explain a bit more.
Had some success, but it's still not correct.
Here is the ajax call. I changed just a few items. It brings back the correct data, but it displays all array items as one line. I need each value in the array as a single value in the drop down list.
var sendData = JSON.stringify({ 'ul': cc });
$.ajax({
url: '/Trucking/returnSymbols',
type: 'POST',
contentType: 'application/json',
data: sendData,
success: function (data) {
//alert('success');
console.log('success, yes');
alert(data);
var numbers = [];
numbers.push(data);
var option = '';
//Added two for loops to show what I've tried.
for (var i = 0; i < numbers.length; i++) {
option += '<option value="' + numbers[i] + '">' + numbers[i] + '</option><br>';
}
$('#ddlMcalSymbols').append(option);
//Tried this option to fill ddl
for (var i = 0; i < numbers.length; i++) {
option = '<option value="' + numbers[i] + '">' + numbers[i] + '</option><br>';
$('#ddlMcalSymbols').append(option);
}
//This Jquery foreach only returns one value to the ddl
$.each(numbers, function (i, value) {
console.log(value);
option += '<option value="' + value[i] + '">' + value[i] + '</option>';
});
$('#ddlMcalSymbols').append(option);
},
error: function () {
//alert('Error');
console.log('Error');
}
});
It brings back the data, but in the drop down both of the for loops above fill the ddl as one long looking string. "61,62,64,66,70,71,72" .. They don't show up as single select values.
I tried parts of the code, and it seems you are overlooking that the var numbers never acquires values.
I also usually prefer to create jquery objects rather than manually compile html; it is easier to develop this way. The code fails with more detail.
Something on the lines of:
var listEl=$('#ddlMcalSymbols');
for (var key in obj) {
jQuery('<option value="' + obj[key] + '">' + obj[key] + '</option>').appendTo(listEl);
}
but in better order
Worked out a solution that while it functions, there is some odd behavior with the CSS of it. I'm using a multiselect drop down called bootstrap-select. Has a .js and .css file. I needed to fill the multiselect drop down with values from a db instead of hard-coding them in with the method.
I use a post ajax call to send a parameter to the controller which retrieves the values I need based on it. I don't know if it's the bootstrap-select or a limitation with multiselect, but it did not like displaying the Json data. My ajax call is already parsing the Json, so that wasn't it. After multiple attempts and trials I figured out the only thing that really works is with an int array. When I had the string array it would display everything as either one long string or only one value. Additionally, even now with it working as I would like, I have to reload the page every time I make a change to the .js file i'm working on. That screws up the bootstrap-select.css file. NO IDEA AS TO WHY. What happens is every 3 to 4 page reloads the values are outside the drop down list and smooshed together like a bunch of unreadable text. (See pic above) I press ctrl + shft + R to clear the chromes cached css and it goes back to how it should look and function. Long-winded, but true. Here is my ajax call with some comments, so you can see what I did. I'm sure there may be more elegant and straightforward ways of doing this, but it was an improvement on what I already had. Maybe it will help someone else.
function returnSymbols(cc) {
var sendData = JSON.stringify({ 'ul': cc });
$.ajax({
url: '/Trucking/returnSymbols',
type: 'POST',
contentType: 'application/json',
data: sendData,
success: function (data) {
var num = [];
var num1 = [];
//Push all returned values into num array
$.each(data, function (index, value) {
num.push(value);
});
console.log(num); // console out to ensure values have been pushed
//convert the string array into an int array
for (var i in num) {
num1[i] = parseInt(num[i]);
}
console.log(num1); //conosle out to ensure values have parsed correctly
fillddl(num1); // send int array to fill drop down func
},
error: function () {
//alert('Error');
console.log('Error');
}
});
}
Then the Function to actually send the values to the drop down list. Very similar to what I've found in other methods.
function fillddl(sym)
{
var s = '';
for (var i = 0; i < sym.length; i++)
{
s += '<option value="' + sym[i] + '">' + sym[i] + '</option>';
}
$(".ddlMcalSymbols").html(s);
}
you can do something like this
In action method
[HttpPost]
public ActionResult getCicitesAction(int provinceId)
{
var cities = db.cities.Where(a => a.provinceId == provinceId).Select(a => "<option value='" + a.cityId + "'>" + a.cityName + "'</option>'";
return Content(String.Join("", cities));
}
The ajax call would be like this:
$("province_dll").change(function(){
$.ajax({
url: 'getCitiesController/getCitiesAction',
type: 'post',
data: {
provinceId: provinceIdVar
}
}).done(function(response){
$("cities_dll").html(response);
});

"Synchrounous" AJAX call and web2py

I need some help with "synchronizing" my AJAX calls. I have a function scripted that takes in a file with certain test parameters and uses those parameters to kick off test via an AJAX call/s. The way the code is suppose to work is thatonce the test run is complete, another AJAX call is suppose to update the eventLog with the test results for that run and then move to the next iteration of the for loop.
The ajax calls can be seen in the for loop towards the bottom of the code. I looked into some documentation on using the jQuery Deffered class, but I am pretty new to JavaScript in general and I'm having trouble understanding how that code works. Thanks in advance for any help.
function runTest(modelName, serialNum, passArea) {
//Pull in sequence file
var str = "";
var table = document.getElementById('taskTable');
var output = document.getElementById('outputStrArea');
var passFail = document.getElementById(passArea).innerHTML;
var rowCount = table.rows.length;
for(var i=1; i<rowCount; i++) {
var row = table.rows[i];
str+= row.innerHTML+"\n";
}
str = str.split("<td>");
delete str[0];
delete str[-1];
//Create a list of tests that can be read out
var testList = [];
for (var i=1; i <str.length; i++){
str[i]= str[i].replace("</td>", "");
str[i]= str[i].replace(" ", "");
if (str[i].search("checkbox") < 0){
testList.push(str[i]);
}
}
var model = document.getElementById(modelName).innerHTML;
model = model.replace("<b>", "");
model = model.replace("</b>", "");
model = model.replace(" ", "");
var serial = document.getElementById(serialNum).innerHTML;
var info = model+" "+serial+" ";
for(var k=0; k<testList.length; k+=5){
info+= testList[k]+" "+testList[k+1]+" "+testList[k+2]+" "+testList[k+3]+" "+testList[k+4]+" ";
ajax("loadTestSequence?info="+info, [], passArea);
ajax("loadEventLog", [], 'eventLog');
}
}
The ajax calls have a success callback in which you can invoke another ajax call id you want. Syntax is something like this:
$.ajax({
url: url,
data: data,
success: function(){
$.ajax({
url: url,
data: data,
success: success,
dataType: dataType
});
},
dataType: dataType
});
So now you can chain your respective ajax calls similarly. Hope that helps.

First Time Ajax request getting two url different elements

var memberURL;
var memberAva;
var memberName;
var members = data.find('.userdata');
for (var j = 0; j < members.length; j++) {
membername = $(members[j]).find('.username').text();
memberURL = $(members[j]).find('.username').attr('href');
}
memberAva = $('#advanced-profile-right img:eq[0]');
$.ajax({
url:"/viewonline",
type:"GET",
data: {memberURL, memberName}, //What should i do here?
success: function() {
$.ajax({
url: memberURL,
type:"GET",
data: memberAva
}).done(function() {
$('.user_info_on').append('<div class="on_name"><img src="' + memberAva + '"/></div>');
}
});
});
What I am trying to get from the first ajax request is the members URL and the Members name- then on success make another ajax request to the Members URL (each) and get the Members Avatar. Then on done post the data that is retrieved. Code is not working, and not sure what I should do?
I tried posting on two .get()s though I guess this is the only way? Anyways anyone have suggestions and tips for me?
The .get() that works-
$(function () {
$.get('/viewonline', function (data) {
data = $(data);
var members = data.find('.userdata');
for (var j = 0; j < members.length; j++) {
var membername = $(members[j]).find('.username').text();
var memberURL = $(members[j]).find('.username').attr('href');
});
$('.user_info_on').append('<div class="on_name"><img src=""/></div>'); //In between source of image would be memberAva from the other .get() request.
}
}, 'html');
});

Use a FOR loop within an AJAX call

So, what i'm trying to do is to send an AJAX request, but as you can see i have many fields in my form, and i use an array to make validations, i would like to use the same array, to pass the values to be sent via AJAX:
I never used the for loop in JS, but seems familiar anyway.
The way the loop is made, obviously wont work:
for (i=0;i<required.length;i++) {
var required[i] = $('#'+required[i]).attr('value');
This will create the variables i want, how to use them?
HOPEFULLY, you guys can help me!!! Thank you very much!
required = ['nome','sobrenome','endereco','codigopostal','localidade','telemovel','email','codigopostal2','localidade2','endereco2','nif','entidade','codigopostal3','localidade3','endereco3','nserie','modelo'];
function ajaxrequest() {
for (i = 0; i < required.length; i++) {
var required[i] = $('#' + required[i]).attr('value');
var dataString = 'nome=' + required[0] + '&sobrenome=' + required[1];
}
$.ajax({
type: "POST",
url: "ajaxload/como.php",
data: dataString,
success: function() {
$(".agendarleft").html("SUCESS");
}
});
To help ensure that the appropriate element IDs and values are passed, loop through the various elements and add the data to an object first.
jQuery:
required = ['nome', 'sobrenome', 'endereco', 'codigopostal', 'localidade', 'telemovel', 'email', 'codigopostal2', 'localidade2', 'endereco2', 'nif', 'entidade', 'codigopostal3', 'localidade3', 'endereco3', 'nserie', 'modelo'];
function ajaxrequest() {
var params = {}; // initialize object
//loop through input array
for (var i=0; i < required.length; i++) {
// set the key/property (input element) for your object
var ele = required[i];
// add the property to the object and set the value
params[ele] = $('#' + ele).val();
}
$.ajax({
type: "POST",
url: "ajaxload/como.php",
data: params,
success: function() {
$(".agendarleft").html("SUCESS");
}
});
}
Demo: http://jsfiddle.net/kPR69/
What would be much cleaner would be to put a class on each of the fields you wish to save and use this to iterate through them. Then you wouldn't need to specify the input names either and you could send a json object directly to the Service;
var obj = {};
$('.save').each(function () {
var key = $(this).attr('id');
var val = $(this).val();
if (typeof (val) == "undefined")
val = "''"
obj[key] = val;
}
Then send obj as the data property of your AJAX call....
There are a few issues with your code. 'required' is being overwritten and is also being re-declared inside of the loop.
I would suggest using pre-written library, a few I included below.
http://jquery.malsup.com/form/#validation
https://github.com/posabsolute/jQuery-Validation-Engine
Otherwise the follow would get you close. You may need to covert the array into a string.
var required = ['nome','sobrenome'];
function ajaxrequest() {
var values;
for (i = 0; i < required.length; i++) {
var values[i] = $('#' + required[i]).attr('value');
}
$.ajax({
type: "POST",
url: "ajaxload/como.php",
data: values,
success: function() {
$(".agendarleft").html("SUCESS");
}
});
}

JavaScript auto-incrementing a variable in jQuery and AJAX

I have JavaScript using jQuery and AJAX which creates a dynamic array, which has some values used for AJAX request as below;
<script type="text/javascript">
var array = Array("y","y","x","y","y","y");
function updateBackground(cellId, titleId) {
var i = 0;
$.ajax({
type: "POST",
url: "ajax.php",
data: {
filename: Array(array[i], "testdata", $("#"+titleId).html())
},
success: function(response){
$("#"+cellId).css("background-image", "url('pdfthumb/" + response + "')");
}
});
i++;
}
</script>
The script is suppose to submit values in the array in array[i] for each AJAX request. I made a variable var i which auto increments.. But the script is not working.. The script works well if array[i] is replaced by array[0] or array[1] etc..
How can I solve the syntax error?
Every time you call updateBackground() i = 0 (again). May be you must initialize i outside of the function.
What happens if i > array.length? And I would rename the variable.
You don't have an iterator. Your variable i gets set to 0 every time the function runs. The increment at the end is useless.
Maybe you need something like this?
var array = Array("y","y","x","y","y","y");
function updateBackground(cellId, titleId) {
for( var i = 0; i < array.length; i++ ) {
$.ajax({
type: "POST",
url: "ajax.php",
data: {
filename: Array(array[i], "<?php echo $dir; ?>", $("#"+titleId).html())
},
success: function(response){
$("#"+cellId).css("background-image", "url('pdfthumb/" + response + "')");
}
});
}
}
Each time you call updateBackground() function, the i variable is being reinitialized. It's just a local variable and as soon as the function finishes it's being destroyed by GC. You could do something like this:
var UpdateBackground = {
array: [..],
counter: 0,
doUpdate: function(cellId, titleId) {
// AJAX request
this.counter++;
}
};
UpdateBackground.doUpdate(1, 1);
UpdateBackground.doUpdate(1, 1);
I think that you should send the whole array maybe as a commaseparated string and instead and make just one ajax request, because http-requests are expensive and change the server side code accordingly. And fetch the cellids as an array.
If you think that you have a long list or a table it can be like a lot of requests. Do the stuff in client code and do the stuff in server code and keep the number of http-requests as few as possible.
And use the join method on the array.
var arr = [ 'y', 'y' ];
arr.join(',');
// outputs y, y
I fixed it... Thank you so much #Jed, #Pointy, #Crozin, and #Lord Vader for helping me to figure it out.... :)
I just take var i = 0; outside the loop.... above var array like;
var i = 0;
var array = Array("y","y","x","y","y","x");

Categories

Resources