Pass variables to URL in ajax - javascript

I have the below ajax call in which I am trying to post the registration data directly to URL, but is there anyway I can store those variables and then pass it into the URL. Please help thank you in advance.
You can see the Script.js in this plunker
jquery:
$(function() {
/* Registration form for the website */
/* validation */
$("#register-form").validate({
rules: {
firstName: {
required: true
},
lastName: {
required: true
},
userName: {
required: true,
minlength: 4
},
email: {
required: true,
email: true
},
password: {
required: true,
minlength: 8,
maxlength: 15
},
cpassword: {
required: true,
equalTo: '#password'
},
},
messages: {
userName: "please enter a valid user name",
password: {
required: "please provide a password",
minlength: "password at least have 8 characters"
},
email: "please enter a valid email address",
cpassword: {
required: "please retype your password",
equalTo: "password doesn't match !"
}
},
submitHandler: submitForm
});
/* validation */
/* form submit */
function submitForm() {
var data = $("#register-form").serialize();
// var data={
// firstName: $('#firstName').val(),
// }
$.ajax({
url: 'http://localhost:8000?userName=&password=&firstName=&lastName=&email=',
type: 'POST',
data: data,
beforeSend: function() {
$("#error").fadeOut();
$("#btn-submit").html('<span class="glyphicon glyphicon-transfer"></span> sending ...');
},
success: function(data) {
if (data === 0) {
$("#error").fadeIn(1000, function() {
$("#error").html('<div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span> Sorry email already taken !</div>');
$("#btn-submit").html('<span class="glyphicon glyphicon-log-in"></span> Create Account');
});
} else if (data == 1) {
$("#btn-submit").html('<img src="btn-ajax-loader.gif" /> Signing Up ...');
} else {
$("#error").fadeIn(1000, function() {
$("#error").html('<div class="alert alert-danger"><span class="glyphicon glyphicon-info-sign"></span> ' + data + ' !</div>');
$("#btn-submit").html('<span class="glyphicon glyphicon-log-in"></span> Create Account');
});
}
}
});
return false;
}
});

url: 'http://localhost:8000?userName=&password=&firstName=&lastName=&email=',
type: 'POST',
data: data,
become
url: 'http://localhost:8000?' + data,
type: 'GET',
//data: data,

