Send Form fields to jquery - javascript

I'm trying to pass all my form fields, to a ajax function where i will insert the user into the database.
But for some reason, my alert (in my JS file) isn't showing anything.
Any ideas what i'm doing wrong?
My HTML:
<form id="signupForm">
<input id="signupFormEmail" type="text" name="email" placeholder=" E-mail"><br />
<input id="signupFormPassword" type="text" name="password" placeholder=" Password"><br />
<input id="signupFormUsername" type="text" name="userName" placeholder=" User Name"><br />
<input id="submitSignup" type="button" value="SIGN UP" onclick="signUp(this);">
</form>
My javascript file:
function signUp(elem)
{
var postData = $(this).serializeArray();
//$('#myResults').html(postData);
alert($.param($(elem).serializeArray()));
if($(elem).parent().children('#signupFormEmail').val() != ''){
// verifica se o email já existe
$.ajax(
{
url: "/newsletter/check-email/",
type: "POST",
data: {type:'check',email:$(elem).parent().children('#signupFormEmail').val()}
}).done(function(response)
{
if(response == -1) {
$.ajax(
{
url: "/newsignup/registare/",
type: "POST",
data: postData
}).done(function(userCreated) {
if(userCreated == 1) {
alert('user created');
/*
$(elem).parent().children('#signupForm').val('');
$('#signUpCompleted').show();
*/
}
else
{
/*$('#signUpError').show();*/
alert('user not created');
}
})
//testing
//$('#signUpCompleted').show();
}
else //testing
{
$('.emailError').show(); //testing
}
}
);
}
}

It looks like you are serializing the element itself. You have to serialize the form, please check this out.
function signUp(elem)
{
var postData = $('form').serialize();
//$('#myResults').html(postData);
alert(postData);
if($(elem).parent().children('#signupFormEmail').val() != ''){
// verifica se o email já existe
$.ajax(
{
url: "/newsletter/check-email/",
type: "POST",
data: {type:'check',email:$(elem).parent().children('#signupFormEmail').val()}
}).done(function(response)
{
if(response == -1) {
$.ajax(
{
url: "/newsignup/registare/",
type: "POST",
data: postData
}).done(function(userCreated) {
if(userCreated == 1) {
alert('user created');
/*
$(elem).parent().children('#signupForm').val('');
$('#signUpCompleted').show();
*/
}
else
{
/*$('#signUpError').show();*/
alert('user not created');
}
})
//testing
//$('#signUpCompleted').show();
}
else //testing
{
$('.emailError').show(); //testing
}
}
);
}
}

In your onclick attribute, this is not the FORM; this is the button you clicked.

Related

How to Edit/Save changes to a text box through Javascript

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 have tried using ajax to call into my php function but i dont know whats wrong with the code its not working

