0

Possible Duplicate:
Using jQuery to compare two arrays

I have to send the form data via ajax to server on say every 30 second. Now I want it to be checked at client end and ajax been hit only in case there is any change in form. I am using:

var lastData = "";
function saveFormInDB(){
    var $form = $("#fb_divBl0ck1").closest('form');
    var isSame = false;
    data = $form.serializeArray();
    if(lastData == ""){
        lastData = data;
    }else{
        if(lastData == data){
            isSame = true;
        }
        lastData = data;
    }
    if(!isSame){
        jqxhr = $.post("/SPSKMEForm/FormSaveServlet", data)
        .success(function() {
            if(jqxhr.responseText != ""){
                alert(jqxhr.responseText);
                alert($("#fixedFooter"));
                alert($("#fixedFooter").html());
                $("#fixedFooter").text(jqxhr.responseText).css("display", "");
                $("#fixedFooter").fadeOut("slow");
            }
        });
    }
}

but isSame is coming to be false always.

0

2 Answers 2

1

That is because your variable lastData is considered as a String whilst data is an Object. So your check will always fail and you will always have isSame = false.

EDIT:

The .serializeArray() method creates a JavaScript array of objects, ready to be encoded as a JSON string.

Sign up to request clarification or add additional context in comments.

6 Comments

i dont think so... m assigning data to lastData.. so it will be an object also var can be used for all the stuff(i guess).
just check your code Varun, you will do the check and if it is true you will say isSame = true and no matter what the result of the check you will always assign lastData to data, but isSame will always be false.
+1: The .serializeArray() method creates a JavaScript array of objects, ready to be encoded as a JSON string. - api.jquery.com/serializeArray
I know there is some issue but i doubt the reason lastData been given as string will be issue... though not sure
@Varun: stackoverflow.com/questions/1773069/… - consider yourself spoonfed :)
|
1

I would approach this problem differently:

In your form input tags add an attribute containing the saved (original) value:

<input type="text" name="name" value="" original="Brian">

Now in your jQuery, check if the values match:

if($('[name="name"]').attr('value') == $('[name="name"]').attr('original')) {
  //perform .post here
  //post success sets attr original to posted value
 }

Each time you submit data, make sure to update the "original" attribute.

1 Comment

will it increase efficiency? wont it be better to simply put a loop on global data variable and check its value

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.