Javascript Question

How to stop duplicate data in jquery mobile after navigationg between pages

I am creating a chat application in jQuery Mobile.The problem is that when you navigate between pages and come back to the chat page when submitting data the data is resent according to the number of times one has navigated between other pages

When i perform a full page refresh data is sent only once as required.

I have tried adding

data-ajax = false
to the
of the link(button) but still it doesnt work?

The html code:

<form id="form_message_user" method="post"
<div data-inset="true">
<label for="requestmessage" class="ui-hidden-accessible"></label>
<textarea cols="40" rows="6" name="requestmessage"
id="text_user_message" placeholder="Type message to send "></textarea>
<input type="submit" value="submit" id="submitmessage" />


The form is on a page with

<div data-role="page" id="user_requestmoreinfo_page" data-theme="e">

The submission code:

$(document).on('pageshow', '#user_requestmoreinfo_page',function(e){
var id_from = localStorage.loggedin_id;
var id_to = localStorage.user_schoolls_id;
var message = $("#text_user_message").val();

$('#form_message_user').on('submit', function(e){
if(message > 0 ){
// Send data to server through the Ajax call
// action is functionality we want to call and outputJSON is our data
$.ajax({url: '',
data: {message:message,id_from:id_from,id_to:id_to},
type: 'post',
async: 'true',
dataType: 'json',
beforeSend: function() {
// This callback function will trigger before data is sent
$.mobile.showPageLoadingMsg(true); // This will show ajax spinner
complete: function() {
// This callback function will trigger on data sent/received complete
$.mobile.hidePageLoadingMsg(); // This will hide ajax spinner
success: function (result) {
error: function (error) {
// This callback function will trigger on unsuccessful action
} else {
alert('Please enter the message');
return false; // cancel original event to prevent form submitting


On success the console.log() displays the json data according to the number of page navigations before getting to the page(#user_requestmoreinfo_page);


If i had to navigate between other pages 3 times the console.log() will show output of 3 times

Answer Source

My guess is that you're binding the event handler to the #form_message_user element each time the #user_requestmoreinfo_page event is handled. I'd try adding


directly before

$('#form_message_user').on('submit', function(e){
    // function body continues

You could also try using .one:

$('#form_message_user').one('submit', function(e){
    // function body continues

According to the docs, that should have the same affect as .off() followed by .on():