!-- Main Page Starts Here -->
<section class="container">
<div class="row">
<div class="centerlogin">
<div class="frmlogin">
<form role="form" name="signin" id="signin" method="post" action="#">
<div class="headtab"><h3>Login</h3></div>
<ul>
<li><i class="glyphicon glyphicon-user"></i> <input type="text" id="email" name="username" class="usern" placeholder="Enter Username"></li>
<li><i class="glyphicon glyphicon-lock"> </i><input type="password" id="pwd" name="password" class="passn" placeholder="Enter Password"></li>
<li><button class="subn" id="btnSubmit">Login</button></li>
</ul>
</form>
</div>
</div>
</div>
</section>
<!-- Main Page Ends Here -->
the above is my login form.
and below is my ajax call
//ajax calls start below
$(document).ready(function () {
$("#btnSubmit").click(function (e) {
e.preventDefault();
var email = $("#email").val();
var password = $("#pwd").val();
var pwd = $.md5(password);
auth(email, pwd);
});
});
//authenticate function to make ajax call
function auth(email, pwd) {
$.ajax
({
type: "POST",
url: "https://localhost/main/web/sign-in",
dataType: 'json',
type : "POST",
data: { email: email,pwd: pwd },
success: function (r) {
//console.log(r);
if(r.status == '0')
{
var sk=r.sk;
$.ajax({
type: "POST",
url: "http://localhost/main/secret/signin.php",
type : "POST",
data: { sk:sk},
success: function(r)
{
if(r == '0')
{
window.location.href = "http://localhost/main/index.php";
}
else
{
window.location.href = "http://localhost/main/login.php";
alert('Something Went Wrong.Please Try Again!');
}
}
});
}
else if(r.status == '401')
{
alert("Incorrect Email/Password");
$("#signin")[0].reset();
}
else
{
alert("User Doesn't exist");
$("#signin")[0].reset();
}
return false;
}
});
}
I dont know whats wrong with my code even the code its not working, it is not even showing the alerts on form blank inputs and form gets reload after clicking login button,Please help me stuck very badly.
Type property in Ajax call is defined twice.
Please use debugging tool, such as Firebug to debug xhr requests to understand if they are being sent or not. You can also view the responses of those requests which might hint errors.
Try below code as i have just removed http:// from url. hope this helps.
//ajax calls start below
$(document).ready(function () {
$("#btnSubmit").click(function (e) {
e.preventDefault();
var email = $("#email").val();
var password = $("#pwd").val();
var pwd = $.md5(password);
auth(email, pwd);
});
});
//authenticate function to make ajax call
function auth(email, pwd) {
$.ajax
({
type: "POST",
url: "web/sign-in",
dataType: 'json',
type : "POST",
data: { email: email,pwd: pwd },
success: function (r) {
//console.log(r);
if(r.status == '0')
{
var sk=r.sk;
$.ajax({
type: "POST",
url: "secret/signin.php",
type : "POST",
data: { sk:sk},
success: function(r)
{
if(r == '0')
{
window.location.href = "main/index.php";
}
else
{
window.location.href = "main/login.php";
alert('Something Went Wrong.Please Try Again!');
}
}
});
}
else if(r.status == '401')
{
alert("Incorrect Email/Password");
$("#signin")[0].reset();
}
else
{
alert("User Doesn't exist");
$("#signin")[0].reset();
}
return false;
}
});
}
Code is working after i change the sequence of my javascript files into my html file of my form.
I place my javascript code file after
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
and It was working perfectly.

Image is not inserted with data using ajax jquery in asp.net MVC

