So I have a one page site, that only shows a login with username and password.
I have the $.ajax fire on the submit click.
What I want is for it remove the login box and load in the page that will have all the content ready for the ajax content to go into.
$.ajax function works and was tested by alert(n); the number for my json array.
What happens is after the box disappears and the page loads, it reverts back to the login box.
$(document).ready(function() {
$('#launchform').click(function() {
$.ajax({
url: 'campaign.json',
dataType: 'JSON',
type: 'GET',
success: function (data) {
console.log(data);
var string = JSON.stringify($('form').serializeArray());
var login = JSON.parse(string);
var username = login[0].value;
var password = login[1].value;
var n = '';
for (var i = 0; i < data.result.length; i++){
if (data.result[i].name == username){
if (data.result[i].id == password){
var n = i;
}
}
}
if(n!=='') {
$(".container").remove();
$("#loginfade").load("test.html");
} else {
alert('Invalid Username/Password Combination.');
}
}
});
});
});
This is a pretty common problem. When you bind to a submit event, you are effectively able to run some logic, but unless you stop it, the event will continue to propagate and will also run the normal submit logic, which causes a full page refresh. This is fairly easy to prevent:
$(document).ready(function() {
$('#launchform').on('click', function(e) {
e.preventDefault(); // Add this
});
});
As stated in another answer, you can also return false;. That is sometimes a better way to do it when using jQuery as it effectively cancels everything. Although, in non-jQuery solutions, it doesn't stop the event bubbling. You can read more details about why here: event.preventDefault() vs. return false
If you are performing this within a <form> element then the form is probably submitting after the ajax call and reloading the page. Try adding:
return false;
to the end of the click event function to prevent the form submitting.
So the above code would look like:
$(document).ready(function() {
$('#launchform').click(function() {
$.ajax({
url: 'campaign.json',
dataType: 'JSON',
type: 'GET',
success: function (data) {
console.log(data);
var string = JSON.stringify($('form').serializeArray());
var login = JSON.parse(string);
var username = login[0].value;
var password = login[1].value;
var n = '';
for (var i = 0; i < data.result.length; i++){
if (data.result[i].name == username){
if (data.result[i].id == password){
var n = i;
}
}
}
if(n!=='') {
$(".container").remove();
$("#loginfade").load("test.html");
} else {
alert('Invalid Username/Password Combination.');
}
}
});
return false;
});
Related
I am working on a form I wish to validate via jQuery $.ajax. The form should only be submitted if a certain condition, data == 1
var preventSubmit = function() {
return false;
var form = $(this),
name = form.find('#name').val(),
email = form.find('#email').val(),
comment = form.find('#comment').val();
$.ajax({
type: "POST",
url: absolute_store_link + '/ajax/comments-filter',
data: {
name: name,
email: email,
comment: comment
},
success: function(data) {
// if data is equal to 1,
// submit form
if (data == 1) {
return true;
}
}
});
};
$("#comment_form").on('submit', preventSubmit);
The submit happens regardless if the condition is met or not.
Where is my mistake?
If I use e.preventDefault();, how can I "undo" it in case if data is equal to 1?
You won't be able to allow the submission of the form with a return value of true because the ajax is happening asynchronously (by the time it completes the function has already finished executing). What you can do is always prevent the form from submitting in the preventSubmit function, then submit it programmatically.
var preventSubmit = function() {
var form = $(this),
name = form.find('#name').val(),
email = form.find('#email').val(),
comment = form.find('#comment').val();
$.ajax({
type: "POST",
url: absolute_store_link + '/ajax/comments-filter',
data: {
name: name,
email: email,
comment: comment
},
success: function(data) {
// if data is equal to 1,
// submit form
if (data == 1) {
form.off();//remove bound events (this function)
form.submit();//manually submit the form
}
}
});
return false;//the return needs to be at the end of the function and will always prevent submission
};
$("#comment_form").on('submit', preventSubmit);
Anything after the return false; will never be executed.
Also, you should be doing form validation on the front-end rather than the back-end. With that being said, you should not remove the validation from the back-end.
One more thing, try doing HTML5 form validation first as that's your first line of defence.
You're looking at something on the lines of:
var validateForm = function(e) {
// prevent the default form action to allow this code to run
e.preventDefault();
var isValid = false,
form = $(this),
name = form.find('#name').val(),
email = form.find('#email').val(),
comment = form.find('#comment').val();
// Validation goes here
// ...
// isValid = true;
if (isValid) {
$.ajax({
type: "POST",
url: absolute_store_link + '/ajax/comments-filter',
data: {
name: name,
email: email,
comment: comment
},
success: function(data) {
// do something with the response. Maybe show a message?
form.submit();
}
});
}
};
I'm developing a post comment system with PHP CodeIgniter framework.When a user comment for a post-it didn't get loaded without page refresh. Here is my ajax code.
var id = $(this).attr("data-id");
// check to see which events this comment already has
var events = $._data( this, 'events' ).keypress;
// Try to find if keypress has already been registered
// registering it twice causes duplicate comments
var hasEvents = false;
for(var i=0;i<events.length;i++) {
if(events[i].namespace == "") {
hasEvents = true;
}
}
if(!hasEvents) {
$.ajax({
url: global_base_url + 'feed/post_comment/' + id,
type: 'POST',
data: {
comment: comment,
csrf_test_name: global_hash,
page: global_page,
hide_prev: hide_prev
},
dataType: 'json',
success: function(msg) {
if (msg.error) {
alert(msg.error_msg);
return;
}
$('#feed-comments-spot-' + id).html(msg.content);
$('#feed-comments-' + id).html(msg.comments);
}
});
}
My form code is:
<div class="feed-comment-area" id="feed-comment-<?php echo $r->ID ?>">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
$(document).ready(function () {
$("#Button1").click(function (evt) {
var fileUpload = $('[id$=FileUpload1]')[0].value.split(",");
var data = new FormData();
for (var i = 0; i < fileUpload.length; i++) {
data.append(fileUpload[i].name, fileUpload[i]);
}
var options = {};
options.url = "Handler.ashx";
options.type = "POST";
options.data = data;
options.contentType = false;
options.processData = false;
options.success = function (result) { alert(result); };
options.error = function (err) { alert(err.statusText); };
$.ajax(options);
evt.preventDefault();
});
});
This was my jquery and below is my handler file code ......
till end i am getting value while debugging but in motto of making upload multiple images at a while i am unable to have any value in handle
handler code
public void ProcessRequest (HttpContext context) {
string filePath = "FileSave//";
foreach (string file in context.Request.Files)
{
HttpPostedFile filed = context.Request.Files[file];
filed.SaveAs(context.Server.MapPath(filePath + filed.FileName));
context.Response.Write("File uploaded");
}
}
You can try this way if you would like to.
$(document).ready(function () {
$("#Button1").click(function (evt) {
evt.preventDefault();
var formdata = new FormData();
var fileInput = $('#sliderFile'); //#sliderFile is the id of your file upload control
if ($(fileInput).get(0).files.length == 0)
{ //show error
return false;
}
else
{
$.each($(fileInput).get(0).files, function (index,value) {
formdata.append(value.name, value);
});
$.ajax({
url: 'Handler.ashx',
type: "POST",
dataType: 'json',
data: data,
processData: false,
contentType:false,
success: function (data) {
if (data.result) {
//return true or any thing you want to do here
}
else {
//return false and display error
}
},
error: function (data) {
//return false and display error
}
});
}
});//button click close
});//document.ready close
Try it and let me know
EDIT: Remember but, HTML5 FormData is not available in older browsers and your code will silently fail. If you need to support older browsers you might need to perform progressive enhancement by testing the capabilities of the browser and falling back to a standard form POST if the browser doesn't support FormData:
if(window.FormData === undefined) {
// The browser doesn't support uploading files with AJAX
// falling back to standard form upload
} else {
// The browser supports uploading files with AJAX =>
// we prevent the default form POST and use AJAX instead
e.preventDefault();
...
}
For more information on this you can see answer I have accepted for one of my questions. It's pretty much clear there what is the issue regarding. Here is the link
EDIT : Just adding these LINK1 and LINK2 for those who come looking for the answer.
use HttpContextBase[] instead of just HttpContext
I have a form that validates php and javascript.
I would like to change the javascript validation to real time. I have it setup so classes and messages are added if user enters proper information or incorrect information after clicking the submit button. This is a validation I have used for awhile and would like to update to be a live validation. I have tried to add onblur(myFunction) etc to the input fields with a corresponding function. That does not seem to work. I am a javascript noob. I realize the script will need quite a bit of overhaul, however can someone point me in the right direction. I realize there is a jquery plugin that does some of this, however I would like to learn how its happening rather than using an existing code.
$(function () {
$('#contact_form').submit(function(e) {
e.preventDefault();
var form = $(this);
var post_url = form.attr('action');
var post_data = form.serialize();
var submit_form = false;
*validation here*
if (pcount == 0 && pcount2 == 0 && pcount3 == 0) {
submit_form = true;
}
if (submit_form) {
$('#loader', form).html('<img src="assets/img/loader.gif" /> Please Wait...');
$.ajax({
type : 'POST',
url : post_url,
data : post_data,
success : function(msg) {
$(form).fadeOut(500, function() {
form.html(msg).fadeIn();
});
}
});
}
});
});
It is not so hard to do, just separate the sending and the validation like this:
$.fn.validateMyForm = function() {
var form = $(this);
/* validation */
if (pcount == 0 && pcount2 == 0 && pcount3 == 0) {
return true;
}
return false;
}
$(function () {
$('#contact_form').submit(function(e) {
e.preventDefault();
var form = $(this);
var post_url = form.attr('action');
var post_data = form.serialize();
if ($(form).validateMyForm()) {
/* ajax sending */
});
}
});
And then add the validation on the blur events where needed:
$("input").blur({
$('#contact_form').validateMyForm();
});
I am trying to make some form validation functions. Here is what I have:
<script>
$(document).ready(function() {
var myObj = {};
$('#username').keyup(function () {
id = $(this).attr('id');
validateUsername(id);
});
function validateUsername(id){
var username = $("#"+id).val();
$.ajax({
url : "validate.php",
dataType: 'json',
data: 'action=usr_id&id=' + username,
type: "POST",
success: function(data) {
if (data.ok == true) {
$(myObj).data("username","ok");
} else {
$(myObj).data("username","no");
}
}
});
} // end validateusername function
$('#submit').click(function(){
if (myObj.username == "ok") {
alert("Username OK");
} else {
alert("Username BAD");
}
});
}); // end doc ready
So you can see, when a key is pressed in the textbox, it checks if it's valid. The "data.ok" comes back correctly. The problem is based on the response, I define $(myObj).username. For some reason, I can't get this value to work outside the validateusername function. When clicking the submit button, it has no idea what the value of $(myObj).username is.
I need to use something like this, because with multiple form fields on the page to validate, I can do something like:
if (myObj.username && myObj.password && myObj.email == "ok")
... to check all my form fields before submitting the form.
I know I must just be missing something basic.... any thoughts?
EDIT: SOLVED
All I had to do was change var myObj = {}; to myObj = {}; and it's working like a charm. I think I've been staring at this screen waaaaay too long!
You're not accessing the data that you stored properly. Access the username value this way:
$(myObj).data("username")
Resources:
Take a look at jQuery's .data() docs.
Very simple jsFiddle that shows how to properly set and retrieve data with jQuery's .data() method.
I would store the promise in that global variable and then bind an event to the done event within your submit button click.
$(document).ready(function() {
var myObj = false;
$('#username').keyup(function () {
id = $(this).attr('id');
validateUsername(id);
});
function validateUsername(id){
var username = $("#"+id).val();
myObj = $.ajax({
url : "validate.php",
dataType: 'json',
data: 'action=usr_id&id=' + username,
type: "POST",
success: function(data) {
$('#username').removeClass('valid invalid');
if (data.ok == true) {
$('#username').addClass('valid');
}
else {
$('#username').addClass('invalid');
}
}
});
} // end validateusername function
$('#submit').click(function(){
// if myObj is still equal to false, the username has
// not changed yet, therefore the ajax request hasn't
// been made
if (!myObj) {
alert("Username BAD");
}
// since a deferred object exists, add a callback to done
else {
myObj.done(function(data){
if (data.ok == true) {
alert("Username BAD");
}
else {
alert("Username OK");
}
});
}
});
}); // end doc ready
you may want to add some throttling to the keyup event though to prevent multiple ajax requests from being active at once.