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

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 href of the link(button) but still it doesnt work?
The html code:
<form id="form_message_user" method="post"
action="#user_requestmoreinfo_page
">
<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>
</div>
<input type="submit" value="submit" id="submitmessage" />
</form>
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){
e.preventDefault();
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: '127.0.0.1/php/send.php',
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) {
console.log(result);
},
error: function (error) {
// This callback function will trigger on unsuccessful action
console.log(error);
}
});
} 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);
Example:
If i had to navigate between other pages 3 times the console.log() will show output of 3 times

I can think of two reasons why you experience this behaviour.
1) Code multiplication. Bind the code to pagecreate, not pageshow, as the latter event is triggered every time the page is displayed, duplicating the submit code and causing multiple events.
2) Page duplication. This is a well-known bug in jQM that is described here. In short, the first page (and its form) is duplicated in DOM under certain circumstances. To fix it, describe the path to the HTML document with the attribute data-url, and place it within the page div. Example code:
<div data-role="page" data-url="mysite/path/index.html" id="user_requestmoreinfo_page">
Here is a rework of your code with added buttons for page navigation:
Example code:
$(document).on('pagecreate', '#user_requestmoreinfo_page', function(e) {
$('#form_message_user').on('submit', function(e) {
//Cancel default action (https://api.jquery.com/event.preventdefault/)
e.preventDefault();
//var id_from = localStorage.loggedin_id;
//var id_to = localStorage.user_schoolls_id;
var message = $("#text_user_message").val();
//Validate
if(message == "")
alert('Please enter the message');
// Send data to server through the Ajax call
// action is functionality we want to call and outputJSON is our data
alert("Thank you for your comment.");
$.ajax({
url: '127.0.0.1/php/send.php',
data: {
message: message,
id_from: id_from,
id_to: id_to
},
type: 'post',
async: 'true', //<- true is default
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) {
console.log(result);
},
error: function(error) {
// This callback function will trigger on unsuccessful action
console.log(error);
}
});
return false; // cancel original event to prevent form submitting
});
});
<html>
<head>
<link href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
</head>
<body>
<div data-role="page" data-url="<mysite>/index.html" id="user_requestmoreinfo_page">
<div data-role="content">
<form id="form_message_user" data-ajax="false">
<label for="requestmessage">Message:</label>
<textarea data-inline="true" id="text_user_message" placeholder="Type message to send"></textarea>
<input type="submit" value="Submit" data-inline="true" />
</form>
Next page
</div>
</div>
<div data-role="page" id="second">
<div data-role="content">
<p>
Second page
</p>
First
Third
</div>
</div>
<div data-role="page" id="third">
<div data-role="content">
<p>
Third page
</p>
First
</div>
</div>
</body>
</html>

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
$('#form_message_user').off('submit');
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():
http://api.jquery.com/one/

Related

Get input field value in same page without refreshing page php

