i have created a form which is submitting data through ajax to the database.this works fine.how can i prevent entering sitename is already available in database.if that sitename already in database it should give error message.
Controller
public function user_add()
{
$data_save = array(
"Mnumber" => $this->input->post("Mnumber"),
"email" => $this->input->post("email"),
"fname" => $this->input->post("fname"),
"address" =>$this->input->post("address"),
"sitename" =>$this->input->post("sitename"),
/* "reqnum" => $this->input->post("reqnum"),*/
"title" => $this->input->post("title"),
"descr" => $this->input->post("descr"),
/*"payment" => $this->input->post("payment"),*/
"uniquekey" => $this->input->post("uniquekey")
/*"subscription" => $this->input->post("subscription"),
"email_sent" => $this->input->post("email_sent"),*/
);
if ($this->user_mod->AddUser($data_save)) {
echo "Successfully Saved";
}
else {
echo "error";
}
}
view
<script>
function save_user_new() {
var Mnumber = $('#Mnumber').val();
var email = $('#email').val();
var fname = $('#fname').val();
var address = $('#address').val();
var sitename = $('#sitename').val();
/*var reqnum = $('#reqnum').val();*/
var title = $('#title').val();
var descr = $('#descr').val();
var uniquekey = $('#uniquekey').val();
/*var subscription = $('#subscription').val();
var email_sent = $('#email_sent').val();
var payment = $('#payment').val();*/
if (sitename != "" && email != "") {
$.ajax({
type: "post",
async: false,
url: "<?php echo site_url('form_con/user_add'); ?>",
data: {
"Mnumber": Mnumber,
"email": email,
"fname": fname,
"address": address,
"sitename": sitename,
/*"reqnum": reqnum,*/
"title": title,
"descr": descr,
"uniquekey": uniquekey
/*"subscription": subscription,
"email_sent": email_sent,
"payment":payment*/
},
dataType: "html",
success: function (data) {
alert(data);
if (data == 'error') {
$('#success_msg').hide();
$('#error_msg1').show();
$('#error_msg1').html("Error : Something wrong.");
} else if (data == 'have') {
$('#success_msg').hide();
$('#error_msg1').show();
$('#error_msg1').html("Error : This Sitename is already exists.");
} else {
$('#error_msg1').hide();
$('#success_msg').show();
$('#success_msg').html("User details successfully saved.");
/*setTimeout(function() { location="features.php"},2000);*/
location.href = 'freecreate';
}
}
});
} else {
$('#success_msg').hide();
$('#error_msg1').show();
$('#error_msg1').html("Error : Please enter User Details.");
}
}
</script>
<form action="#" id="form_sample_1">
<div class="form-body">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Your First Name</label>
<input type="text" class="form-control" id="fname" name="fname" placeholder="Enter text" required="">
</div>
<div class="form-group">
<label class="control-label">Email Address</label>
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-envelope"></i></span>
<input type="email" class="form-control" id="email" name="email" placeholder="Email Address" required="">
</div>
</div>
<div class="form-group">
<label class="control-label">Your Mobile Number</label>
<input type="text" class="form-control" id="Mnumber" name="Mnumber" placeholder="Enter text" required="">
<!--<span class="help-block"> A block of help text. </span>-->
</div>
<div class="form-group">
<label class="control-label">Your Address</label>
<input type="text" class="form-control" id="address" name="address" placeholder="Enter text" required="">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Your Site Name</label>
<input type="text" class="form-control" id="sitename" name="sitename" placeholder="Enter text" required="">
<span class="help-block"> please enter the sitename only.if you wish to cretae site as john just type john.it will create the site automatically as john.site.mobi </span><br>
</div>
<div class="form-group">
<label class="control-label">Title of Your Web site</label>
<input type="text" class="form-control" id="title" name="title" placeholder="Enter text" required="">
</div>
<div class="form-group">
<label class="control-label">Description of Your Web Site</label>
<input type="text" class="form-control" id="descr" name="descr" placeholder="Enter text" required="">
<!--<input type="hidden" class="form-control" id="req_num" name="req_num" value="1" placeholder="Enter text">-->
<?php $uniquekey = md5(uniqid(rand(), true)); ?>
<input type="hidden" class="form-control" id="uniquekey" name="uniquekey" value="<?php echo $uniquekey ?>" placeholder="Enter text">
<!--<input type="hidden" class="form-control" id="subscription" name="subscription" value="1" placeholder="Enter text">
<input type="hidden" class="form-control" id="email_sent" name="email_sent" value="1" placeholder="Enter text">-->
<!--<input type="hidden" class="form-control" id="payment" name="payment" value="1" placeholder="Enter text">-->
</div>
</div>
<div class="form-actions right">
<!--<a class="btn green" onclick="save_user_new()">Submit</a>-->
<button type="submit" id="save_btn" class="btn green" onclick="save_user_new()">Submit</button>
<button type="button" class="btn default">Cancel</button>
</div>
</div>
</form>
Model
public function AddUser($data_save)
{
if ($this->db->insert('users', $data_save)) {
return true;
} else {
return false;
}
}
Write a validate function which actually checks for empty value in textbox and returns true or false. Consider below example.
function ValidateForm(form){
var valid=true;
$(form).find('input[type="text"]').each(function(){
if($(this).val()=="")
valid=false;
});
return valid;
}
function save_user_new() {
//getting all the values
//change if condition to
var form=$("#form_sample_1");
if(ValidateForm(form))
{
//continue with ajax
}
else
{
alert('Please fill all the fields');
return false;
}
}
Add jQuery required in save_user_new function
$("input").prop('required',true);
There is a couple of ways to do this.
As previously mentioned, write a validate method and check if the record already exists in the database.
Set the field to 'unique', and catch the error when you run the query,
also if you want to save yourself some time and coding write a helper function which will load all your post variables for your.
eg.
function LoadPostVariables($variables = [])
{
$CI = & get_instance();
$return_array = [];
foreach($variables as $key){
$p_val = $CI->input->post($key);
//you could perform some basic validation here
$return_array[$key]=$p_val;
}
}
$values = LoadPostVariables(['MNumber', 'email', 'fname', 'address', 'sitename', 'title', 'descr', 'uniquekey']);
public function AddUser($data_save)
{
$check = false;
$query = "SELECT * FROM users WHERE email='$data_save' LIMIT 1";
$result = mysqli_query($dbc, $query);
if($result){
while($row = mysqli_fetch_assoc($result)){
$check = true;
}
}
if($check == false){
// add data
}else{
echo 'Email already found'; exit();
}
}
Related
I'm just starting with JS and like to implement a form that verifies for robots/humans by using captcha v3 on the client side and if verification succeeds the data should be submitted to another file.
This is what I got so far. I know it's wrong, but unsure what the correct logic is. Hope someone can shed a light. Thx!
<script src="https://www.google.com/recaptcha/api.js?render=6Lc3UZkeAAAAAMt6wcA-bYjLenFZPGv3K5AqfvuQ"></script>
<script type="text/javascript" src="/js/libs/jquery-1.11.3.min.js"></script>
<section class="cc-column-component regular-grid">
<form id="bank-form" class="form clear one-full cf-contact-form" action="?" method="POST" data-tracking="contact_sales">
<div>
<label class="label mandatory bank-color bank-label" for="firstName">First Name</label>
<input id="firstName" value="Pepe" type="text" class="one-full bank-color-grey bank-input" name="firstName" placeholder="First Name" autocomplete="off" data-validate="true" data-type="text" data-min="3" value="<?php isset($this) ? print $this->getFirstName() : print ''; ?>">
<br/>
<label class="label mandatory bank-color bank-label" for="lastName">Last Name</label>
<input id="lastName" value="Chanches" type="text" class="one-full bank-color-grey bank-input" name="lastName" placeholder="Last Name" autocomplete="off" data-validate="true" data-type="text" data-min="3" value="<?php isset($this) ? print $this->getLastName() : print ''; ?>">
<br/>
<label class="label mandatory bank-color bank-label" for="email">Email</label>
<input value="asdf#asdf.com" id="email" type="text" class="one-full bank-color-grey bank-input" name="email" placeholder="Email" autocomplete="off" data-validate="true" data-type="email" value="<?php isset($this) ? print $this->getEmail() : print ''; ?>">
<br/>
</div>
<div class="row inline one-full">
<br/>
<!-- <div class="g-recatpcha" data-sitekey="6Lc3UZkeAAAAAMt6wcA-bYjLenFZPGv3K5AqfvuQ"></div> -->
<button type="submit"
id="form-submit"
value="submit"
>
<a>Submit form</a>
</button>
<div class="field inline one-full">
<br/>
</div>
<!-- <input type="hidden" name="recaptcha_response" id="recaptchaResponse"> -->
</div>
</form>
</section>
<script>
$('#bank-form').submit(function(event) {
console.log('subtmitting');
event.preventDefault();
grecaptcha.ready(function() {
grecaptcha.execute('6Lc3UZkeAAAAAMt6wcA-bYjLenFZPGv3K5AqfvuQ', {action: 'submit'}).then(function(token) {
console.log('🚀 ~ grecaptcha.execute ~ token', token)
$('#bank-form').prepend('<input type="hidden" name="token" value="' + token + '">');
$('#bank-form').prepend('<input type="hidden" name="action" value="submit">');
// $('#bank-form').unbind('submit').submit();
});;
});
CheckCaptcha(token)
});
function CheckCaptcha(token) {
var token = $("#token").val()
console.log('🚀 ~ token', token)
var action = $("#action").val()
var RECAPTCHA_V3_SECRET_KEY = "6Lc3UZkeAAAAAIG8bVZDpkheOxM56AiMnIKYRd6z"
$.ajax({
type: "POST",
url: "http://www.google.com/recaptcha/api/siteverify",
data: JSON.stringify([{secret: RECAPTCHA_V3_SECRET_KEY }, {response : token }]),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
// __doPostBack('form-submit', '');
if(response["score"] >= 0.7) {
console.log('Passed the token successfully');
}
},
failure: function (response) {
// set error message and redirect back to form?
console.log('Robot submit', response);
}
})
return false;
}
</script>
This is my first bigger form with validations and etc.
I've created a Registration form and I'm using ng-messages for validation. The problem is that I need to validate the username, does it already exist in the JSON server that we are using or it's available. Of course, if it's taken the warning pops out in the HTML where the username input is, if it's available the submit button is no more disabled (because the form will be $valid) and the user can register. I want to use angular-sanitize because I found this (I don't know if they are related):
ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
var value = modelValue || viewValue;
// Lookup user by username
return $http.get('/api/users/' + value).
then(function resolved() {
//username exists, this means validation fails
return $q.reject('exists');
}, function rejected() {
//username does not exist, therefore this validation passes
return true;
});
};
Here is the code I use now (reg form, controller and service):
// Controller:
export default class registerPageController {
constructor(userService, authenticationService, $location) {
this.register = "Register";
this.userService = userService;
this.$location = $location;
this.authenticationService = authenticationService;
this.hasLoggedIn = false;
}
onSubmit(user) {
let self = this;
let {
name,
age,
email,
username,
password
} = user;
self.userService.register(name, age, email, username, password).then((res) => {
self.userService.login(username, password).then(function (response) {
let data = response.data;
if (data.length) {
let user = data[0];
self.hasLoggedIn = true;
self.authenticationService.setCredentials(username, password);
self.$location.path('/');
}
});
})
.catch(err => {
// WHAT TO PUT HERE AFTER THE USERNAME EXIST VALIDATION ?
})
}
}
// Service:
export class UserService {
constructor($http) {
this.$http = $http;
}
login(username, password) {
return this.$http({
method: 'GET',
url: 'http://localhost:3000/users',
params: {
username: username,
password: password
}
});
}
register(name, age, email, username, password) {
return this.$http({
method: 'POST',
url: 'http://localhost:3000/users',
data: {
name: name,
age: age,
email: email,
username: username,
password: password
}
});
}
// SHOULD I PUT HERE THE USERNAME EXIST VALIDATION LOGIC ?
}
<div class="container main-content">
<form class="registrationForm" name="registerForm" ng-submit="register.onSubmit(register.user)" novalidate="novalidate">
<!-- Enter Name -->
<div class="form-group">
<label for="name" class="control-label"><span id="reqInfo">*</span> Name</label>
<input type="text" name="name" class="form-control" ng-model="register.user.name" ng-pattern="/[a-zA-Zа-яА-Я]+/" id="name"
required="" placeholder="Example: Petar Petrov">
<div ng-messages="registerForm.name.$error" ng-show="registerForm.name.$touched" style="color:maroon" role="alert">
<div ng-message="required">Your name is required</div>
</div>
</div>
<!-- User Age-->
<div class="form-group">
<label for="age" class="control-label"><span id="reqInfo">*</span> Age</label>
<input type="number" name="age" class="form-control" ng-model="register.user.age" ng-min="18" min="18" id="age" required=""
placeholder="Enter your age">
<div ng-messages="registerForm.age.$error" ng-show="registerForm.age.$touched" style="color:maroon" role="alert">
<div ng-message="min">You must be at leats 18 years old</div>
</div>
</div>
<!-- Enter E-mail -->
<div class="form-group">
<label for="email" class="control-label"><span id="reqInfo">*</span> E-mail</label>
<input type="email" name="email" class="form-control" ng-model="register.user.email" ng-pattern="/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+#)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+#)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-_]*)?\??(?:[\-\+=&;%#\.\w_]*)#?(?:[\.\!\/\\\w]*))?)/"
id="email" required="" placeholder="Example: mail#mail.net">
<div ng-messages="registerForm.email.$error" ng-show="registerForm.email.$touched" style="color:maroon" role="alert">
<div ng-message="required">Your valid e-mail is required</div>
</div>
<br>
<!-- Enter Username -->
<div class="form-group">
<label for="username" class="control-label"><span id="reqInfo">*</span> Username</label>
<input type="text" name="username" ng-minlength="5" ng-maxlength="20" class="form-control" ng-model="register.user.username"
ng-pattern="/^[A-Za-z0-9_]{1,32}$/" ng-minlength="7" id="username" required="" placeholder="Enter your username">
<div ng-messages="registerForm.username.$error" style="color:maroon" role="alert">
<div ng-message="minlength">Your Username must be between 7 and 20 characters long</div>
</div>
<br>
<!-- Enter Password -->
<div class="form-group">
<label for="password" class="control-label"><span id="reqInfo">*</span> Password</label>
<input type="password" name="password" class="form-control" ng-model="register.user.password" ng-minlength="7" id="password"
required="" placeholder="Enter your password">
<div ng-messages="registerForm.password.$error" style="color:maroon" role="alert">
<div ng-message="minlength">You Password must be at least 7 symbols long</div>
</div>
</div>
<!-- Register button -->
<div class="form-group">
<button class="btn btn-primary" type="submit" ng-disabled="!registerForm.name.$valid || !registerForm.age.$valid || !registerForm.email.$valid || !registerForm.username.$valid || !registerForm.password.$valid">Register</button>
</div>
<p>Fields with <span id="reqInfo">*</span> must be filled.</p>
</form>
</div>
Important is to know that I have being told explicitly to write it in ES6.
I have problem with the logic so look at my code and please fill it for me so I can use it and most important - learn it :S
Thank you so so much in advance!
I have implemented a directive for different kind of validations (sync Async), and it supports warning as well.
You may check it from
`https://plnkr.co/2WQHOo`
If this is what you needed and need more information, let me know I will try my best to answer.
So upon examining the development console, i can see that my AJAX has succeeded, and I have recieved the JSON data I need, However I can't put my finger on how to display it correctly as I keep getting the following error:
Uncaught TypeError: Cannot read property 'name' of undefined
at Object.success (main.js:11)
at Object.resolveWith (jquery.min.js:16)
at v (jquery.min.js:16)
at XMLHttpRequest.c (jquery.min.js:16)
AJAX output:
Object {rows: Object, response: true}
response:true
rows:Object
address:"testestset"
classid:"2"
dob:"1993-04-27"
email:"tests"
gender:"M"
id:"5"
name:"Second Birthday Test"
parent:"Testerr"
phone:"07123456789"
status:"1"
Main.js:
function getGymnasts(val){
$.ajax({
type:"POST",
url:"ajax_populate_gymnasts.php",
data: 'gymnast='+val,
success: function(response){
var result = JSON.parse(response);
if (result.response == true) {
//console.log(result);
var data = result.rows;
console.log(data);
$("#dob").val(data['rows'].dob);
$("#gender").val(data['rows'].gender);
$("#parent").val(data['rows'].parent);
$("#email").val(data['rows'].email);
$("#phone").val(data['rows'].phone);
$("#address").val(data['rows'].address);
$("#status").val(data['rows'].status);
}else if (result.response == false) {
$('#gymnast').append('<option>No Gymnasts were found!</option>');
}
}
});
}
function populateReports(val){
$.ajax({
type:"POST",
url:"ajax_populate.php",
data: 'classid='+val,
success: function(data){
$("#gymnast").html(data);
}
});
}
ajax_populate_gymnasts.php
<?php
require('../includes/dbconnect.php');
$gymnastid = $_POST['gymnast'];
$sql = "SELECT * FROM gymnasts WHERE id='$gymnastid'";
$result = mysqli_query($GLOBALS['link'], $sql);
if (mysqli_num_rows($result) > 0) {
$data = mysqli_fetch_assoc($result);
echo json_encode(['rows' => $data, 'response' => true]);
} else {
echo json_encode(['response' => false]);
}
mysqli_close($GLOBALS['link']);
exit();
?>
editGymnasts.php:
<?php require('adminheader.php');
?>
<h1>Edit Gymnast</h1>
<form method="post">
<label for="gymnast">Gymnast:</label>
<select id="gymnast" name="gymnast" onChange="getGymnasts(this.value)" required/>
<option value="0">None yet</option>
<?php
$gymnasts = mysqli_query($GLOBALS['link'], "SELECT * FROM gymnasts;");
foreach($gymnasts as $gymnast){
echo("<option value=".$gymnast['id'].">".$gymnast['name']."</option>");
}
?>
</select><br>
<label for="dob">Date of Birth:</label>
<input type="date" id="dob" name="dob" required/>
<label for="gender">Gender:</label>
<select id="gender" name="gender" required />
<option value="F">Female</option>
<option value="M">Male</option>
</select><br>
<label for="parent">Parent's Name:</label>
<input type="text" id="parent" value="derp" name="parent" required /> <br>
<label for="email">Contact Email:</label>
<input type="text" id="email" name="email" required /> <br>
<label for="phone">Contact Phone:</label>
<input type="text" id="phone" name="phone" required /> <br>
<label for="parent">Contact Addres:</label>
<textarea id="address" name="address" required /></textarea><br>
<select id="status" name="status" required />
<option value="0"></option>
<input type="submit" id="saveChanges" name="saveChanges" />
</form>
So it turns out i was unnecessarily entering an undefined nested array.
$("#dob").val(data['rows'].dob);
Should have been
$("#dob").val(data.dob);
I'm getting this error when I try to update a file on my form..."You did not select a file to upload." ...and the problem is that I really am selecting a new file to upload...help me pls, I don't understand what is happening ...here is my code:
FORM
<form class="col s12" id="update_form" required="" enctype="multipart/form-data" aria-required="true" name="update_form" method="post" >
<div class="row">
<div class="input-field col s6">
<input id="update_name" type="text" required="" aria-required="true" name="name" class="validate">
<label for="first_name">Nombre</label>
</div>
<div class="input-field col s6">
<input id="update_last_name" name="lastname" required="" aria-required="true" type="text" class="validate">
<label for="last_name">Apellido</label>
</div>
</div>
<div class="row">
<div class="input-field col s6">
<input id="update_side" type="text" required="" aria-required="true" name="side" class="validate">
<label for="partido">Partido</label>
</div>
<div class="input-field col s6">
<input id="update_charge" type="text" required="" aria-required="true" name="charge" class="validate">
<label for="cargo">Cargo</label>
</div>
</div>
<div class="row">
<div class="input-field col s6">
<div class="file-field input-field no-margin-top">
<div class="btn light-blue darken-4">
<span>Animación/Imagen</span>
<input type="file" name="animation">
</div>
<div class="file-path-wrapper">
<input class="file-path validate" id="animation" name="animation" type="text">
</div>
</div>
</div>
<div class="input-field col s6">
<select id="update_section" required="" aria-required="true" name="section" autocomplete="off">
<option value="" disabled selected>Seleccione una opción</option>
<option value="1">Presidencia</option>
<option value="2">Senadores</option>
<option value="3">Diputados</option>
</select>
<label>Sección</label>
</div>
</div>
<input type="hidden" name="update_politic_hide" id="update_politic_hdn" value="">
</form>
CONTROLLER
public function update_politic(){
$this->load->model("politic");
$params;
if ($this->input->is_ajax_request()) {
if (empty($this->input->post("animation"))){
echo "first";
$data = $this->politic->get_file_name($this->input->post("update_politic_hide"));
$file = $data->POLITIC_FILE;//recupero el nombre de la imagen
$params["name"] = $this->input->post("name");
$params["lastname"] = $this->input->post("lastname");
$params["side"] = $this->input->post("side");
$params["charge"] = $this->input->post("charge");
$params["section"] = $this->input->post("section");
$params["animation"] = $file;
$params["id"] = $this->input->post("update_politic_hide");
if ($params["section"]=="Presidencia") {
$params["section"]=1;
}
if ($params["section"]=="Senadores") {
$params["section"]=2;
}
if ($params["section"]=="Diputados") {
$params["section"]=3;
}
}
else {
echo "second";
$config['upload_path'] = "./public/uploads/";
$config['allowed_types'] = "*";
//$config['overwrite'] = "true";
$config['max_size'] = "500000";
$config['max_width'] = "2000";
$config['max_height'] = "2000";
$this->load->library('upload', $config);
//$file = "animation";
if (!$this->upload->do_upload("animation")) {
$data['uploadError'] = $this->upload->display_errors();
echo $this->upload->display_errors();
}
else {
$file_info = $this->upload->data();
$params["name"] = $this->input->post("name");
$params["lastname"] = $this->input->post("lastname");
$params["side"] = $this->input->post("side");
$params["charge"] = $this->input->post("charge");
$params["animation"] = $file_info['file_name'];
$params["section"] = $this->input->post("section");
$params["id"] = $this->input->post("update_politic_hide");
if ($params["section"]=="Presidencia") {
$params["section"]=1;
}
if ($params["section"]=="Senadores") {
$params["section"]=2;
}
if ($params["section"]=="Diputados") {
$params["section"]=3;
}
}
}
$this->politic->update($params);
}
}
MODEL
public function update($param){
$id = $param["id"];
$values = array(
"POLITIC_NAME" => $param["name"],
"POLITIC_LASTNAME" => $param["lastname"],
"POLITIC_SIDE" => $param["side"],
"POLITIC_CHARGE" => $param["charge"],
"POLITIC_FILE" => $param["animation"],
"SECTION_ID" => $param["section"],
);
$this->db->where("POLITIC_ID",$id);
$this->db->update("politics",$values);
}
JAVASCRIPT
$("#update_politic_btn").click(function(event) {
/* Act on the event */
var chango = $("#update_form").serialize();
$.post(baseurl + 'admin/update_politic', chango,
function(data) {
console.log(data);
list_politic();
});
event.preventDefault();
});
function update_politic(id, name, lastname, section, side, charge, file) {
$("#update_politic_hdn").val(id);
$("#update_name").val(name);
$("#update_last_name").val(lastname);
$("#update_side").val(side);
$("#update_charge").val(charge);
$('[name=section]').val(section);
$("#animation").val(file);
$('select').material_select();
}
There are two name attributes having the same value animation.
<input type="file" name="animation">
and
<input class="file-path validate" id="animation" name="animation" type="text">
The second name attribute is overriding the first one. You need to give it a different name.
Change your Ajax code :
$("#update_politic_btn").click(function(event) {
var chango = new FormData($("#update_form")[0]);
// try this if above one not work
//var chango = new FormData($("#update_form"));
$.ajax({
url: baseurl + 'admin/update_politic',
type: 'POST',
data: chango,
async: false,
success: function (data) {
console.log(data);
list_politic();
},
cache: false,
contentType: false,
processData: false,
error : function() {
}
});
event.preventDefault();
});
I am trying to send an e-mail after an ajax call has been successfully completed. I do not have access to the file that I am making the AJAX call to.
I am preventing the first submit, making the ajax call and submitting the form again upon competition. When doing this, I can't seem to figure out why I have to press the submit button twice for the email to be sent.
Here is my code:
"use strict";
var submitted = '';
/* Send info to the portal */
jQuery(function($) {
$('#quote').submit(function(e){
var firstName = $('#firstName').val(),
lastName = $('#lastName').val(),
email = $('#email').val(),
phone = $('#primaryPhone').val(),
weight = $('#weight').val(),
origin = $('#originPostalCode').val(),
destination = $('#destinationPostalCode').val(),
notes = $('#whatsTransported').val()
if( submitted != 1 )
{
e.preventDefault();
$.ajax({
type: "POST",
url: "https://somewhere.on/the/internet.php",
crossDomain: true,
dataType: "json",
data: {"key": "my secret key","first": firstName, "last": lastName, "email": email, "phone": phone, "weight": weight, "origin_postal": origin, "dest_country": destination, "note": notes }
})
.done(function(data){
if(data[1][0][0] == 2)
{
$('.alert').append( data[1][0][1].message ).addClass('alert-error').show();
} else if(data[1][0][0] == 0) {
console.log("Made it.");
$('#quote #submit').submit();
} else {
$('.alert').append( "Appologies, it seems like something went wrong. Please, <strong>call (877) 419-5523</strong> for immediate assistance or a free quote.");
}
})
.fail(function(data) { console.log(data); });
}
submitted = '1';
});
});
Here is the form HTML
<form action="<?php echo bloginfo($show='template_url').'/includes/form-email.php'; ?>" class="span6 offset1" id="quote" method="post">
<div class="row formRow">
<div class="firstName span3">
<label for="firstName"><?php _e('First Name:','StreamlinedService'); ?></label>
<input type="text" name="firstName" id="firstName">
</div>
<div class="lastName span3">
<label for="lastName"><?php _e('Last Name:','StreamlinedService'); ?></label>
<input type="text" name="lastName" id="lastName">
</div>
</div>
<div class="row formRow">
<div class="email span3">
<label for="email"><?php _e('Email Address:','StreamlinedService'); ?></label>
<input type="text" name="email" id="email">
</div>
<div class="primaryPhone span3">
<label for="primaryPhone"><?php _e('Phone Number:','StreamlinedService'); ?></label>
<input type="text" name="primaryPhone" id="primaryPhone">
</div>
</div>
<div class="row formRow">
<div class="weight span2">
<label for="weight"><?php _e('Weight (lbs):','StreamlinedService'); ?></label>
<input type="text" name="weight" id="weight">
</div>
</div>
<div class="row formRow">
<div class="originPostalCode span3">
<label for="originPostalCode"><?php _e('Origin:','StreamlinedService'); ?></label>
<input type="text" name="originPostalCode" id="originPostalCode">
</div>
<div class="destinationPostalCode span3">
<label for="destinationPostalCode"><?php _e('Destination:','StreamlinedService'); ?></label>
<input type="text" name="destinationPostalCode" id="destinationPostalCode">
</div>
</div>
<div class="row">
<div class="whatsTransported span6">
<label for="whatsTransported"><?php _e('What can we help you transport?','StreamlinedService'); ?></label>
<textarea name="whatsTransported" id="whatsTransported" rows="5"></textarea>
</div>
<input type="hidden" name="formType" value="quote" />
<input type="hidden" name="siteReferer" value="<?php echo $blog_id ?>">
<input type="submit" id="submit" name="submit" value="<?php _e('Get Freight Quote','StreamlinedService') ?>" class="btn btn-primary btn-large span3 offset3" style="float:right;">
</div>
</form>
My question is two-fold: Is there a more efficient way to do this? If not, why isn't this working?
Just use the .submit directly on the form node (note the [0])
$('#quote #submit').submit();
becomes
$('#quote')[0].submit();
this bypasses the jQuery bound event and forces a postback.
You use the wrong approach to Jquery
You miss the key : Write Less Do More, the heart of JQuery.
Anyway try this:
"use strict";
/* Send info to the portal */
jQuery(function($) {
$('#quote').submit(function(e){
var tis = $(this);
$.ajax({
type: "POST",
url: "https://somewhere.on/the/internet.php",
cache: true,
dataType: "json",
data: tis.serialize(),
success: function(data){
if(data[1][0][0] == 2){
$('.alert').append( data[1][0][1].message ).addClass('alert-error').show();
} else if(data[1][0][0] == 0) {
console.log("Made it.");
$('#quote #submit').submit();
} else {
$('.alert').append( "Appologies, it seems like something went wrong. Please, <strong>call (877) 419-5523</strong> for immediate assistance or a free quote.");
}
},
error: function(data){console.log(data);}
});
e.stroPropagation();
e.preventDefault();
});
});
Last thin.. you CAN'T request a remote page that's not hosted on the same domain of the script.. For that ther's This answer