I'm trying to insert data to database using ajax with Jquery. My data is inserted without ajax perfectly but when i use ajax, there is something wrong with image. it get the file null in the controller in post method.
This is my Form in the View.
<form id="InsertForm" name="InsertForm" enctype="multipart/form-data">
<div class="form-group">
<label for="Name">Name</label>
<input type="text" class="form-control" name="StudentName" id="name" />
</div>
<div class="form-group">
<label for="LastName">Last Name</label>
<input type="text" class="form-control" name="StudentLastName" id="last" />
</div>
<div class="form-group">
<label for="Address">Address</label>
<input type="text" class="form-control" name="StudentAddress" id="address" />
</div>
<div class="form-group">
<label for="Gender">Gender</label>
<input type="text" class="form-control" name="Gender" id="gender" />
</div>
<div class="form-group">
<label for="Image">Image</label>
<input type="file" class="form-control" id="StudentImage" name="StudentImage" />
</div>
<button id="saveclick" type="submit" name="save">Save</button>
</form>
This is my Script in the View for inserting data with image.
<script>
$(document).ready(function () {
$("#saveclick").click(function (e) {
var student = {
StudentName: $("#name").val(),
StudentLastName: $("#last").val(),
StudentAddress: $("#address").val(),
Gender: $("#gender").val(),
StudentImage: $("#StudentImage").val().split('\\').pop()
};
//var formdata = new FormData($('InsertForm').get(0));
//var Student= $("#InsertForm").serialize();
var jsonData = JSON.stringify(student);
alert(jsonData);
$.ajax({
type: "POST",
url: '#Url.Action("Insert", "Student", null)',// Insert Action Method in Student Controller.
contentType: "application/json; charset=utf-8",
dataType: "json",
enctype: 'multipart/form-data',
data: jsonData,
success: function (data) {
if (data.success) {
alert(data.message);
}
},
error: function (xhr) {
alert('error');
}
});
return false;
});
});
</script>
This is my Controller action Method in Student Controller.
[HttpPost]
public JsonResult Insert(Student student)
{
if (ModelState.IsValid)
{
Student stu = new Student();
stu.StudentName = student.StudentName;
stu.StudentLastName = student.StudentLastName;
stu.StudentAddress = student.StudentAddress;
stu.Gender = student.Gender;
HttpPostedFileBase file = Request.Files["StudentImage"];
file.SaveAs(HttpContext.Server.MapPath("~/Images/") + file.FileName);
stu.StudentImage = file.FileName;
db.Students.Add(stu);
db.SaveChanges();
return Json(student);
}
else
{
ModelState.AddModelError("", "Inavlid Data Inserted");
}
return Json(student);
}
Thanks if you solve my this problem.
try following
<script type="text/javascript">
$(document).ready(function () {
$("#saveclick").click(function (e) {
var data = new FormData();
var files = fileUpload.files;
fileData.append("StudentImage", files[0]);
fileData.append("StudentName",$("#name").val());
/* add all values as above one by one for LastName,Gender,Address*/
$.ajax({
type: "POST",
url: '#Url.Action("Insert", "Student", null)',// Insert Action Method in Student Controller.
contentType: "application/json; charset=utf-8",
processdata: false,
data: data,
type:"POST"
success: function (data) {
if (data.success) {
alert(data.message);
}
},
error: function (xhr) {
alert('error');
}
});
return false;
});
});
</script>
Here is the solution that solve my great problem. We need to append the ForamData in any variable.
<script>
$(document).ready(function () {
$("#saveclick").click(function (e) {
// Create FormData object
var fileData = new FormData();
var fileUpload = $("#StudentImage").get(0);
var files = fileUpload.files;
// Looping over all files and add it to FormData object
//for (var i = 0; i < files.length; i++) {
// fileData.append(files[i].name, files[i]);
//}
fileData.append("StudentImage", files[0]);
fileData.append("StudentName", $("#name").val());
fileData.append("StudentLastName", $("#last").val());
fileData.append("StudentAddress", $("#address").val());
fileData.append("Gender", $("#gender").val());
$.ajax({
type: "POST",
url: '#Url.Action("Insert", "Student", null)',
data: fileData,
processData: false,
contentType: false,
success: function (data) {
if (data.success) {
alert(data.message);
}
},
error: function (xhr) {
alert('error');
}
});
return false;
});
});
</script>

How to validate data in an AJAX call