I am trying to send my input value to a code segment in the same page, but it doesn't work. Right now, I can't get the value in the code segment. This is my current code:
<?php
if ($section == 'codesegment') {
if ($_GET['hour']) {
echo $_GET['hour'];
//here i want call my method to update db with this value of hour...
}
if ($section == 'viewsegment') {
?>
<form id="my_form" action="#" method="Get">
<input name="hour" id="hour" type="text" />
<input id="submit_form" type="submit" value="Submit" />
</form>
<script>
var submit_button = $('#submit_form');
submit_button.click(function() {
var hour = $('#hour').val();
var data = '&hour=' + hour;
$.ajax({
type: 'GET',
url: '',
data: data,
success:function(html){
update_div.html(html);
}
});
});
</script>
Any advice?
If you want to get the value without refresh your page you have to use javascript, you can try this:
$('#hour').onchange = function () {
//type your code here
}
By the way, your php script is server side, according to this, you can't use the value without post/submit/refresh
Whenever you are using
<input type="submit">
it sends the data to the action of the form, so whenever you are clicking the submit button before the onclick function gets called, it sends the data to the action and the page gets refreshed. So instead of using input element try something like this
<button id="submit_form"> Submit </button>
two things,
1. as yesh said you need to change the input submit to button type=button and add an onClick function on that button. Or you can give a the javascript function inside a function line function sampleFn(){} and call this function onSubmit of form.
2. You need to give the javascript inside document.ready function since the script execute before the dom loading and the var submit_button = $('#submit_form'); may not found. In that case there will be an error in the browser console.
Try to add errors in the post since it will help to debug easily.
It's not possible to do on the same page. you can write ajax call to another page with data where you can do the functions with the data.
Something like this
//form.php
<form id="hour-form">
<input type="text" name="hour" id="hour">
<input type="submit" name="hour-submit" >
</form>
<script type="text/javascript">
$(document).ready(function(){
$(document).on('submit', '#hour-form', function(e){
e.preventDefault();
var data = $('#hour').val();
$.ajax({
url: "post.php",
method: "POST",
data: {'hour':data},
success: function(data)
{
//if you want to do some js functions
if(data == "success")
{
alert("Data Saved");
}
}
});
});
});
//post.php
if(isset($_POST['hour']))
{
// do the php functions
echo "success";
}

[jQuery]Page refreshes after appending html with .html()

So I'm trying to get some data from the server with php but as soon as it's loaded onto the page it seems to reload the page and make it disappear again.
My html:
<form id="searchForm">
<input name="searchValue" type="text" id="search">
<input type="submit" name="Submit" value="Zoek op klant" onclick="getKlanten()">
</form>
<div id="klanten">
</div>
My js:
function getKlanten(){
var value = $("#search").val();
$.ajax({
url:'includes/getKlanten.php',
async: false,
type: 'POST',
data: {'searchValue':value},
success: function(data, textStatus, jqXHR)
{
$('#klanten').html(data);
},
error: function () {
$('#klanten').html('Bummer: there was an error!');
}
});
}
Can anyone help? It gets put into the div but then instantly disappears again.
Firstly, avoid inline click handlers. The page reloads because by default a form submits the form content to the url specified in action attribute.
Instead attach an event to the form and use preventDefault to avoid the page from refreshing. Do something like this
$('#searchForm').on('submit', function(e){
e.preventDefault();
// your ajax request.
});
Or attach an event to input button like this
$('input[type="submit"]').on('click', function(e){
e.preventDefault();
// your ajax request
});
Read more about preventDefault here

JavaScript/Ajax - How to run one PHP script before posting form to another one

I am almost at my wit's end trying to figure out why my code is not working.
Here is what I am trying to do:
1) Accept several variables in a form (myform).
2) Using an onsubmit, I want to use pass one or more of those variables to a script (process_info).
3) After process_info has executed, the form should be posted to the form's action URL ('save_info.php').
As you can see in the code below, I have tried several things:
Test 1: This simple alert is shown and the form is submitted to save_info.php.
Test 2: I copied and modified this jQuery script from another page on this site. No matter what I do, the script does not run. I know this because no alert message is shown.
Test 3: After removing the jQuery(document).ready statement from Test 2, the senddata function runs. Although it runs the process_info script, the form does not get posted to save_info.
<html>
<head>
<title>Form Test</title>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javaScript">
/* Test 1: this works - form is submitted to the action URL
function senddata() { alert('here'); }
*/
/* Test 2: this does not run (no alert shown) - form is submitted to the action URL */
jQuery(document).ready(function() {
function senddata() {
var formdata = jQuery("#myform").serialize();
var decoded = decodeURIComponent(formdata);
strip = decoded.replace(/[\[\]]/g, "_");
// alert(strip);
jQuery.ajax({
type: "POST",
url: 'process_info.php',
data: strip,
success: function(){ alert('success'); },
error: function(){ alert('failure'); },
complete: function(){
jQuery("#myform").submit(); //submit the form after ajax completes
}
});
return false; //stop the form from initially submitting
}
});
/* Test 3: this runs and the AJAX URL is executed, "success" is displayed - form is NOT submitted to the action URL
function senddata() {
var formdata = jQuery("#myform").serialize();
var decoded = decodeURIComponent(formdata);
strip = decoded.replace(/[\[\]]/g, "_");
// alert(strip);
jQuery.ajax({
type: "POST",
url: 'process_info.php',
data: strip,
success: function(){ alert('success'); },
error: function(){ alert('failure'); },
complete: function(){
jQuery("#myform").submit(); //submit the form after ajax completes
}
});
return false; //stop the form from initially submitting
}
*/
</script>
</head>
<body>
<form name="myform" id="myform" onsubmit="return senddata()" action="save_info.php" method="post" enctype="multipart/form-data">
<input type="text" name="id" />
<input type="text" name="last" />
<input type="submit" value="send" />
</form>
</body>
</html>
I assume that what I am trying to do is actually possible. What am I doing wrong?
ok, I have edited your code in a way that it works and I'll explain a few changes after the code.
<html>
<head>
<title>Form Test</title>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javaScript">
/* Test 2: this does not run (no alert shown) - form is submitted to the action URL */
jQuery(document).ready(function(){
$("#myform").submit(function(event){
event.preventDefault();
var formdata = jQuery("#myform").serialize();
var decoded = decodeURIComponent(formdata);
strip = decoded.replace(/[\[\]]/g, "_");
// alert(strip);
jQuery.ajax({
type: "POST",
url: 'process_info.php',
data: strip,
success: function(){ alert('success'); },
error: function(){ alert('failure'); },
complete: function(){
jQuery("#myform")[0].submit(); //submit the form after ajax completes
}
});
return false; //stop the form from initially submitting
});
});
</script>
</head>
<body>
<form name="myform" id="myform" action="save_info.php" method="post" enctype="multipart/form-data">
<input type="text" name="id" />
<input type="text" name="last" />
<input type="submit" value="send" />
</form>
</body>
</html>
So, first I have removed onsubmit from the <form> element in the html
Then changed the function the same as you did in your comment.
The last trick is that if I wanted to use jQuery("#myform").submit(); in the complete section of the ajax it would add another listener for the form submit event and would call the function again and again and again.
So I had to access the HTML form element directly and call the submit for it, that's the trick as you can see jQuery("#myform")[0].submit();

