I trying to autofill my form with cnic which i set as unique. If Cnic exists then all fields against the entered cnic with autofill. how i will do that? I have uploaded my form , jquery and controller. If you need more data to understand you can ask. I am getting data but form is not filling with ajax request. how to resolve this issue?
My form:
<form class="form" method="post" action="{{route('add.member')}}">
<input type="hidden" name="_token" value="{{csrf_token()}}">
<div class="row justify-content-md-center">
<div class="col-md-6">
<div class="form-body">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="name">Name</label>
<input type="text" id="name" class="form-control" placeholder="Enter Name" name="name" value="{{old('name')}}">
#if ($errors->has('name'))
<span style="color: red" class="help-block">{{ $errors->first('name') }}</span>
#endif
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="cnic">CNIC</label>
<input type="number" id="cnic" class="form-control" placeholder="Enter CNIC" name="cnic" value="{{old('cnic')}}">
#if ($errors->has('cnic'))
<span style="color: red" class="help-block">{{ $errors->first('cnic') }}</span>
#endif
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="mobile_number">Mobile Number</label>
<input type="number" id="mobile_number" class="form-control" placeholder="Enter Mobile Number" name="mobile_number" value="{{old('mobile_number')}}">
#if ($errors->has('mobile_number'))
<span style="color: red" class="help-block">{{ $errors->first('mobile_number') }}</span>
#endif
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="party_joining_year">Party Joining Year</label>
<input type="text" id="party_joining_year" class="form-control" placeholder="Enter Party Joining Year" name="party_joining_year" value="{{old('party_joining_year')}}">
#if ($errors->has('party_joining_year'))
<span style="color: red" class="help-block">{{ $errors->first('party_joining_year') }}</span>
#endif
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="qualification">Qualification</label>
<input type="text" id="qualification" class="form-control" placeholder="Enter Qualification" name="qualification" value="{{old('qualification')}}">
#if ($errors->has('qualification'))
<span style="color: red" class="help-block">{{ $errors->first('qualification') }}</span>
#endif
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="party_position">Party Position</label>
<input type="text" id="party_position" class="form-control" placeholder="Enter Party Position" name="party_position" value="{{old('qualification')}}">
#if ($errors->has('party_position'))
<span style="color: red" class="help-block">{{ $errors->first('party_position') }}</span>
#endif
</div>
</div>
</div>
<div class="form-group">
<label for="profession">Profession</label>
<input type="text" id="profession" class="form-control" placeholder="Enter Profession" name="profession" value="{{old('qualification')}}">
#if ($errors->has('profession'))
<span style="color: red" class="help-block">{{ $errors->first('profession') }}</span>
#endif
</div>
<div class="form-group">
<label for="district">District/Tahseel</label>
<input type="text" id="district" class="form-control" placeholder="Enter District" name="district" value="{{old('qualification')}}">
#if ($errors->has('district'))
<span style="color: red" class="help-block">{{ $errors->first('district') }}</span>
#endif
</div>
</div>
</div>
</div>
</form>
Ajax:
$("#cnic").focusout(function(e){
// alert($(this).val());
var cnic = $(this).val();
$.ajax({
type: "POST",
url: "{{route('get.all.fields')}}",
data: {'cnic':cnic},
dataType: 'json',
success : function(e) {
if(e===0){
$('.flash-message').html('Data not found');
$('#cnic').val('');
}
else {
$('.flash-message').html('');
r = $.parseJSON(e); //convert json to array
$('#name').autocomplete({
source: r.name,
}); //assign name value
$('#mobile_number').autocomplete({
source: r.mobile,
}); //assign email value
$('#party_joining_year').autocomplete({
source: r.party_joining_year,
}); //assign department value
$('#qualification').autocomplete({
source: r.qualification,
}); //assign department value
$('#party_position').autocomplete({
source: r.party_position,
}); //assign department value
$('#profession').val(r.profession).autocomplete({
source: r.profession,
}); //assign department value
$('#district').val(r.profession).autocomplete({
source: r.district,
}); //assign department value
$("#cnic").html(e);
}
}
});
});
</script>
My Controller:
public function getAllFields(Request $request)
{
$getFields = Member::where('cnic', $request->get('cnic'))->get(['name','mobile','party_joining_year','qualification','party_position','profession','district']);
return json_encode($getFields[0]['mobile']);
}
Route:
Route::post('/get_fields', 'MemberController#getAllFields')->name('get.all.fields');
In your controller you should be returning a proper JSON response
public function getAllFields(Request $request)
{
try {
$getFields = Member::where('cnic',$request->cnic)->first();
// here you could check for data and throw an exception if not found e.g.
// if(!$getFields) {
// throw new \Exception('Data not found');
// }
return response()->json($getFields, 200);
} catch (\Exception $e) {
return response()->json([
'message' => $e->getMessage();
], 500);
}
}
You shouldn't need to parse the json as
dataType: 'json'
will automatically expect JSON and the response variable will already be an object and you just need to map it like
$("#cnic").focusout(function(e){
// alert($(this).val());
var cnic = $(this).val();
$.ajax({
type: "POST",
url: "{{route('get.all.fields')}}",
data: {'cnic':cnic},
dataType: 'json',
success : function(data) {
$('#name').val(data.name);
$('#mobile_number').val(data.mobile);
$('#party_joining_year').val(data.party_joining_year);
...
},
error: function(response) {
alert(response.responseJSON.message);
}
});
});
You must read the laravel docs carefully. you don't need to get the inputs if you want a row from db.
The ->get() method returns an array of al the matched rows.
The ->first() method returns only the first row that matches the where clause.
So you must first correct the eloquent query. If you want to specify the columns that you want to retrieve from the database you must use the ->select method. But I don't see any reason to do that. so your controller must look like this:
public function getAllFields(Request $request)
{
$getFields = Member::where('cnic',$request->get('cnic'))->first();
return json_encode($getFields);
}
After that, you must decode the JSON array with jquery and add the values one by one.
$("#cnic").focusout(function(e){
// alert($(this).val());
var cnic = $(this).val();
$.ajax({
type: "POST",
url: "{{route('get.all.fields')}}",
data: {'cnic':cnic},
dataType: 'json',
success : function(e) {
if(e.length === 0){
$('.flash-message').html('Data not found');
$('#cnic').val('');
}
else {
$('.flash-message').html('');
r = $.parseJSON(e); //convert json to array
$('#name').val(r.name);
$('#mobile_number').val(r.mobile);
$('#party_joining_year').val(r.party_joining_year)
and so on...
$("#cnic").html(e); //-> I dont realy understand why you use this part of code?
}
}
});
});
Remember: you must get the fields from "r" object exactly by the name of database column that you retrieve the data.
Related
Using Laravel framework.
I don't get it. I have a hidden input with id = prime near the top.
<form name="paymentForm" action="/parking_302/upload_payment" method="POST" role="form" class="form-horizontal">
{{ csrf_field() }}
<input type="hidden" id="parking_lot_id" name="parking_lot_id" value="{{ $parking_lot_id }}">
<input type="hidden" id="booking_id" name="booking_id" value="{{ $booking_id }}">
<input type="hidden" id="Price" name="Price" value="{{ $Price }}">
<input type="hidden" id="prime" name="prime"> {{-- To be obtained --}}
<legend>電子發票 & TapPay 付款</legend>
<div class="form-group">
<label for="CustomerEmail" class="col-lg-3 col-md-3 col-xs-4">電子信箱</label>
<div class="col-lg-9 col-md-9 col-xs-8">
<input type="email" class="form-control" id="CustomerEmail" name="CustomerEmail" value="{{ old('CustomerEmail') }}">
</div>
</div>
<div class="form-group">
<label for="CustomerPhone" class="col-md-3 col-xs-4">手機號碼</label>
<div class="col-md-9 col-xs-8">
<input type="number" class="form-control" id="CustomerPhone" name="CustomerPhone" value="{{ old('CustomerPhone') }}">
</div>
</div>
<hr>
<div class="form-group">
<div class="col-md-offset-3 col-xs-offset-4 col-md-9 col-xs-8">
<select class="form-control" id="giveTongBian" name="giveTongBian">
<option value="no" #if(old('giveTongBian') === "no") selected #endif>不需統編</option>
<option value="yes" #if(old('giveTongBian') === "yes") selected #endif>輸入統編</option>
</select>
</div>
</div>
<div class="form-group" id="customerIdentGroup">
<label for="CustomerIdentifier" class="col-md-3 col-xs-4">統一編號</label>
<div class="col-md-9 col-xs-8">
<input type="text" class="form-control" id="CustomerIdentifier" name="CustomerIdentifier" value="{{ old('CustomerIdentifier') }}">
</div>
</div>
<div class="form-group" id="customerNameGroup">
<label for="CustomerName" class="col-md-3 col-xs-4">買受人</label>
<div class="col-md-9 col-xs-8">
<input type="text" class="form-control" id="CustomerName" name="CustomerName" value="{{ old('CustomerName') }}">
</div>
</div>
<div class="form-group" id="customerAddrGroup">
<label for="CustomerAddr" class="col-md-3 col-xs-4">地址</label>
<div class="col-md-9 col-xs-8">
<input type="text" class="form-control" id="CustomerAddr" name="CustomerAddr" value="{{ old('CustomerAddr') }}">
</div>
</div>
<div class="tappay-form col-xs-offset-1 col-xs-10">
<h4 style="color: darkkhaki;">信用卡</h4>
<div class="form-group card-number-group">
<label for="card-number" class="control-label"><span id="cardtype"></span>卡號</label>
<div class="form-control card-number"></div>
</div>
<div class="form-group expiration-date-group">
<label for="expiration-date" class="control-label">卡片到期日</label>
<div class="form-control expiration-date" id="tappay-expiration-date"></div>
</div>
<div class="form-group cvc-group">
<label for="cvc" class="control-label">卡片後三碼</label>
<div class="form-control cvc"></div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">Pay</button>
</div>
</div>
</form>
I then have a on submit event which does a few things. At the bottom is me updating the hidden input with id = prime.
$('form').on('submit', function (event) {
//Code for first part of form begin
var boolFlag = true; //Default is submit
var errorMsg = ""; //Initial message
//Begin validation
var numOfNonEmptyFields = 0;
if(document.forms["paymentForm"]["CustomerEmail"].value != "") {
numOfNonEmptyFields++;
}
if(document.forms["paymentForm"]["CustomerPhone"].value != "") {
numOfNonEmptyFields++;
}
if(numOfNonEmptyFields == 0) {
errorMsg += "請輸入至少一個電子信箱或手機號碼.\n";
boolFlag = false;
}
//End validation
//Final steps: overall error message + success or fail case
if(boolFlag == false) {
alert("錯誤:\n" + errorMsg);
return false;
}
//Code for first part of form end
// fix keyboard issue in iOS device
forceBlurIos()
const tappayStatus = TPDirect.card.getTappayFieldsStatus()
console.log(tappayStatus)
// Check TPDirect.card.getTappayFieldsStatus().canGetPrime before TPDirect.card.getPrime
if (tappayStatus.canGetPrime === false) {
bootbox.alert({
title: "錯誤訊息",
message: "取得不了Prime.",
buttons: {
ok: {
label: "OK",
className: "btn btn-primary"
}
}
});
return false
}
// Get prime
TPDirect.card.getPrime(function (result) {
if (result.status !== 0) {
bootbox.alert({
title: "錯誤訊息",
message: result.msg,
buttons: {
ok: {
label: "OK",
className: "btn btn-primary"
}
}
});
return false
}
$("#prime").val(result.card.prime);
})
})
I've tested the hidden input with alert($("#prime").val()) directly after and it seems updated, however after submission, my Controller receives the value as null while other hidden input values are correct. So I suspect it's something got to do with the on submit event.
Added id attribute to the form element:
<form id="paymentForm" name="paymentForm" action="/parking_302/upload_payment" method="POST" role="form" class="form-horizontal">
Removed type from the button and added id:
<button id="submit-btn" class="btn btn-default">Pay</button>
Introduced a new click listener:
$(document).on("click","#submit-btn", function(event){
event.preventDefault();
validateAndSendForm();
});
Introduced a new function for the final form submit:
function submitForm(){
//do other stuff here with the finalized form and data
//.....
$( "#paymentForm" ).submit();
}
And put all of your old things into a new function as well:
function validateForm(){
//Code for first part of form begin
var boolFlag = true; //Default is submit
var errorMsg = ""; //Initial message
...
...
...
}
// Get prime
TPDirect.card.getPrime(function (result) {
if (result.status !== 0) {
bootbox.alert({
title: "錯誤訊息",
message: result.msg,
buttons: {
ok: {
label: "OK",
className: "btn btn-primary"
}
}
});
return false;
}
$("#prime").val(result.card.prime);
//use when you are ready to submit
submitForm();
})
}
So, basically you will have a "submitForm" function that you can use whenever you are ready to submit the form.
Seems like TPDirect.card.getPrime is something that gets data asynchronously so the $('form').on('submit' function won't wait for it to finish.
I am implementing Google's Invisible Recaptcha and I am trying to have everything run from my mail.js file (and I would really prefer to keep it there). For some reason Recaptcha is not finding "onSuccess" in mail.js but if I move it to the HTML inside <script></script> it works.
I am getting this error in JavaScript console: ReCAPTCHA couldn't find user-provided function: onSuccess when it is in mail.js
$(".input-field").each(function () {
var $this = $(this);
if ($this.val().length) {
$this.parent().addClass("input--filled")
}
$this.on("focus", function () {
$this.parent().addClass("input--filled");
});
$this.on("blur", function () {
if (!$this.val().length) {
$this.parent().removeClass("input--filled")
}
})
});
$(function () {
// Get the form.
var form = $('#ajax-contact'),
// Get the messages div.
formMessages = $('#form-messages');
// Set up an event listener for the contact form.
$(form).submit(function (e) {
// Stop the browser from submitting the form.
grecaptcha.execute();
e.preventDefault();
});
});
var onSuccess = function(response) {
$("#btn-submit").addClass("btn-loading");
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function (response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error').addClass('success').fadeIn().delay(5000).fadeOut();
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$(form).trigger("reset");
grecaptcha.reset();
$("#btn-submit").removeClass("btn-loading");
})
.fail(function (data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success').addClass('error').fadeIn().delay(5000).fadeOut();
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
$("#btn-submit").removeClass("btn-loading");
});
};
here is the HTML:
<form id="ajax-contact" class="" method="post" action="mailer.php">
<fieldset>
<div class="row">
<div class="input col-xs-12 col-sm-12 padding-bottom-xs-50 padding-bottom-40">
<label class="input-label" for="name">
<span class="input-label-content font-second" data-content="name">name *</span>
</label>
<input class="input-field" type="text" name="name" id="name" required />
</div>
<div class="input col-xs-12 col-sm-6 padding-bottom-xs-50 padding-bottom-50">
<label class="input-label" for="email">
<span class="input-label-content font-second" data-content="email">email *</span>
</label>
<input class="input-field" type="email" name="email" id="email" required />
</div>
<div class="input col-xs-12 col-sm-6 padding-bottom-xs-60 padding-bottom-50">
<label class="input-label" for="company">
<span class="input-label-content font-second" data-content="company">company</span>
</label>
<input class="input-field" type="text" name="company" id="company" />
</div>
<div class="message col-xs-12 col-sm-12 padding-bottom-xs-40 padding-bottom-30">
<label class="textarea-label font-second" for="message">message *</label>
<textarea class="input-field textarea" name="message" id="message" required></textarea>
</div>
</div>
<div class="g-recaptcha" data-sitekey="6Lf-6XQUAAAAAGhsZxXTlA3MtMGr_xDhOXPG-Ds0" data-badge="inline" data-size="invisible" data-callback="onSuccess"></div>
<div id="form-messages" class="form-message"></div>
<div class="col-xs-12 margin-top-30 text-center">
<button id="btn-submit" type="submit" class="btn btn-animated btn-contact ripple-alone" data-text="send it"><span class="btn-icon"><span class="loader-parent"><span class="loader3"></span></span>
</span>
</button>
</div>
</fieldset>
I have a forms.ImageField in my model called Post. When I create an instance of it, I do it via Ajax, while posting serialized data with data=$(this).serialize() to my PostCreateAPIView, which is a generic API CreateView of Django REST Framework, but this method serializes data only and ignores my image.
Here's my code:
My CreateAPIView:
class PostCreateAPIView(generics.CreateAPIView):
serializer_class = PostModelCreateSerializer
permission_classes = [permissions.IsAuthenticated]
def perform_create(self, serializer):
print(self)
serializer.save(user = self.request.user)
My Form:
class PostModelCreateForm(forms.ModelForm):
content = forms.CharField(
label="",
help_text="",#text to help
widget=forms.Textarea( attrs={
'cols' : "50", #size
'rows' : "6", #size
'placeholder' : 'Votre publication',
'style' : 'resize : none'
}))
group = forms.ChoiceField(choices=USER_GROUPS, label='')
class Meta:
model = Post #we define the model
fields = [
"content",
"group",
"photo"
]
$(document.body).on("submit", ".post_form_class",function(event){
event.preventDefault();
this_ = $(this);
var formData = this_.serialize();
$.ajax({
method : "POST",
url : createPostUrl,
data : formData,
success : function(data){
},
error : function(data){
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id = 'post-form' class="post_form_class" method="POST" action="" enctype="multipart/form-data">
<input type='hidden' name='csrfmiddlewaretoken' value='6bgEU7jPVxXskBGJzP7KzSj9mz75k2dpSqG9Fn1kfghUeWQPTKCbm8JJc5za0ecl' />
<p></p>
<div id="div_id_content" class="form-group"> <div class="controls "> <textarea name="content" cols="50" rows="6" placeholder="Votre publication" style="resize : none" class="textarea form-control" required id="id_content">
</textarea> </div> </div> <div id="div_id_group" class="form-group"> <label for="id_group" class="control-label requiredField">
Group<span class="asteriskField">*</span> </label> <div class="controls "> <select name="group" class="select form-control" id="id_group"> <option value="1" selected>Département juridique</option> <option value="2">Département ingénieurs</option> <option value="3">Département Commerce</option> <option value="4">Nouveau</option>
</select> </div> </div> <div id="div_id_photo" class="form-group"> <label for="id_photo" class="control-label ">
Photo
</label> <div class="controls "> <input type="file" name="photo" class="clearablefileinput" id="id_photo" /> </div> </div>
<div class="row">
<div class='col-sm-2 '>
<input class="btn btn-primary submit_form" id="submit_form" type="submit" value="Publier"/>
</div>
<div class='col-sm-1 col-sm-offset-8 '>
<span class='post-chars-left' > </span>
</div>
</div>
</form>
N.B: I've tried formData = new FormData(this_); but I get this error:
TypeError: Argument 1 of FormData.constructor does not implement interface HTMLFormElement
Thanks to Luca, here is the answer:
$(document.body).on("submit", ".post_form_class",function(event){
event.preventDefault();
var formData = new FormData(this);
$.ajax({
method : "POST",
url : createPostUrl,
data : formData,
processData:false,
contentType:false,
success : function(data){
location.reload(true);
},
error : function(data){
console.log("ERROR:CH0x2 while fetching after creation form submit");
console.log("data :",data.status, data.statusText);
}
});
});
<form name="LPform" novalidate>
<div class="form-row clearfix">
<label class="lbl-fld" style="margin-left: 12%;width:20%;">Email ID</label>
<input class="mob-adj-inpbx " type="email" name="uemail" ng-model="useremail" placeholder=" me#example.com" ng-required="true"/>
<div class="valid-chk validation-loginpopup" ng-show="LPform.uemail.$dirty && allow_Invalid">
<i style="font-size: 1.15em;padding:0px;" ng-class="{'false':'icon-close', 'true': 'icon-correct'}[LPform.uemail.$valid]" class="icon-correct"></i>
</div>
<div class="error-prompt" ng-show="LPform.uemail.$dirty && allow_Invalid">
</div>
</div>
<div class="form-row clearfix">
<label class="lbl-fld" style="margin-left: 12%;width:20%;">PASSWORD</label>
<input class="mob-adj-inpbx" type="password" name="upassword" ng-model="userpassword" placeholder=" password" ng-required="true"/>
<div class="valid-chk validation-loginpopup" ng-show="LPform.upassword.$dirty && allow_Invalid">
<i style="font-size: 1.15em;padding:0px;" ng-class="{'false':'icon-close', 'true': 'icon-correct'}[LPform.upassword.$valid]" class="icon-correct"></i>
</div>
<div class="error-prompt" ng-show="LPform.upassword.$dirty && allow_Invalid">
</div>
</div>
<div id="server_message" class="form-row clearfix basic-error-msg-loginpopup" ng-show="server_message">
{{server_message}}
</div>
<div class="btn-container clearfix mobile-adj" style="margin-left:17.2%;">
<div class="btn-wrap btn-loginpopup">
<input style="max-height:40px;width:121%;" type="submit" name="commit" value="LOGIN" ng-click="login_request()"/>
</div>
</div>
</form>
This part is displayed to the user and the inputs are validated using angular validations. All validations are working fine.
$scope.login_request = function(){
if(LPform.useremail.$valid && LPform.userpassword.$valid) {
$scope.allow_Invalid = "true";
$http({
method: 'POST',
url: '/users/home_login',
data: {email: $scope.useremail, password: $scope.userpassword}
}).success(function (response) {
console.log(response);
window.location = response.location;
}).error(function (response) {
console.log(response);
$scope.server_message = response.server_message;
});
}
else if(!LPform.useremail.$valid) {
$scope.allow_Invalid = "true";
$scope.server_message = "Please enter valid email.";
}
else if(!LPform.userpassword.$valid) {
$scope.allow_Invalid = "true";
$scope.server_message = "Please enter valid password.";
}
else{
$scope.allow_Invalid = "true";
$scope.server_message = "Request Failed.";
}
};
This part is in javascript file where I want to use the validations to decide whether to send a request to the server or not. The conditions I have used in the if else clause is not working, which I randomly tried btw. I am aware that I can disable Login button, however, I don't want to implement this that way.
I believe your problem is that the form name is bound to $scope and isn't a global variable.
In controller change
LPform
To
$scope.LPform
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