I am trying to do a form validation function with Ajax submission. For some reason the validation doesn't work and when it submits, my server gets the empty fields (when I am testing for the validation) but it shows that it tried to post to the same page... I don't know why.
Form:
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
<form id='form' novalidate method="post" class='m-2 p-1'>
<div class='row'>
<div class='col p-1'>
<div class="form-floating mb-3">
<input required type="text" name='First Name' class="form-control" id="fname" placeholder="First Name">
<label for="fname">First Name<span class='red' aria-label='required'> *</span></label>
</div>
</div>
<div class='col p-1'>
<div class="form-floating mb-3">
<input required type="text" name='Last Name' class="form-control" id="lname" placeholder="Last Name">
<label for="lname">Last Name</label>
</div>
</div>
</div>
<div class='row'>
<div class='col p-1'>
<div class="form-floating mb-3">
<input required type="email" name='Email' class="form-control" id="email" placeholder="Email">
<label for="lname">Email <span class='red' aria-label='required'> *</span></label>
</div>
</div>
<div class='col p-1'>
<div class="form-floating mb-3">
<select required name='Reason For Contacting' class="form-control" id="reason" placeholder="Reason For Contacting">
<option value='Feedback' selected>Feedback</option>
<option value='other'>Other</option>
</select>
<label for="why">Reason For Contacting<span class='red' aria-label='required'> *</span></label>
</div>
</div>
</div>
<div class='row'>
<div class='col p-1'>
<div class="form-floating mb-3">
<textarea required name='Comments' class="form-control" id="comment" placeholder="Your Comments"></textarea>
<label for="comment">Your Comments<span class='red' aria-label='required'> *</span></label>
</div>
</div>
</div>
<div class='row'>
<div class='col p-1'>
<button class='form-control btn btn-outline-primary' id='submit'>Send</button>
</div>
</div>
</form>
My JS File:
$(document).ready(() => {
autosize($('textarea'))
$('#submit').click((e) => {
if (validate() == true) {
sendForm();
} else {
error(validate())
}
})
})
var errors;
window.onerror = function(msg, url, linenumber) {
alert('Error message: ' + msg + '\nURL: ' + url + '\nLine Number: ' + linenumber);
return true;
}
function validate() {
elements = $(':input')
elements.each((element) => {
element = $(element).get()
if (element.value === '' || !email(element)) {
errors += element.name + " is invalid."
} else {
return;
}
})
if (errors) {
return errors
} else true;
}
function sendForm() {
name = $('input[name="First Name"]').val().trim() + " " + $('input[name="Last Name"]').val().trim()
email = $('input[name="Email"]').val().trim()
why = $("select").val().trim()
comments = $('textarea').val().trim()
data = {
"name": name,
"email": email,
"reason": why,
"text": comments
}
$.ajax({
type: 'POST',
url: 'https://admin.bekesbikes.tk/contact',
crossDomain: true,
data: data,
dataType: 'json',
success: (responseData, textStatus, errorThrown) => {
new Notify({
title: 'Submitted!',
text: 'Your feedback has been recorded!\n\nWe will get back to your email shortly!\n\nHope to see you soon!',
effect: 'slide',
status: 'success',
speed: 1000,
autoclose: true
})
$(':input').val('');
$('select').val('Feedback')
},
error: (responseData, textStatus, errorThrown) => {
new Notify({
title: 'Could not submit!',
text: 'The form could not be submitted.\n\nPlease try again or come back later!\n\nSorry for the inconvenience.',
effect: 'slide',
customIcon: "<img src='https://www.flaticon.com/svg/vstatic/svg/753/753345.svg?token=exp=1616679486~hmac=4f66bb69b263e9e4d9be5038a16cc41d' width='50px'>",
status: 'error',
speed: 1000,
autoclose: true
})
}
});
}
function error(text) {
new Notify({
title: 'Form Fields Are Not Correct',
text: text,
effect: 'slide',
status: 'info',
speed: 1000,
autoclose: true
})
}
function send() {
if (validate()) {
sendForm()
} else {
error(validate())
}
}
function email(element) {
if (element.type === 'email' && /^[^\s#]+#[^\s#]+$/.text(element.value)) {
return true;
} else if (element.type !== 'email') {
return true;
} else {
return false;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Where I go when I submit (the form is at this URL):
Any Idea what I should do? I am using node.js with express.js.
I added: e.preventDefault() to my submit event handler but now when I submit the form without filling in anything, I get this notification:
I changed your click handler:
default prevention,
validate() as variable so that it runs only once,
the errors declaration
empty string instead of undefined,
your validate() function
excluded button using :not(),
changed arrow function to ordinary anonymous function,
used this instead of element, which was only an index,
added a return to the last else,
and your email() function
sourced the email validation out to an own function.
I also deleted send(), as it was not used, declared the variables in sendForm() with var and added many semicolons -> maybe in your code one is already missing and you are hoping that the js error correction will add them automatically...
Finally i added the param showIcon to your Notify objects (that was the 'undefined' part ;)
$(document).ready(() => {
autosize($('textarea'))
$('#form').submit((e) => {
e.preventDefault();
var validated = validate();
if (validated == true) {
sendForm();
} else error(validated);
});
var errors = '';
window.onerror = function(msg, url, linenumber) {
alert('Error message: ' + msg + '\nURL: ' + url + '\nLine Number: ' + linenumber);
return true;
}
function validate() {
elements = $(':input:not(button)');
elements.each(function() {
if (this.value === '' || !email(this)) {
errors += this.name + " is invalid.";
} else return;
});
if (errors) {
return errors;
} else return true;
}
function sendForm() {
var name = $('input[name="First Name"]').val().trim() + " " + $('input[name="Last Name"]').val().trim();
var email = $('input[name="Email"]').val().trim();
var why = $("select").val().trim();
var comments = $('textarea').val().trim();
var data = {
"name": name,
"email": email,
"reason": why,
"text": comments
};
$.ajax({
type: 'POST',
url: 'https://admin.bekesbikes.tk/contact',
crossDomain: true,
data: data,
dataType: 'json',
success: (responseData, textStatus, jqXHR) => {
new Notify({
title: 'Submitted!',
text: 'Your feedback has been recorded!\n\nWe will get back to your email shortly!\n\nHope to see you soon!',
effect: 'slide',
status: 'success',
speed: 1000,
autoclose: true,
showIcon: false
});
$(':input').val('');
$('select').val('Feedback');
},
error: (jqXHR, textStatus, errorThrown) => {
new Notify({
title: 'Could not submit!',
text: 'The form could not be submitted.\n\nPlease try again or come back later!\n\nSorry for the inconvenience.',
effect: 'slide',
customIcon: "<img src='https://www.flaticon.com/svg/vstatic/svg/753/753345.svg?token=exp=1616679486~hmac=4f66bb69b263e9e4d9be5038a16cc41d' width='50px'>",
status: 'error',
speed: 1000,
autoclose: true,
showIcon: true
});
}
});
}
function error(text) {
new Notify({
title: 'Form Fields Are Not Correct',
text: text,
effect: 'slide',
status: 'info',
speed: 1000,
autoclose: true,
showIcon: false
})
}
function validateEmail(email) {
const re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
function email(element) {
if (element.type === 'email' && validateEmail(element.value)) {
return true;
} else if (element.type !== 'email') {
return true;
} else return false;
}
});
Related
I am using some javascript to post my form but I dont want to have to submit each form field is there a way I can serlize this to an object in .net so that it will bring in all the form contents.
section Scripts {
<script>
function confirmEdit() {
swal({
title: "MIS",
text: "Case Created your Case Number is " + $("#Id").val(),
icon: "warning",
buttons: true,
dangerMode: true,
}).then((willUpdate) => {
if (willUpdate) {
$.ajax({
url: "/tests/edit/" + $("#Id").val(),
type: "POST",
data: {
Id: $("#Id").val(),
Name: $("#Name").val()
},
dataType: "html",
success: function () {
swal("Done!", "It was succesfully edited!", "success")
.then((success) => {
window.location.href = "/tests/index"
});
},
error: function (xhr, ajaxOptions, thrownError) {
swal("Error updating!", "Please try again", "error");
}
});
}
});
}
</script>
}
asp.net core will automatically bind json data using the [FromBody] attribute.
data: {
id: $("#Id").val(),
name: $("#Name").val()
},
and then in your controller
[HttpPost("/tests/edit/")]
public IActionResult Process([FromBody] MyData data){ ... }
where MyData is
public class MyData
{
public string Id {get;set;}
public string Name {get;set;}
}
section Scripts { function confirmEdit() {
swal({ title: "MIS", text: "Case Created your Case Number is " + $("#Id").val(), icon: "warning", buttons: true, dangerMode: true, }).then((willUpdate) => { if (willUpdate) {
var obj = { Id: $("#Id").val(), Name: $("#Name").val() }
$.ajax({ url: "/tests/edit/" + $("#Id").val(), type: "POST", data: JSON.Stringify(obj), dataType: "html", success: function () { swal("Done!", "It was succesfully edited!", "success") .then((success) => { window.location.href = "/tests/index" }); }, error: function (xhr, ajaxOptions, thrownError) { swal("Error updating!", "Please try again", "error"); } }); } }); } }
in c# use
public ActionResult FormPost(MyData obj)
Please refer to the following methods to submit the form data to action method:
using the serialize() method to serialize the controls within the form.
#model MVCSample.Models.OrderViewModel
<h4>OrderViewModel</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Showsummary" asp-controller="Home" method="post" class="signup-form">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="OrderId" class="control-label"></label>
<input asp-for="OrderId" class="form-control" />
<span asp-validation-for="OrderId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="OrderName" class="control-label"></label>
<input asp-for="OrderName" class="form-control" />
<span asp-validation-for="OrderName" class="text-danger"></span>
</div>
<div id="packages">
#for (int i = 0; i < Model.Packages.Count; i++)
{
<div class="form-group">
<label asp-for="#Model.Packages[i].Pid" class="control-label"></label>
<input asp-for="#Model.Packages[i].Pid" class="form-control" />
<span asp-validation-for="#Model.Packages[i].Pid" class="text-danger"></span>
<br />
<label asp-for="#Model.Packages[i].PackageTitle" class="control-label"></label>
<input asp-for="#Model.Packages[i].PackageTitle" class="form-control" />
<span asp-validation-for="#Model.Packages[i].PackageTitle" class="text-danger"></span>
</div>
}
</div>
</form>
</div>
</div>
<div>
<input type="button" id="summary" value="Summary" />
<div id="page_3">
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(function () {
$("#summary").click(function () {
console.log("calling summary");
event.preventDefault();
$.ajax({
type: "POST",
url: "/Home/Showsummary", //remember change the controller to your owns.
data: $("form.signup-form").serialize(),
success: function (data) {
console.log(data)
},
failure: function (response) {
console.log(response.responseText);
},
error: function (response) {
console.log(response.responseText);
}
});
});
});
</script>
Code the the action method:
[HttpPost]
public PartialViewResult Showsummary(OrderViewModel model)
{
try
{
//...
return PartialView("OrderSummary", model);
}
catch
{
return PartialView("OrderSummary", model);
}
}
After clicking the button, the result like this:
As we can see that, we could get the element's value in the form and even the nested entity.
Note: Only "successful controls" are serialized to the string. No submit button value is serialized since the form was not submitted using a button. For a form element's value to be included in the serialized string, the element must have a name attribute. Values from checkboxes and radio buttons (inputs of type "radio" or "checkbox") are included only if they are checked. Data from file select elements is not serialized.
Create a JavaScript object, and post it to action method.
Change the JavaScript script as below:
$(function () {
$("#summary").click(function () {
console.log("calling summary");
event.preventDefault();
//create a object to store the entered value.
var OrderViewModel = {};
//using jquery to get the entered value.
OrderViewModel.OrderId = $("input[name='OrderId']").val();
OrderViewModel.OrderName = $("input[name='OrderName']").val();
var packages = [];
//var count = $("#packages>.form-group").length; //you could use it to check the package count
$("#packages>.form-group").each(function (index, item) {
var package = {}
package.Pid = $(item).find("input[name='Packages[" + index + "].Pid']").val();
package.PackageTitle = $(item).find("input[name='Packages[" + index + "].PackageTitle']").val();
packages.push(package);
});
//add the nested entity
OrderViewModel.Packages = packages;
$.ajax({
type: "POST",
url: "/Home/Showsummary", //remember change the controller to your owns.
data: OrderViewModel,
success: function (data) {
console.log(data)
$('#page_3').html(data);
},
failure: function (response) {
console.log(response.responseText);
},
error: function (response) {
console.log(response.responseText);
}
});
});
});
By using the above code, I could also get the submit entity, you could refer to it.
I want validation onclick. I want that before sending data, validate function run, if there is an empty field then it show amessage and data should not be send to php file. else if there is no empty fields then it should send data to php file.Form and functions are given below
<form role="form" id="schclass_form" name="schclass_form">
<div class="form-group">
<label>Enter Class Name</label>
<input class="form-control" type="text" name="class1" id="class1" placeholder="For Example: 'one'">
</div>
<div class="addmore">
<button type="button" class="btn btn-default" id="addmoreclass">Add More</button>
</div>
<button type="button" class="btn btn-default" onClick="schclass(this.id)">Submit</button>
<button type="reset" class="btn btn-default">Reset</button>
</form>
function validateForm1() {
$('#schclass_form input[type="text"]').each(function(){
var data=""+$(this).val();
if(data=="")
{
swal("Oops...", "Please fill the empty fields first", "error");
}
});
}
here is function which is sending data to php file.
function schclass(a) {
if ($("#" + a).is("[disabled=disabled]")) {
return false
} else {
$("#" + a).attr("disabled", "disabled");
swal("Wait", "Request Initiate, Please Wait....", "info");
var b = $("#schclass_form").serialize() + "&type=schClass;
$.ajax({
type: "POST",
url: "include/function.php",
data: b,
cache: false,
success: function(c) {
try {
c = JSON.parse(c)
} catch (d) {
console.log(d);
swal("Oops...", "Error: Wrong response", "error");
return;
}
if ($.trim(c.result) == "success") {
swal("Success", "Message: "+c.message, "success");
} else {
swal("Oops...", "Error: "+c.message, "error");
}
},
error: function(e, c, d) {
swal("Oops...", "Error: "+d, "error");
}
})
}
$("#" + a).removeAttr("disabled");
return false;
}
I suggest making the validateForm1() function return true/false if valid/invalid, then calling it from an if statement in your schclass(a) function, if it returns true then submit, else don't submit.
Here is your code with the suggested edits:
<form role="form" id="schclass_form" name="schclass_form">
<div class="form-group">
<label>Enter Class Name</label>
<input class="form-control" type="text" name="class1" id="class1" placeholder="For Example: 'one'">
</div>
<div class="addmore">
<button type="button" class="btn btn-default" id="addmoreclass">Add More</button>
</div>
<button type="button" class="btn btn-default" onClick="schclass(this.id)">Submit</button>
<button type="reset" class="btn btn-default">Reset</button>
</form>
function validateForm1() {
var valid = true;
$('#schclass_form input[type="text"]').each(function(){
var data=""+$(this).val();
if(data=="")
{
valid = false;
}
});
return valid;
}
function schclass(a) {
if ($("#" + a).is("[disabled=disabled]")) {
return false
} else {
if (validateForm1()) {
$("#" + a).attr("disabled", "disabled");
swal("Wait", "Request Initiate, Please Wait....", "info");
var b = $("#schclass_form").serialize() + "&type=schClass;
$.ajax({
type: "POST",
url: "include/function.php",
data: b,
cache: false,
success: function(c) {
try {
c = JSON.parse(c)
} catch (d) {
console.log(d);
swal("Oops...", "Error: Wrong response", "error");
return;
}
if ($.trim(c.result) == "success") {
swal("Success", "Message: "+c.message, "success");
} else {
swal("Oops...", "Error: "+c.message, "error");
}
},
error: function(e, c, d) {
swal("Oops...", "Error: "+d, "error");
}
})
} else {
swal("Oops...", "Please fill the empty fields first", "error");
}
}
$("#" + a).removeAttr("disabled");
return false;
}
I'm working on a simple CRUD application where I have a sign in, sign up, and account section for the user. Once the user signs in, then clicks account, there is the option to edit and save your changes. You'll notice I have "here is where you want to change the disable to true" and "here is where you will update the user information in the database". This is where I am supposed to implement the code. How do I actually get those edit and save buttons to work through javascript? Here is my code:
HTML:
<nav>
<div>HOME</div>
<div>ABOUT</div>
<div>SPEAKERS</div>
<div>INFO</div>
<div class="join-button">
JOIN IN
<div class="join-holder">
<div class="sign-in">
<form>
<h2>Sign In</h2>
<label>User Name:</label>
<input id="username" type="text" value="name#name.com">
<label>Password:</label>
<input id="siPW" type="password" value="12345678">
<input class="submit-button si-submit" type="submit">
</form>
</div>
<div class="sign-up">
<form>
<h2>Sign Up</h2>
<label>Name:</label>
<input id="fullName" type="text" value="name">
<label>Email:</label>
<input id="email" type="email" value="name#name.com">
<label>Password:</label>
<input id="pw" type="password" value="12345678">
<input class="submit-button su-submit" type="submit">
</form>
</div>
</div>
</div>
<div class="account">Account</div>
<div class="signOut">Sign Out</div>
</nav>
<div class="home">
Home
</div>
JS:
function setBindings() {
$(".account").click(function (e) {
var ui = DATA.getUserInfo();
if($.isEmptyObject(ui)){
swal("Oops...", "You need to sign in!", "error");
}else{
$(".home").html('<label>Name:</label><input disabled="true" id="userFullName" value="' + ui.fullName +'" type="text"><button class="edit">Edit</button><button class="save">Save</button>');
$(".edit").click(function (e) {
//here is where you want to change the disable to true
});
$(".save").click(function (e) {
//here is where you will update the user information in the database
})
}
});
$(".signOut").click(function (e) {
DATA.signOut();
});
$(".su-submit").click(function (e) {
e.preventDefault();
var fullName = $("#fullName").val(),
email = $("#email").val(),
pw = $("#pw").val(),
cpw = $("#cPw").val();
if(fullName == ""){
swal("Oops...", "You need a name!", "error");
}else if(!validateEmail(email)){
swal("Oops...", "Your email is not valid!", "error");
}else if(pw == "" || pw.length < 8){
swal("Oops...", "Your password needs to be longer than 8!", "error");
}else if(cpw == "" || cpw.length < 8 || pw != cpw){
swal("Oops...", "Your passwords don't match!", "error");
}else{
var info = {
"fullName": fullName,
"email": email,
"password": pw
};
DATA.addUser(info, addedUser);
// swal("Congrats", "You are signed up!", "success");
}
});
$(".si-submit").click(function (e) {
e.preventDefault();
var username = $("#username").val(),
pw = $("#siPW").val();
if(username == "" || validateEmail(username) == false){
swal("Oops...", "You need a username!", "error");
}else if(pw == "" || pw.length < 8){
swal("Oops...", "Your password needs to be longer than 8!", "error");
}else{
DATA.checkUser(username, pw, userSignIn);
}
});
}
function addedUser(data) {
console.log("data " , data);
}
function userSignIn(data) {
console.log(data.fullName);
swal("Congrats", data .fullName + " You are signed in!", "success");
};
function validateEmail(email) {
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
$(document).ready(function () {
setBindings();
});
Data JS:
var userLoggedIn = {};
var _checkUser = function (username, password, callback) {
$.ajax({
url: _baseQueryURL + 'q={"email":"' + username + '","password":"' + password +'"}' + _queryApiKey,
type: "GET",
contentType: "application/json"
}).done(function (data) {
userLoggedIn = data[0];
callback(data[0]);
}).fail(function (error) {
console.log("error " + error);
});
};
var _addUser = function (userInfo, callback) {
console.log(userInfo.email + ' ' + userInfo.password);
$.ajax({
url: _baseQueryURL + 'q={"email":"' + userInfo.email + '","password":"' + userInfo.password +'"}&c=true' + _queryApiKey,
type: "GET",
contentType: "application/json"
}).done(function (data) {
if(data == 0){
$.ajax({
url: _baseURL + _apiKey,
data: JSON.stringify( userInfo ),
type: "POST",
contentType: "application/json"
}).done(function (data) {
userLoggedIn = data;
callback(data);
}).fail(function (error) {
swal("Oops...", "You have an error!", "error");
});
}else if(data == 1){
swal("Oops...", "You are already signed up. Please Sign in!", "error");
}
}).fail(function (error) {
console.log("error " + error);
});
};
var _signOut = function () {
userLoggedIn = {};
};
var _getUserInfo = function () {
return userLoggedIn;
};
return {
checkUser: _checkUser,
addUser: _addUser,
signOut: _signOut,
getUserInfo: _getUserInfo
}
})();
I'm using a jeasyui form, inside a xoops module, in which I'm trying to clear all the form fields once the data has successfully submitted.
I've already consulted this question, but it didn't solve the problem in my case.
My HTML:
<div class="easyui-panel" title="Capture Reqs" style "width:100%;
max-width:600px; padding:30px 60px;">
<form action = "captureReqs_Save.php" id ="ff" class = "easyui-form"
method ="post" data-options = "novalidate:true">
<div style="margin-bottom:20px"> Area <br>
<input id="idArea" class="easyui-combobox" style="width:260px" name="idArea"
data-options="
url:'areasJson.php?idZona=<?php echo $idZone; ?>',
label:'Area:',
valueField: 'id',
textField: 'desc',
required:true
">
</div>
<div style="margin-bottom:20px"> Material
<input id="IdMaterial" class="easyui-combobox" style="width:100%"
name="IdMaterial" data-options="
loader: myloader,
mode: 'remote',
valueField: 'code',
textField: 'desc',
required:true
">
<div style="margin-bottom:20px"> Qty
<input class="easyui-textbox" name="quantity" style="width:100%"
data-options="label:'Qty:',required:true, validType:'number'">
</div>
<div style="margin-bottom:20px">
</form>
<div style="text-align:center;padding:5px 0">
<a href="javascript:void(0)" class="easyui-linkbutton"
onClick = "submitForm()" style="width:80px"> Submit</a>
<a href="javascript:void(0)" class="easyui-linkbutton"
onClick = "resetForm()" style = "width:80px"> Clear </a>
</div>
</div>
Script:
<script>
var myloader = function (param, success, error) {
var q = param.q || '';
if (q.length <= 2) {
return false
}
$.ajax({
url: 'materialJson.php?idArea=' + $('#idArea').combobox('getValue'),
dataType: 'json',
data: {
q: q
},
success: function (data) {
var items = $.map(data, function (item, index) {
return {
code: item.code,
desc: item.desc
};
});
success(items);
},
error: function () {
error.apply(this, arguments);
}
});
}
function submitForm() {
$('#ff').form('submit', {
onSubmit: function () {
return $(this).form('enableValidation').form('validate');
}
});
}
function resetForm() {
$('#ff')[0].reset();
}
</script>
Try calling resetForm. I converted to use promise style ajax and added resetForm
var myloader = function (param, success, error) {
var q = param.q || '';
if (q.length <= 2) {
return false
}
$.ajax({
url: 'materialJson.php?idArea=' + $('#idArea').combobox('getValue'),
dataType: 'json',
data: {
q: q
}
}).then(function (data) {
var items = $.map(data, function (item, index) {
return {
code: item.code,
desc: item.desc
};
});
success(items);
}).fail(function () {
error.apply(this, arguments);
});
}
function submitForm() {
$('#ff').submit(function () {
if ($(this).form('enableValidation').form('validate')) {
$.post($(this).attr('action'), $(this).serialize(), function (response) {
clearForm();
});
}
return false;
});
}
function resetForm() {
$('#ff')[0].reset();
}
<form method="POST" class="userform" id="loginForm">
<div data-role="content">
<h2> Login:</h2>
<div data-role="fieldcontain">
<input name="email" placeholder="put your name" type="email" data-mini="true">
</div>
<div data-role="fieldcontain">
<input name="password" placeholder="enter your password" type="password" data-mini="true">
</div>
<input type="submit" data-theme="a" value="submit" id="submitButton">
<h5 align="center">
Forget password?
</h5>
</div>
</form>
this is my login.js
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
var $bro = $('#loginForm');
$('#submitButton').click(function(e) {
//console.log("submit button has been clicked");
e.preventDefault(); //cancel form submit
var jsObj = $bro.serializeObject()
, ajaxObj = {};
//console.log(jsObj);
ajaxObj = {
type: "POST",
url: "http://192.168.0.100:8080/AdvancedLibrarySystem/api/v1/login",
data: JSON.stringify(jsObj),
contentType:"application/json",
error: function(jqXHR, textStatus, errorThrown) {
console.log("Error " + jqXHR.getAllResponseHeaders() + " " + errorThrown);
},
success: function(data) {
console.log(data);
if(data[0].status == '200') {
alert("Welcome!!!")
$('#div_ajaxResponse').text( data[0] );
$.mobile.changePage('home.html');
}
else{
alert("Incorret Username or Password!!!")
}
},
complete: function(XMLHttpRequest) {
//console.log( XMLHttpRequest.getAllResponseHeaders() );
},
dataType: "json" //request JSON
};
$.ajax(ajaxObj);
});
I'm trying to use an authentification in phonegap via ajax but if i'm trying to run that code in chrome console it works fine but when i'm using it in my phonegap application it's not giving response in the server... Anyone can help me out please...
I am not sure what you mean by 'not giving response in the server', but one thing worth checking out is the cross-domain options in the config.xml of your phonegap project. There should be an "access" tag in there that specifies what domains can be accessed. Try setting it to "*" and try again.