views:

26

answers:

2

I have a webpage that fires off an Ajax request which stores some data to a database and I want to update the webpage so that the user can see their changes have been submitted.

There are at least 3 ways I can think of accomplishing this:

  • Immediately update the webpage with plain JavaScript by grabbing the contents of the user's inputted text and immediately inserting it where it belongs.
  • Have the ajax call return the stored text as the response, grab the response, and then insert this text where it belongs on the page using JavaScript
  • Have the ajax call return a flag (say, true for successful db write, false otherwise), and if the flag is true, use JavaScript to grab the user's contents from the input control and insert it where it belongs elsewhere on the page
  • Or another method not mentioned...?

I don't mean this to be subjective, I just don't know which would be the best method to apply. My instinct tells me to go with the third item (return a flag, then update the field). Is this the best way?

Thanks

A: 

I do it two ways: if the page is being populated by ajax to start with, then i re-call that function to re-get that data on success.

Otherwise, I append the data to where it needs to go if successful. That way, you're not trafficking the data back and forth.

Dan Heberden
+1  A: 

I would go with the second or third way. There is no significant difference between the two.

My reasoning...

Number one updates the field before you know whether the request was successful or not. This is responsive from a UI point of view but not correct if the request failed.

The second or third way gives you whether the request was a success (allowing you to display an error if it wasn't), and allows for updating the UI without making a separate request. The third way may be a little better if the value returned from the request would be large and thus take up unnecessary bandwidth.

Jacob
Yeah, I was thinking the third way for the same reason-- it's that much less data being sent over the wire, even if it doesn't make a huge impact. Thanks!
Cuga