I have a page that is posting a JSON to a cfc, and getting a success/fail message back. The array that the JSON is built from contains the ID’s of the input fields that were updated. I am changing the background color of the elements to alert the users that an update was made, but the problem arises when the the user posts more changes without leaving the page. The array still contains the data from the previous post, and no matter what or where I try to clear the array, the changing of the background stops working.
Here is the code:
$("input").change(function(){
theArray.push({
'id':$(this).attr('id'),
'value':$(this).val()
});
});
$("#edit_button").click(function(){
if(theArray.length >0){
theArray.push({
//some processing information to the cfc
});
theJson = JSON.stringify(theArray);
$.post("CFCs/fund_profile.cfc",
{
method:"updateProfile",
data:theJson
},
function(data){
if(data.HASERROR == 1){
$("#messageDiv").empty().html(data.MESSAGE);
}
else{
$("#messageDiv").empty().html(data.MESSAGE);
theArray.pop();//removing the cfc processing information
for(var i = 0; i <= theArray.length; i++){
var $el = $("#" = theArray[i].id).parent().parent().css('background','red');
setTimeout(function(){
$el.css('background','');
$("#messageDiv").empty();
},5000);
}
}
},
"json");
//THIS IS WHERE THE PROBLEM LIES (I THINK)
//I HAVE TRIED THE FOLLOWING:
var arrayLen = theArray.length;
for(var j = 0;j <= arrayLen; j++){
theArray.pop();
}//DOESN'T WORK
theArray.length = 0;
//DOESN'T WORK
for(var j = 0;j <= arrayLen; j++){
theArray.shift();
}//DOESN'T WORK
}
});
If I remove the code to clear the array, the background change happens, but the array never loses that element, and will always show that element as being updated. If I keep it the background changes doesn’t happen at all.
I”m sure it is something simple that I am missing, but I’m frustrated about it.
Any thoughts?
Add this inside of your post statement after the if/else statement:
That effectively makes the array empty. No need for looping through it.
Also, as pointed out by David, it has to be inside of the success of the post, not after it.
Edit:
Your for loop isn’t executing exactly as you expect it to, the setTimeout should only affect the last element. To solve that, switch to a
$.each, or create an anonymous function inside of your for loop.One more note:
If someone submits a second set of data to the server before the first one is complete, things may get very messed up due to both cases using the same array. David touched on that on his answer pretty well. Maybe on the click event you should immediately make a copy of the array and then clear the original, leaving it open for use by the next click.
Example (possibly working, not tested):
Edit updated for loop in last statement, should be easier to understand.