Login page using jquery does not resubmit

The problem is that on a login page, after an incorrect entry is submitted, the ajax request does not go through a second time on pressing submit.
I have hunted through StackExchange for an answer to my question, and have looked at links such as Why won't my jQuery form resubmit? and jQuery & AJAX login form among a dozen others. Looks like I need to unbind the submitted variables, but not sure how to do this.
HTML
<div data-role="page" id="login">
<div data-role="header" data-position="inline" data-theme="b">
<h1>My login</h1>
</div><!-- /header -->
<div data-role="content">
<form method="post" id="loginform">
<label for="username">Username:</label> <input type="text" name="username" id="username" value="" />
<label for="passwd">Password:</label> <input type="password" name="passwd" id="passwd" value="" />
<input type="submit" value="Login" />
</form>
</div><!-- /content -->
</div><!-- /login page -->
JavaScript:
$(document).ready(function() {
$("#loginform").on('submit',function(event){
var $form = $(this),
serializedData = $form.serialize();
// fire off the request to /form.py
$.ajax({
url: "https://mywebsite/cgi-bin/form.py",
type: "post",
data: serializedData,
// callback handler that will be called on success
success: function(response, textStatus, jqXHR){
console.log(response);
// If login is unsuccessful, log message and return to login screen again
if (response == "INVALID_USER\n") {
alert("sorry, try again");
} else {
// Login successful - do something
}
},
// callback handler that will be called on error
error: function(jqXHR, textStatus, errorThrown){
console.log(
"The following error occured: "+
textStatus, errorThrown);
},
// callback handler that will be called on completion
// which means, either on success or error
complete: function(){
//----- DO I NEED TO UNBIND SOMETHING HERE?
var dummy = 1;
}
}); // end of ajax call
}); // end of submit handler
});
Would you try to add return false before the end of the event handler? Using return false you prevent the event fire and prevent the user from proceeding without filling out the correct required fields.
$("#loginform").on('submit',function(event){
...
return false;
});
Furthermore what data type is returned by the server? For example if the server returns JSON then you should add dataType: 'json' in the AJAX code. If none is specified, jQuery will try to infer it based on the MIME type of the response.
Maybe you could use the firebug to find out whether any error occurs.

