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.
Related
I made a custom Jquery plugin to help me easily send data via Ajax to the server that has been tailored to suit laravel, but apparently I am not able to send any data. when I use dd($request->all()) to check what has been sent to the laravel server, I receive an empty array in console implying that I have not sent anything. Below is my code
JS
(function($){
'use strict'
$.fn.lajax=function(options){
//overwrite options
var optns=$.extend({
dataType: 'json',
debug:false,
processData: true,
headers:{
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
acceptedInputFile:'/*/',
//functions that are very similar to the ajax optns but differ a little
//as the paramters give easy access to the ajax form element
lajaxBeforeSend: function(form,formData,jqXHR,settings){},
lajaxSuccess: function(form,formData,data,textStatus,jqXHR){},
lajaxError: function(form,formData,jqXHR,textStatus,errorThrown){},
},options);
//loop through every form, 'this' refers to the jquery object (which should be a list of from elements)
this.each(function(index,el){
$(el).submit(function(e){
//prevent submission
e.preventDefault();
//form jquery instance & form data
var $form=$(this);
var formData = new FormData($form[0]);
//catch url where the ajax function is supposed to go
var url=$form.attr('action');
//check if REST based method is assigned
if($form.find('input[name="_method"]').length)
{
var method=$(this).find(':input[name="_method"]').val().toUpperCase();
if(optns.debug)
console.log("'"+method+"' method registered for form submission");
}
//If no REST method is assigned, then check method attr
else if($form.attr('method'))
{
var method=$form.attr('method').toUpperCase();
if(optns.debug)
console.log("'"+method+"' method registered for form submission");
}
//method is not assigned
else
{
var method='GET';
if(optns.debug)
console.log('The form that submitted has no method type assigned. GET method will be assigned as default');
}
//object that will be fed into jquerys ajax method
var ajax_options={
url: url,
method: method,
beforeSend: function(jqXHR,settings){
console.log(jqXHR);
console.log(settings);
if(optns.debug)
console.log('executing beforeSend function');
optns.lajaxBeforeSend($form,formData,jqXHR,settings);
},
success: function(data,textStatus,jqXHR){
if(optns.debug)
console.log('executing success function');
optns.lajaxSuccess($form,formData,data,textStatus,jqXHR)
},
error: function(jqXHR,textStatus,errorThrown){
if(optns.debug)
console.log('error encountered. ajax error function procked');
optns.lajaxError($form,formData,jqXHR,textStatus,errorThrown);
var errors = jqXHR.responseJSON;
console.log(errors);
},
}
//check if files are included in the submitted form if the method is not GET
if($form.find('input:file').length && method!='GET'){
ajax_options.processData=false;
ajax_options.contentType=false;
ajax_options.cache=false;
ajax_options.data=formData;
}
if(optns.debug)
console.log('About to send ajax request');
//sending request here
$.ajax(ajax_options);
if(optns.debug)
console.log('finished with form '+$form+'. Looping to next form if exists');
return false;
});
});
return this;
}
}(jQuery));
HTML
<form class="lajax" action="{{ action('AlbumController#store') }}" method="POST" enctype="multipart/form-data">
<div class="form-group">
<label>Album Name</label>
<input type="text" name="name" class="form-control">
</div>
<div class="form-group">
<label for="coverFile">Album Cover Image</label>
<input name="cover" type="file" id="coverFile">
<p class="help-block">Example block-level help text here.</p>
</div>
<div class="form-group">
<label for="albumFiles">Album Images</label>
<input type="file" name="photos[]" multiple>
</div>
<button type="submit" class="btn btn-primary">Create Album</button>
</form>
I think my JS is not sending my data over to the server but im not sure why. Please help
Did you define a Post route in your route file that exactly point to AlbumController#store Controller method
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/
I checked many posts here regarding same issue but nothing was working, and more or less it behaves like a glitch:
function onbtnclick(){
var user_email=$('#user_email').val();
var send_data = {email:user_email};
$.ajax({
type: 'POST',
url: 'someURL.php',
crossDomain: true,
data:send_data,
dataType: 'text',
success: function(responseData, textStatus, jqXHR) {
alert("Thank you for the mailing list");
},
error: function (responseData, textStatus, errorThrown) {
alert('Your email is already in our mailing list.');
console.log('log e:'+responseData);
console.log('log e:'+textStatus);
console.log('log e:'+errorThrown);
}
});
return false;
}
};
<form name="myform">
<input id="user_email" type="email" name="email" placeholder="Your Email Here" style="width:300px" required><br>
<br><button type="submit" class="leka-button button-style2 offer_button" onclick="onbtnclick()"><h5>SIGN UP</h5></button>
</form>
Simply i'm trying to alert the proper message if the user new to fire success or if he registered to fire error, I tried to remove dataType:'text' or adding 'json' and\with removing crossDomain attribute as well but all didn't give me the reason.
In case this was useful, here is where I fire the AJAX script.
You call the JavaScript when you click on a submit button.
The JavaScript runs. The Ajax request is prepared. The JavaScript finishes. The submit button's default behaviour submits the form. The page unloads. The Ajax request is canceled. The regular form submission takes place.
Get rid of the onclick attribute. Bind your event handlers with JavaScript instead.
$(function () {
var $form = $([name="myform"]); // `name` is obsolete for form elements, give it an ID instead
$form.on('submit', onbtnclick);
function onbtnclick(event) { // Give this function a better name
event.preventDefault(); // Don't submit the form normally
// Then put the rest of your existing code
}
});
I have a django form like :
<form class="myform" action="{% url "create" %}" method="post">{% csrf_token %}
<div class="results"></div>
<label class="input margin-bottom-10">{{form.name}}
<div class="name_error"></div>
</label>
<label class="input margin-bottom-10">{{form.age}}
<div class="age_error"></div>
</label>
<input class="margin-top-10 pull-right" type="submit" value="Confirm" >
</form>
and my jquery is like:
frm = $('.myform')
frm.on('submit', function(event){
create(frm);
});
function create(frm) {
$.ajax({
url : frm.attr('action'), // the endpoint
type : frm.attr('method'), // http method
data: frm.serialize(), // data sent with the post request
// handle a successful response
success : function(response) {
if(response.status == "success"){
var success_message = "<div>some success message</div>)
$('#container_body').html(success_message);
};
if(response.status == "error"){
frm.find('.results').html("<div class='alert alert-mini alert-danger'>"+response.message+"</div>");
};
},
});
};
Here my ajax call is doing good. I am getting proper response but DOM manipulation is wrong..
When I click the submit button and there is error. I want to show the error message on .results class.
When there is error the form with error is shown for a while and disappear and my url page with json reponse is shown.
My form with error message did not stay and redirects to the url page with json response.
What is wrong in here
Your scripts had JS errors and it is submitted. Here is what you need to do to address this. Read inline comments.
frm.on('submit', function(event){
event.preventDefault(); //Prevents the default action from happening and Rayon mentioned
create(frm);
});
Fix your JS errors in success function. Remember JS errors may fail your whole app.
success : function(response) {
if(response.status == "success"){
var success_message = "<div>some success message</div>"; //This line had error in your code
$('#container_body').html(success_message);
} //You don't need a semicolon here
if(response.status == "error"){
frm.find('.results').html("<div class='alert alert-mini alert-danger'>"+response.message+"</div>");
} //You don't need a semicolon here
}// You dont need the redundant comma here which will error out in IE
I have a login page basically connecting to a location, and do a simple post call. I want to redirect the page to somewhere else if a user clicks submit and if post returns 200 or success. If not, return fail.
What would be the simplest way to do it? I am looking into client side redirect.
<html>
<head>
<title>Login</title>
</head>
<body>
<form action="/1.1.1.1:80/login" method="POST">
<p>Username: <input type="text" name="username" /><p>
<p>Password: <input type="password" name="password" /><p>
<p><input type="submit" value="Log In" /></p>
{% module xsrf_form_html() %}
</form>
</body>
</html>
UPDATE:
<html>
<head>
<title>Please Log In</title>
<script src="/Users/src/downloads/app/jquery-2.1.4.min.js" type="text/javascript"></script>
</head>
<body>
<form action="https://1.1.1.1:80/login" method="POST">
#Tried as well, but doesn't redirect <form action="https://google.com" method="POST">
<input class="form-control" type="text" required name="username" placeholder="username">
<input class="form-control" type="password" required name="password" placeholder="Password">
<input class="form-control" type="hidden" required name="eauth" value="pam">
<p><input type="submit" value="Log In" /></p>
{% module xsrf_form_html() %}
</form>
</body>
</html>
<script type="text/javascript">
$('form').submit(function(){
$.ajax({
type: "Post",
url: $('form').attr('action'),
success: function (response) {
window.location = 'http://www.google.com';
//error handling
}
});
//return false so the form does not submit again
return false;
});
</script>
you can post your form by jquery(ajax) and when result back decide what you want to do.
this link should help you
// Variable to hold request
var request;
// Bind to the submit event of our form
$("#foo").submit(function(event){
// Abort any pending request
if (request) {
request.abort();
}
// setup some local variables
var $form = $(this);
// Let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");
// Serialize the data in the form
var serializedData = $form.serialize();
// Let's disable the inputs for the duration of the Ajax request.
// Note: we disable elements AFTER the form data has been serialized.
// Disabled form elements will not be serialized.
$inputs.prop("disabled", true);
// Fire off the request to /form.php
request = $.ajax({
url: "/form.php",
type: "post",
data: serializedData
});
// Callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
// Log a message to the console
console.log("Hooray, it worked!");
});
// Callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// Log the error to the console
console.error(
"The following error occurred: "+
textStatus, errorThrown
);
});
// Callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// Reenable the inputs
$inputs.prop("disabled", false);
});
// Prevent default posting of form
event.preventDefault();
});
include jQuery and Try to use this according your code input
<script type="text/javascript">
$(document).ready(function(){
$('form').submit(function(){
$.ajax({
url: 'your-php-file.php',
dataType: 'html',
success: function(response) {
window.location.href = response;
}
});
});
});
</script>
Try something like this:
Make sure you have downloaded jquery.js file, put it in your directory somewhere, and put this in the head tag
<script src="path to your jquery file" type="text/javascript"></script>
Put this at the end of your html:
<script type="text/javascript">
$('form').submit(function(){
$.ajax({
type: "Post",
url: $('form').attr('action'),
success: function (result) {
if(result.Code == 200) //change this to your status code return
window.location = 'http://www.google.com';
else
//error handling
}
});
//return false so the form does not submit again
return false;
});
</script>
This should capture the form's submit event and instead post it via ajax which will allow you to handle the response however you want.