Your AJAX URL is wrong, you do not need to type in the full address. The Serialize method should do that for you. All you need is localhost:8000? + data. And as #zer00ne said, never use a GET if your sending in a password, it will show up on the URL. As a rule of thumb, anything sent in a form should be a POST request, unless some rare cases which I am not aware of.
My suggestion:
$.ajax({
url: 'http://localhost:8000?',
type: 'POST',
data: data,
This way your sending in your information to the proper place and securely.

Related

How can I send ajax call after validation is correct?

I am trying to send data to my heroku database, i have user input from a html file and sending it through to my jquery file, my validation works but i wish to send my ajax call after this is valid, i.e. upon the submit button clicked. It doesn't seem to get to my ajax call( the ajax works).The success bit is my attempt to show success message (swal is sweetalert library & and not sure is success works). I believe my submit handler is at fault.
// * html code of form *
<form action="" name="registration"><br>
<label for="email">Email</label><br>
<input type="email" name="email" id="email" placeholder="example#example.com" /><br><br>
<label for="password">Password</label><br>
<input type="password" name="password" id="password"
placeholder="●●●●●" /><br><br>
<label for="repassword">Re-Type Password</label><br>
<input type="password" name="repassword" id="repassword"
placeholder="●●●●●" /><br><br>
<input type="checkbox" name="agreeBox" id="agreeBox" />
<label for="agree-boxId">I agree
to all statements in <a href="../documents/terms_of_service" class="term-service">Terms of
Service</a></label><br><br>
<button type="submit" id="signUp">Register</button>
<div class="signup-image">
<figure><img src="images/signup-image.png" alt="sign up image"></figure>
</div>
</form>
// ***** my content in Jquery file ******
$("form[name='registration']").validate({
// *** Validation Rules ***
rules: {
email: {
required: true,
email: true
},
password: {
required: true,
minlength: 8,
maxlength: 60
},
repassword: {
required: true,
minlength: 8,
maxlength: 60,
equalTo: '#password'
},
agreeBox: {
required: true
}
},
// *** Validation error messages ***
messages: {
email: "Please enter a valid email address",
password: {
required: "Please provide a password",
minlength: "Your password must be at least 8 characters long",
maxlength: "Your password can't be more than 60 characters"
},
repassword: {
required: "Please provide your password",
minlength: "Your password must be at least 8 characters long",
maxlength: "Your password can't be more than 60 characters",
equalTo: "Your password must equal your first password"
},
agreeBox: {
required: "Please read conditions and tick box"
}
},
submitHandler: function () {
ev.preventDefault();
var userEmail = $('input[id="emailId"]').val();
var userPass = $('input[id="passId"]').val();
$.ajax({
method: 'POST',
url: 'my database (this has been replaced)',
data: JSON.stringify({
name: userEmail,
password: userPass,
status: 'user',
}),
contentType: "Application/json",
dataType: "json",
success: function () {
swal("Lets Go Shopping!", {
buttons: {
confirm: "Go Shopping",
},
})
.then(() => {
window.location = 'index.html';
});
}
})
return false;
}
});
The issue that you have is with the AJAX call syntax or usage. You have used both success and then calls simultaneously. You need to have either success or then.
If you need success then it should be inside then like so.
$.ajax({
method: 'POST',
url: 'my database (this has been replaced)',
success: function( resp ) {
console.log('the success function', resp );
},
error: function( req, status, err ) {
console.log( 'Oops, something went wrong!!!', status, err );
}
});
or you can use .then() like so
$.ajax({
method: 'POST',
url: 'my database (this has been replaced)'
}).then( function( resp ) {
console.log('the success function', resp );
},
function( req, status, err ) {
console.log( 'Oops, something went wrong!!!', status, err );
});
Its like $.ajax({}).then(success, err)
Check out this post for further reading.

Form validation not working before submit with ajax method

I creating submit form with ajax but, i cant validate form before submit..
iam using codeigniter 3 with jquery validate
my code working, but i need set form like min lenghth, email format etc
this my code before (with input class="required")
$(document).ready(function(){
$(".save_post").click(function(){
if ($("#post_val").valid()) {
$("#post_val").submit();
}else{
return false;
}
var data = $('.post_form').serialize();
$.ajax({
type: 'POST',
url: "<?= base_url() ?>admin_ajx/post_ajx/update_post",
data: data,
success: function(data) {
alert("Post Success!");
}
});
});
});
i trying to modified that code to this, but code its not working
$(document).ready(function(){
$(".save_post").click(function(){
$('#post_val').validate({
rules: {
title: {
required: true,
minlength: 10
},
image: {
required: true,
minlength: 5
}
},
messages: {
title:{
required: 'title error',
minlength: 'kurang dari 10'
},
image: {
required: true,
minlength: 5
}
}
});
var data = $('.post_form').serialize();
$.ajax({
type: 'POST',
url: "<?= base_url() ?>admin_ajx/post_ajx/update_post",
data: data,
success: function(data) {
alert("Post Success!");
}
});
});
});
my form like this
<form action="<?= base_url() ?>admin/add-post" method="POST" role="form" class="post_form" id="post_val">
<input type="text" name="title" class="form-control" placeholder="Title" id="post_title" onkeyup="auto_alias();">
<input class="form-control input-sm required" type="text" name="image" id="img_url" readonly="readonly" onclick="openKCFinder(this)" style="cursor:pointer" />
<a class="btn btn-sm btn-info save_post" onClick="CKupdate();$('#article-form').ajaxSubmit();">POST</a>
</form>
i expect, i can validate that form before submit
You are using jquery validate in an incorrect manner.
For starters you don't nest validate in a click event, and then you don't run your submit code independently. Instead you run it in the submit callback of validate.
A sample looks like this:
$("#ajax-contact-form").validate({
errorClass: "text-danger",
rules: {
name: {
required: true,
},
phone: {
required: false,
digits: true,
minlength: 7,
},
email: {
required: true,
email: true,
},
message: {
required: true,
minlength: 10,
},
},
submitHandler: function (form, e) {
e.preventDefault(); // important to prevent issues!!!
$("#contact-button").html('Sending...');
var str = $(form).serialize(); // to get your serialized form
$.ajax({
type: "POST",
url: base_path + "/contact/send",
data: str,
dataType: 'json',
success: function (data) {
var result = '';
if (data.status === 'success') {
$(form).trigger('reset');
result = '<div class="alert alert-success"><i class="fa fa-check"></i> ' + data.msg + '</div>';
} else {
result = '<div class="alert alert-danger"><i class="fa fa-exclamation-circle"></i> ' + data.msg + '</div>';
}
$("#contact-button").html('Send Message');
$('#note').html(result);
setTimeout(function () {
$("#note").fadeOut();
}, 8000);
}
});
},
});
also I would remove $('#article-form').ajaxSubmit(); from this onClick="CKupdate();$('#article-form').ajaxSubmit();". It holds no reference to current code, and it won't work with validate.

unable to send data via this.serialize

I am using following function to validate and send data to the php server:
$(document).ready(function () {
$(function() {
// Setup form validation on the #register-form element
$("#register_form").validate({
// Specify the validation rules
rules: {
register_username: "required",
register_password: "required",
register_email: {
required: true,
email: true
},
register_confirm_password: {
required: true,
equalTo: '#register_password'
},
},
// Specify the validation error messages
messages: {
register_username: "Please enter your username",
register_password: "Please enter your password",
register_confirm_password: {
required: "Please provide a password",
equalTo:"Please enter password same as above."
},
register_email: "Please enter a valid email address",
},
submitHandler: function(form) {
var pdata = $(this).serialize();
alert(pdata);
$.ajax({
type: 'POST',
url: 'http://localhost/quiz/index.php/signin',
data: $(this).serialize(),
dataType : 'json',
success: function(data) {
if (data.success){
console.log("Form is submitted.data is" + data.success);
$.each(data, function() {
$.each(this, function(k, v) {
console.log("key; " + k);
console.log("value; " + v);
});
});
}
else
{
console.log("The data returned is:" + data.success);
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
return false;
},
});
});
});
All the validation works, but the issue is with the line:
var pdata = $(this).serialize();
I am getting empty pdata:
alert(pdata);
I don't know why the data is not serialized here. Please help me to solve this.
Don't serialize $( this )
Try serializing the form instead.
$( "#register_form" ).serialize();
$(this) isn't what you think it is anymore. It's not #register_form, but instead the submitHandler function.
If you do console.log(pdata) you should see the function definition in your console.
The scope of the submitHandler function is not the form element, so this is not pointing to the element you require. It does however provide you with a parameter, which you've named form, that you can use instead, like this:
submitHandler: function(form) {
$.ajax({
type: 'POST',
url: 'http://localhost/quiz/index.php/signin',
data: $(form).serialize(),
// your code...

Error: jQuery jquery.min.js?_=1420285687057:4 Uncaught TypeError: undefined is not a function

I have problem with jquery validate plugn and history API, when i click few times
i have error jquery.min.js?_=1420288991396:4 Uncaught TypeError: undefined is not a function, when I comment a fragment with validate, script works fine. How concat this script.
In file script.js i have:
$(document).ready(function(){
$("#loginForm").validate({
rules: {
username: {
required: true,
minlength: 2
},
password: {
required: true,
minlength: 5
},
},
messages: {
username: {
required: "Please enter a username",
minlength: "Your username must consist of at least 2 characters"
},
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
},
submitHandler: function() {
var username=$("#usernameLogin").val();
var password=$("#passwordLogin").val();
var dataString = 'username='+username+'&password='+password+'&tag=login';
if($.trim(username).length>0 && $.trim(password).length>0){
$.ajax({
type: "POST",
url: "include/help4meApi.php",
data: dataString,
cache: false,
success: function(data){
if(data){
if($("#rememberMe:checked").val()){
checkCookie(username);
}
window.location.href = "index.php";
}
else{
$("#error").html("<label class='error'>Wrong password or username!</label>");
console.log("Wrong password or username!");
}
}
});
}
return false;
}
});
// validate signup form on keyup and submit
$("#signupForm").validate({
rules: {
firstname: {
required: true,
minlength: 3
},
lastname: "required",
username: {
required: true,
minlength: 2
},
password: {
required: true,
minlength: 5
},
confirm_password: {
required: true,
minlength: 5,
equalTo: "#password"
},
email: {
required: true,
email: true
}
},
messages: {
firstname: {
required: "Please enter your firstname",
minlength: "Your firstname must consist of at least 3 characters"
},
lastname: "Please enter your lastname",
username: {
required: "Please enter a username",
minlength: "Your username must consist of at least 2 characters"
},
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
confirm_password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long",
equalTo: "Please enter the same password as above"
},
email: "Please enter a valid email address",
},
submitHandler: function() {
var username=$("#username").val();
var password=$("#password").val();
var firstname=$("#firstname").val();
var lastname=$("#lastname").val();
var email=$("#email").val();
var dataString = 'username='+username+'&password='+password+'&firstname='+firstname+'&lastname='+lastname+'&email='+email+'&tag=register';
if($.trim(username).length>0 && $.trim(password).length>0){
$.ajax({
type: "POST",
url: "include/help4meApi.php",
data: dataString,
cache: false,
success: function(data){
if(data){
console.log(data);
$(".register_notification").html("<label class='error' style='background:#6DC066'>Register successfully!</label>");
}
else{
$(".register_notification").html("<label class='error'>Username already exists, please choose another one!</label>");
}
}
});
}
return false;
}
});
// propose username by combining first- and lastname
$("#username").focus(function() {
var firstname = $("#firstname").val();
var lastname = $("#lastname").val();
if (firstname && lastname && !this.value) {
this.value = firstname + "." + lastname;
}
});
$("footer a").click(function(e){
//e.preventDefault();
/*
if uncomment the above line, html5 nonsupported browers won't change the url but will display the ajax content;
if commented, html5 nonsupported browers will reload the page to the specified link.
*/
//get the link location that was clicked
pageurl = $(this).attr('href');
//to get the ajax content and display in div with id 'content'
$.ajax({url:pageurl,success: function(data){
$('#login_box').html(data);
}});
//to change the browser URL to 'pageurl'
if(pageurl!=window.location){
window.history.pushState({path:pageurl},'',pageurl);
}
return false;
});
});
$(window).bind('popstate', function() {
if(!location.pathname.localeCompare('/login.php')){
$.ajax({url:location.pathname,success: function(data){
$('body').html(data);
}});
}
else{
$.ajax({url:location.pathname,success: function(data){
$('#login_box').html(data);
}});
}
});
From jQuery library:
// Get transport
transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
// If no transport, we auto-abort
if ( !transport ) {
done( -1, "No Transport" );
} else {
jqXHR.readyState = 1;
// Send global event
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = setTimeout(function() {
jqXHR.abort("timeout");
}, s.timeout );
}
try {
state = 1;
transport.send( requestHeaders, done );
} catch ( e ) {
// Propagate exception as error if not done
if ( state < 2 ) {
done( -1, e );
// Simply rethrow otherwise
} else {
throw e;
}
}
}
it shows throw e.
I can't think of any reason why using the browser's "back" button would cause the JavaScript to fail. Everything should be cached and continue to work as before.
The error you're getting is similar to the error you'd get if you failed to include the plugin.
Here is how you're including the jQuery Validate plugin...
<script src="http://jqueryvalidation.org/files/dist/jquery.validate.js"></script>
Notice how you're hotlinking to the plugin hosted on the developer's own domain. (likely for his demos and/or to download.) This error might be caused by a timing issue, the plugin not loading fast enough from this URL.
The developer has provided his plugin on two different free CDN services where "hotlinking welcome". So instead of leaching the plugin directly from his domain, try hotlinking to the CDN links provided here.
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.js"></script>

jquery validation - submitting form with enter key

I am new to javascript and jquery and I'm trying to submit a form which is validated using the jquery validation plugin using the enter key. This is my code but the form is not being submitted as the alert isn't showing when you press enter. I'm not sure what exactly is happening. I think the page is simply being reloaded when i press enter. There's certainly no validation
<script>
$(document).ready(function() {
jQuery.validator.setDefaults({
errorPlacement: function(error, element) {
error.appendTo('#invalid_' + element.attr('id'));
}
});
var validator = $("#login_form").validate({
rules: {
user_email: {
required: true,
email: true
},
password: {
required: true
}
},
messages:{
user_email:{
required:"Email required",
email: "Must be a valid email"
},
password: {
required: "Password required"
}
},
submitHandler: function(form) {
alert('submitted');
$.ajax({
type: "POST",
url: "ajax/check_login.php",
data: $(form).serialize(),
timeout: 3000,
success: function(resp) {
if (resp == 'error') {
$('#login_error').html('Invalid login');
} else {
load_user_area();
}
},
error: function(e) {alert('failed' + e);}
});
return false;
}
});
$(document).keydown(function(e) {
if (e.keyCode == 13) { $('#login_form').submit(); }
});
});
</script>
Thanks in advance for any help!

Categories

Resources