I am trying to call data from a PHP file where it takes the data entered and tells if it is validated or not. How do you do this in the javascript file using an AJAX call?
$("#PersonForm").submit(function()
{
$.ajax({
url: 'backend.php', type: 'post', data: { act:'validate'},
dataType: 'json',
function(result) {
if($validateData==1){
$('#success').html('validated');
}
else{
$('#errors').html('Not Correct');
}
}
//});
});
return false;
});
Here is the PHP file
<?php
if ($_REQUEST['act'] == 'validate')
{
$validateData = array();
if (preg_match("/^[A-Za-z]{3,20}$/",$_REQUEST['name'])) $validateData['name'] = 1;
else $validateData['name'] = 0;
if (preg_match("/^[0-9]{10}$/",$_REQUEST['phone'])) $validateData['phone'] = 1;
else $validateData['phone'] = 0;
if (preg_match("/^[A-Z][0-9][A-Z][0-9][A-Z][0-9]$/",
$_REQUEST['postal'])) $validateData['postal'] = 1;
else $validateData['postal'] = 0;
if (preg_match("/^[0-9]{3} [A-Za-z]{3,10} Street$/",
$_REQUEST['address'])) $validateData['address'] = 1;
else $validateData['address'] = 0;
echo json_encode($validateData);
}
else echo "Should not happen";
?>
HTML file:
<html>
<body>
<h1>Form Validation</h1>
<form id="PersonForm">
Name: <input type="text" id="name" name="name"> <br>
Postal Code: <input type="text" id="postal" name="postal"> <br>
Phone Number: <input type="text" id="phone" name="phone"> <br>
Address: <input type="text" id="address" name="address"> <br>
<input id="sub" type="submit">
</form>
Refresh
<a id="InsertDefault" href="">Insert Default Data</a>
<br>
<ul id="errors"></ul>
<p id="success"></p>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript" src="main.js"></script>
</html>
First, you're not sending the any of the inputs in your data: parameter. So $_REQUEST['name'], $_REQUEST['phone'], etc. won't exist.
Second, you can't access PHP variables in Javascript. The JSON that the PHP echoes at the end will be decoded into the result variable in the success: callback function.
Third, your syntax is wrong, the callback function needs to be in the success: option.
So it should be:
$("#PersonForm").submit(function()
{
$.ajax({
url: 'backend.php',
type: 'post',
data: 'act=validate&' + $(this).serialize(),
dataType: 'json',
success: function(result) {
if(result.name && result.phone && result.post && result.address){
$('#success').html('validated');
}
else{
$('#errors').html('Not Correct');
}
}
});
return false;
});
You should use the success and error callbacks so that you are waiting for the promise from the ajax call to come back. I am assuming you are trying to figure out how to get to the data that comes back. If you need further assistance with then validating the real data, I can help with that as well.
$.ajax({
url: 'backend.php', type: 'post', data: { act:'validate'},
dataType: 'json',
success: function (data) {
if($validateData==1){
$('#success').html('validated');
}
else{
$('#errors').html('Not Correct');
}
},
error: function (request, status, error) {
// Error occurred calling API
}
});

get ajax response in jquery modal form dialog

I can't get the ajax response when submitting a modal dialog form. It works perfectly when the form is not modal.
The form:
<div id="form2" style="display: none">
<form id="objectInsert" action="element/create" method="POST" enctype="multipart/form-data">
<div class="form-group">
<label for="name">Name</label>
<input class="form-control" type="text" name="name" id="name"/>
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea class="form-control" name="description"></textarea>
</div>
</form>
Here i get the ajax success part in the console!
$("#objectInsert").submit(function(e) {
e.preventDefault();
resetErrors();
var form = this;
var url = $(this).attr('action');
var data = new FormData($(this)[0]);
$.ajax({
type: 'POST',
url: url,
data: data,
dataType: 'json',
cahe:false,
processData: false,
contentType: false,
success: function(resp) {
console.log(resp);//Working
},
error: function() {
console.log('there was a problem checking the fields');
}
});
});
Here i get the ajax error part in the console! can someone tell me where i'm doing wrong?
$("#add_element").click(function(){
$("#form2").dialog({
modal:true,
width:400,
buttons:{
Send:function(e){
e.preventDefault();
var form = $("#objectInsert");
var url = form.attr('action');
var data = new FormData(form[0]);
$.ajax({
type: 'POST',
url: url,
data: data,
dataType: 'json',
cahe:false,
processData: false,
contentType: false,
success: function(resp) {
console.log(resp);//not working
},
error: function(xhr, status, error) {
console.log('there was a problem checking the fields');
console.log(xhr);
console.log(error);
}
});
return false;
},
Cancel:function(){
$(this).dialog("close");
}
}
});
});
The controller
public function create() {
try{
$this->form = new Form();
$this->form->post('name');
$this->form->val('isEmpty', 'name');
$this->form->post('description');
$this->form->val('isEmpty', 'description');
$this->form->fetch();
$this->form->submit();
$data = $this->form->get_postData();
$this->model->insert($data);
echo json_encode('success');
} catch (Exception $ex) {
$errors = $this->form->get_error();
$_SESSION["errors"] = $errors;
//This is for ajax requests:
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH'])
== 'xmlhttprequest') {
echo json_encode($_SESSION['errors']);
exit;
}
foreach ($_SESSION["errors"] as $errors){
echo $errors;
echo '<br/>';
}exit;
}
}
see this code you have not closed the function block
success: function(resp) {
console.log(resp);//not working
},//This is not closed for success function
error: function() {
console.log('there was a problem checking the fields');
}

Categories