How to put a jQuery code into one file which will be referenced by all pages?

I have a login popup that will pop up on every page of my site. What I want to do is once the user clicks submit, to have a single JS file where the jQuery code for handling that request lives, and makes an AJAX call to validate the parameters in the DB.
I am able to get the pop up box to pop up. And the form loads. I am thinking my jQuery code will live in a separate imported file and look like this:
<script type="text/javascript" >
$(function()
{
$("input[type=submit]").click(function()
{
var some_params= $("#param").val();
var dataString = 'Some url to send to ajax';
if( params validated ok )
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "/problems/add_problem.php",
dataType: "json",
data: dataString,
success: function(json)
{
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
</script>
So my question is how do I make this get invoked only when the right form is submitted? The form would have some id="some_name" but I don't really understand how to make this jQuery code get executed only when that form element is called.
And here is the form I am calling to display in the popup:
<?php
echo '<div id="login_div">
<form id="login_form" method="post" action="">
<p>
<label for="name"><span>Your Email:</span></label> <input type="text" name="email" />
</p>
<p>
<label for="name"><span>Your Password:</span></label> <input type="password" name="user_pass">
</p>
<p>
<input type="submit" value="Log In" />
</p>
</form>
</div>
<p>
Create Account | Reset Pass
</p>
';
?>
and here is the problemio.js contents with the jQuery to handle the login form submit:
// javascript library
// login_form
$(function()
{
$("#login_form input[type=submit]").click(function()
{
console.log("test");
alert("1");
// var name = $("#problem_name").val();
// var problem_blurb = $("#problem_blurb").val();
// var dataString = 'problem_name='+ name + '&problem_blurb=' + problem_blurb;
// if(name=='' || problem_blurb == '')
// {
// $('.success').fadeOut(200).hide();
// $('.error').fadeOut(200).show();
/// }
// else
// {
// $.ajax({
// type: "POST",
// url: "/problems/add_problem.php",
// dataType: "json",
// data: dataString,
// success: function(json)
// {
// $('.success').fadeIn(200).show();
// $('.error').fadeOut(200).hide();
//
/// // Here can update the right side of the screen with the newly entered information
// //alert (json);
//
// new_string = "<h2>Most Recently Added Problems</h2>";
// Have to figure out how to make this work with the DOM.
// }
// });
// }
return false;
});
});
Two things. First, when you place the code above into a separate javascript file, be sure to remove the <script ..> and </script> HTML tags.
Next, alter the following line:
$("input[type=submit]").click(function()
To instead say:
$("#loginform input[type=submit]").click(function()
And then set id="loginform" on your <form> tag.
You can use .submit() to attach a handler to the form submit event. First you'll need to select your form via the id:
$("#some_form_id").submit(function() {
// the code you have in the click event above goes here.
});
You can specific the form you want to trigger the jquery. http://api.jquery.com/submit/
If you are not sure, just right-click this webpage and read its html code.
<script type="text/javascript" src="some.js"></script>
And also, binding the the function to form.submit is much better than to the submit button.
$('formid').submit(function(){blablabla;return false;})
If you would like to handle the click event for every submit on the page without using ids, you can always use the this keyword in the click event to find the sender and then find the parent form.

Categories

Resources