php not inserting data into table - javascript

I have a HTML form
<div class="contact-form col-md-6 " >
<form id="contact-form" method="post" action="" role="form">
<div class="form-group">
<input type="text" placeholder="Your Name" class="form-control" name="name" id="name" required>
</div>
<div class="form-group">
<input type="email" placeholder="Your Email" class="form-control" name="email" id="email" required>
</div>
<div class="form-group">
<input type="text" placeholder="Your Phone Number" class="form-control" name="phone" id="phone" required>
</div>
<div class="response_msg"></div>
<div id="mail-success" class="success">
Thank you. You are registerd. :)
</div>
<div id="mail-fail" class="error">
Sorry, don't know what happened. Try later :(
</div>
<div id="cf-submit">
<input type="submit" id="contact-submit" class="btn btn-transparent" value="Register" name="submit">
</div>
</form>
</div>
I need to submit form on same page and show message on successfully submission. I am using JS for this
<script>
$(document).ready(function(){
$("#contact-form").on("submit",function(e){
e.preventDefault();
if($("#contact-form [name='name']").val() === '')
{
$("#contact-form [name='name']").css("border","1px solid red");
}
else if ($("#contact-form [name='email']").val() === '')
{
$("#contact-form [name='email']").css("border","1px solid red");
}
else if ($("#contact-form [name='phone']").val() === '')
{
$("#contact-form [name='phone']").css("border","1px solid red");
}
else
{
$("#loading-img").css("display","block");
var sendData = $( this ).serialize();
$.ajax({
type: "POST",
url: "js/ajaxsubmit.php",
data: sendData,
success: function(data){
$("#loading-img").css("display","none");
$(".response_msg").text(data);
$(".response_msg").slideDown().fadeOut(3000);
$("#contact-form").find("input[type=text], input[type=email], textarea").val("");
}
});
}
});
$("#contact-form input").blur(function(){
var checkValue = $(this).val();
if(checkValue != '')
{
$(this).css("border","1px solid #eeeeee");
}
});
});
</script>
As soon i clicked on submit button page refresh but my i don't see my pho code inserting data in database.
<?php
require_once("conn.php");
if((isset($_POST['name'])&& $_POST['name'] !='') && (isset($_POST['email'])&& $_POST['email'] !='') && (isset($_POST['phone'])&& $_POST['phone'] !=''))
{
// require_once("contact_mail.php");
$yourName = $conn->real_escape_string($_POST['name']);
$yourEmail = $conn->real_escape_string($_POST['email']);
$yourPhone = $conn->real_escape_string($_POST['phone']);
$sql="INSERT INTO Beta_Registration (name, email, phone) VALUES ('".$yourName."','".$yourEmail."', '".$yourPhone."')";
if(!$result = $conn->query($sql)){
die('There was an error running the query [' . $conn->error . ']');
}
else
{
echo "Thank you! We will contact you soon";
}
}
else
{
echo "Please fill Name and Email";
}
?>
I want my form to submit on same page also stays on same block and shows the messages in div inside form when data entered successfully or failed into database.
The issues i am facing whenever i press submit button it refreshed the page and form data doesn't executed into database. It might be php or JS i am using. Please help me in this.

1- You need to add "return false" in your on submit function to prevent browser to submit the form
$(document).ready(function () {
$("#contact-form").on("submit", function (e) {
...
return false;
});
...
});
2- You need to match you database table name, and their columns name which you have used in your MySQL query.

Related

Google App Script Closure error when calling script

This is my first foray into Google scripts and I have a form that calls two different Google app scripts(both are in the .gs file). One Uploads a file while the other saves the form data to a google spreadsheet. For some reason I get an error when calling the file upload script
(Uncaught TypeError: Cannot read property 'closure_lm_407634' of null)
While the script that uploads the data works fine.
Saving the form data to spreadsheet(which works):
google.script.run.withUserObject(data).saveToSheet(data);
-- which calls:
function saveToSheet(data) {
var date = new Date();
var sheet = SpreadsheetApp.openById(submissionSSKey);
sheet
.appendRow([date, data.name, data.email, data.headline,
data.location, data.newsContent, data.websiteContent, data.expiry, data.fileUrl]);
}
Uploading file(doesn't work):
google.script.run
.withUserObject(theForm)
.withSuccessHandler(processForm)
.uploadFile(theForm);
-- which calls:
function uploadFile(form) {
var folder = DriveApp.getFolderById(folderId), doc = '', file = form.uploadedFile;
if (file.getName()) { doc = folder.createFile(file); }
return doc;
}
I can't for the life of me figure out why one call works while the other does not. I've tried every way I could think of to call the upload script but nothing works. I've tried removing the user object and success handler.
HTML:
<?!= include('styles'); ?>
<div id="container" class="col-lg-12 col-md-12 col-sm-12">
<header class="col-lg-offset-3 col-md-offset-3"></header>
<div class="col-lg-offset-3 col-lg-6 col-md-6 col-sm-12" id="form">
<h1 class="text-center">
SAS News Submission
</h1>
<span id="required-content">
<sup>*</sup>
Required
</span>
<br>
<br>
<form name="sas-form">
<label for="name" class="required">Contact Person/ Source of News</label>
<input type="text" name="name" value="test" class="form-control" id="name" required="required">
<br>
<label for="email" class="required">Contact Person's email (in case we have questions regarding your News content)</label>
<input type="email" name="email" value="me#me.com" id="email" class="form-control" required="required">
<br>
<label for="headline" class="required">Headline (try to keep below 10 words if possible) </label>
<input type="text" name="headline" value="headline" id="headline" class="form-control" required="required">
<br>
<label for="newsContent" class="required">News Content *Note all content must be fully edited to ensure posting</label>
<textarea rows="5" cols="0" name="newsContent" class="form-control" id="newsContent" required="required">
Content
</textarea>
<br>
<label class="required">Where would you like the News to be shared? (You may choose more than one)</label>
<ul id="social-list">
<li>
<input type="checkbox" name="newsletter" id="newsletter" value="newsletter">
<label for="newsletter"> Newsletter</label>
</li>
<li>
<input type="checkbox" name="social" id="social" value="social">
<label for="social"> Social Media (Facebook, LinkedIn, Twitter)</label>
</li>
<li>
<input type="checkbox" name="website" id="website" value="website" checked>
<label for="website"> Website </label>
</li>
</ul>
<br>
<label for="websiteContent">If you chose the website, please provide specific instructions on where you would like the content to be posted.</label>
<br>
<small>News and Events Page, Volunteer Page, Student Page, etc. Ex: Please post in the News and Events Page and send the link and headline out on social media.</small>
<textarea rows="5" cols="0" name="websiteContent" id="websiteContent" class="form-control">website content</textarea>
<br>
<label for="expiry">If your content has an expiration date, please share that date below.</label>
<input type="date" name="expiry" id="expiry" class="form-control">
<br>
<label>If you have files that need to be attached, pick them below.</label>
<input type="file" name="uploadedFile" id="file">
<br>
<div id="not-valid"><span></span></div>
<div id="error"><span>
An error occurred, please try submitting again.
</span></div>
<div id="success"><span>
Form submission was successful! Thank you!
</span></div>
<input type="button" value="Submit" class="btn btn-primary" id="submit"
onclick="validateForm(this.parentNode)">
</form>
</div>
</div>
<footer>
<?!= include('javascript'); ?>
</footer>
<script>
var validateForm = function(theForm)
{
var valid = true;
$('#not-valid span').empty();
$('input').removeClass('warning');
if($('#name').val() == '')
{
$('#name').addClass('warning');
$('#not-valid span').append('Please enter a name <br>');
valid = false;
}
if($('#email').val() == '')
{
$('#email').addClass('warning');
$('#not-valid span').append('Please enter an email <br>');
valid = false;
}
if($('#headline').val() == '')
{
$('#headline').addClass('warning');
$('#not-valid span').append('Please enter a headline <br>');
valid = false;
}
if($('#newsContent').val() == '')
{
$('#newsContent').addClass('warning');
$('#not-valid span').append('Please enter news content <br>');
valid = false;
}
if(!$('#social').is(':checked') && !$('#website').is(':checked') && !$('#newsletter').is(':checked'))
{
$('#not-valid span').append('Please choose where you would like the news to be shared. <br>');
$('#social-list').addClass('warning');
valid = false;
}
if(valid)
{
google.script.run.withSuccessHandler(processForm).uploadFile(theForm)
}
};
function processForm(file)
{
var fileUrl = file ? file.getUrl() : 'No file uploaded',
location = [];
if($('#social').is(':checked'))
{
location.push('social');
}
if($('#newsletter').is(':checked'))
{
location.push('newletter');
}
if($('#website').is(':checked'))
{
location.push('website');
}
var data = {
name: $('#name').val(),
email: $('#email').val(),
headline: $('#headline').val(),
location: location.toString(),
newsContent: $('#newsContent').val(),
websiteContent: $('#websiteContent').val(),
expiry: $('#expiry').val() ? $('#expiry').val() : 'No expiration date selected',
fileUrl: fileUrl
};
google.script.run.saveToSheet(data);
clearForm();
success();
};
var clearForm = function()
{
$("input[type=text], input[type=date], textarea, input[type=email], input[type=file]").val("");
$("input[type=checkbox]").attr('checked', false);
enableSubmit();
};
var success = function()
{
$('#success').show()
};
var enableSubmit = function()
{
$("#submit").prop('disabled', false);
};
</script>
I was able to reproduce your error. I have no idea why that error is occurring, but I found a way to make it work.
Here is what you need to do:
Put an id attribute into the upper form tag:
<form id="myForm">
Remove the button using an input tag.
Add a <button> tag outside of the form. Must be outside of the form. And get the form with document.getElementById('myForm')
<form id="myForm">
<input type="file" name="uploadedFile">
</form>
<button onclick="validateForm(document.getElementById('myForm'))">submit</button>
I've tested this. It got the file, and sent it to the server inside of the form element.
You can use Logger.log() in the server code without using the debugger.
function uploadFile(form) {
Logger.log('form: ' + form);
Logger.log('form.uploadedFile: ' + form.uploadedFile);
Logger.log('form.uploadedFile: ' + form.uploadedFile.getName());

jQuery ajax second post

When I hit the submit button at the first time these codes works. But when I hit the second time to the button even if email and password values were true nothing happens and the user can not login. But if I write the true values at the first time, it works and user can login. So I figured the cause of this problem is about the "return false;" phrase. But if I remove return false; phrase, the form posts and ajax codes become useless. I must avoid the posting without ajax.
jQuery:
<script>
$(document).ready(function(){
$('#submit-btn').click(function(){
var email = $('#email').val();
email = $.trim(email);
var password = $('#password').val();
password = $.trim(password);
if(email == "") {
$('#email').css({
"background-color": "#FF7070"
});
$('#box1').css({
"visibility": "visible"
});
return false;
}else if(password == "") {
$('#password').css({
"background-color": "#FF7070"
});
$('#box2').css({
"visibility": "visible"
});
return false;
}else{
$.ajax({
type: "POST",
url: "ajax.php",
data: $('#loginform').serialize(),
timeout: 5000,
success: function(c) {
if(c == "no") {
$('#box3').css({
"visibility": "visible"
});
return false;
} else if (c == "ok") {
window.location.href = "homepage.php";
}
},
error: function(a, b) {
if (b == "timeout") {
alert("Error: #101");
}
},
statusCode: {
404: function(){
alert("Error: #102")
}
}
});
}
return false;
})
});
</script>
Html:
<form name="loginform" id="loginform" method="post" action="">
<div class="field">
<input type="text" maxlength="40" id="email" name="email" placeholder="E-mail">
</div>
<div class="field">
<input type="password" id="password" name="password" placeholder="Password" autocomplete="off">
</div>
<div class="field">
<input type="submit" id="submit-btn" value="Log in">
</div>
<div class="keep-login">
<label for="remember">
<input type="checkbox" name="remember" id="remember" checked="checked">Remember me
</label>
<span>Forgot password?</span>
</div>
</form>
PHP:
if(Input::exists()) {
if(Token::check(Input::get('token'))) {
$validate = new Validate();
$validation = $validate->check($_POST, array(
'email' => array('required' => true),
'password' => array('required' => true)
));
if($validation->passed()) {
$user = new User();
$remember = (Input::get('remember') === 'on') ? true : false;
$login = $user->login(Input::get('email'), Input::get('password'), $remember);
if($login) {
echo "ok";
} else {
echo "no";
}
} else {
echo "no";
}
}
}
First, remove the method and action attributes of the form element. You can remove the form tag altogether but if you want to support non-javascript submissions, you'll need the form tag (however, the original question did not ask for this). You're 'submitting' the form via jQuery, so you don't need a method and an action on a form tag.
Input type="password" never autocompletes, so you don't need that attribute.
I also added an error div. Here is your new html:
<div id="error" style="display: none;">Login failed.</div>
<form>
<div class="field">
<input type="text" maxlength="40" id="email" name="email" placeholder="E-mail">
</div>
<div class="field">
<input type="password" id="password" name="password" placeholder="Password">
</div>
<div class="field">
<input type="submit" id="submit-btn" value="Log in">
</div>
<div class="keep-login">
<label for="remember">
<input type="checkbox" name="remember" id="remember" checked="checked">Remember me
</label>
<span>Forgot password?</span>
</div>
</form>
Replace your $.ajax statement with a $.post statement, and simply your logic.
$.post("ajax.php", { e: email, p: password }, function (data) {
if (data == "ok") window.location.href = "homepage.php";
else $("#error").slideDown().delay(3000).slideUp(); // I added div#error with "Failed to Login" message in the html above
});
This code will now redirect if the returned data is "ok"; otherwise, it will show div#error (again, this is in the html above), delay for 3 seconds, and then hide the message.
The return false; is unnecessary in each instance in your code above because after each conditional, the code ends - there is no other code to prevent from executing (which is why you would use return false; in this context).
You can do the $.trim on the same line as when you assign the variables, like I did with the slideUp, delay, and slideDown.

Implemented reCaptcha... Still getting spam

I just implemented a reCaptcha on a WP Site contact form.
It works like this:
Submission is cancelled using $form.submit(function(e) { e.preventDefault(); return false; }
reCaptcha is dynamically inserted before the form.
if reCaptcha's AJAX response is successful, perform HTLMFormElement.submit, using $form[0].submit();
HTML
<div id="ny_cf-3" class="footer-ny widget widget_ny_cf"><h2 class="widgettitle">Contact Us</h2>
<!-- contact form widget -->
<p class="response"></p>
<form method="post" enctype="multipart/form-data" class="ny-footer-contact-form" action="http://wpstage.leadscon.com/leadsconny/" data-submit="return fm_submit_onclick(1)" id="fm-form-1" name="fm-form-1">
<div class="form-group" id="fm-item-text-53546749dea0d">
<input type="text" name="text-53546749dea0d" id="text-53546749dea0d" style="width:px;" placeholder="Your name" class="form-control">
</div>
<div class="form-group" id="fm-item-text-5354674e4b90b">
<input type="text" name="text-5354674e4b90b" id="text-5354674e4b90b" style="width:px;" placeholder="Email address" class="form-control">
</div>
<div class="form-group" id="fm-item-textarea-5354675009293">
<textarea name="textarea-5354675009293" id="textarea-5354675009293" style="width:px;height:100px;" placeholder="Your message" class="form-control"></textarea>
</div>
<input type="email" class="teddybear" style="display:none">
<button type="submit" id="fm_form_submit" name="fm_form_submit" class="btn btn-primary btn-block submit">Submit</button>
<input type="hidden" name="fm_nonce" id="fm_nonce" value="1165f15ac2">
<input type="hidden" name="fm_id" id="fm_id" value="1">
<input type="hidden" name="fm_uniq_id" id="fm_uniq_id" value="fm-536b89c742833">
<input type="hidden" name="fm_parent_post_id" id="fm_parent_post_id" value="4">
</form>
<!-- end cf widget -->
</div>
JavaScript code:
var getRecaptcha = function($form, $frmResponseField) {
$form.fadeOut();
// Add the reCaptcha
// ========================================================================
var $recaptchaForm = $('<form class="recaptcha_form" style="display:none;"><p><strong>Spam verification (sorry):</strong></p><p class="response"></p><button class="btn btn-success btn-sm" type="submit">Submit</button></form>');
var recaptcha_el = $('<div id="recaptcha_el"></div>').insertAfter($recaptchaForm.find('.response')).get(0);
$recaptchaForm.insertBefore($form).slideDown();
leadsCon.reCaptchaHTML().appendTo($(recaptcha_el));
Recaptcha.create('6LdUZPASAAAAAGZI_z-qQ7988o0nGouHHtIsh4yX', recaptcha_el, {
theme : 'custom',
custom_theme_widget: 'recaptcha_widget',
callback: Recaptcha.focus_response_field
});
// Bind submit action to check it
$recaptchaForm.submit(function(e) {
e.preventDefault();
var challenge = Recaptcha.get_challenge();
var response = Recaptcha.get_response();
var $btn = $recaptchaForm.find('button[type="submit"]')
var btnVal = $btn.html();
var $responseField = $recaptchaForm.find('.response');
var data = {
action: 'verify_recaptcha',
challenge: challenge,
response: response
};
$btn.html("<i class='dashicons dashicons-clock'></i>");
$responseField.text('');
$.post(ajax_object.ajax_url, data, function(response) {
if ( response.success == true ) {
$responseField.removeClass('text-danger').addClass('text-success').html('<i class="icon-ok"></i> You got it. One second...');
// We're ok.. send.
Recaptcha.destroy();
$recaptchaForm.remove();
$frmResponseField.removeClass('text-danger').addClass('text-success').html('<i class="icon-ok"></i> Wait while we send your message.');
$form[0].submit();
} else {
$responseField.removeClass('text-success').addClass('text-danger').html('<i class="dashicons dashicons-dismiss"></i> Oops! Try again.');
$btn.html(btnVal);
}
});
});
};
$('.ny-footer-contact-form').submit(function (e) {
e.preventDefault();
var $form = $(this);
var $responseField = $form.siblings('.response').removeClass('text-success text-danger').html('');
var command = $form.attr('data-submit').match(/return (\w+)\((.+)\)/i);
var fn = window[command[1]];
var $honeypot = $form.find('input.teddybear');
if ( fn(command[2]) && $honeypot.val() == '' ) {
getRecaptcha($form, $responseField);
} else {
$responseField.removeClass('text-success').addClass('text-danger').html('<i class="dashicons dashicons-dismiss"></i> There are missing fields.');
}
return false;
});
My impression is that since $form[0].submit() is not in any way filtered and doesn't trigger the submit event from jQuery, spammers are using that to submit the form and circunvent the reCaptcha.
What can I do?
A spammer will not execute your javascript code. They will simply post to the correct URL. Therefore you can't reliably validate anything on the client, you'll have to validate it on the server as well.
Bots can even does not run your JS - they just find forms in raw html and try to act as an user submitting the form. You have to validate reCaptcha value on server side, see here: https://developers.google.com/recaptcha/docs/php

jQuery Ajax - no success

success in my AJAX call doesn't trigger at all, and I can't figure out why. None of the alerts specified in the AJAX file are popping up.
The form:
<form onsubmit="check_reg();return false;" method="post" name="reg_form" id="reg">
<label class="error" id="reg_error"></label>
<label for="login_reg">Login</label>
<input type="text" name="login" id="login_reg" placeholder="Login">
<label for="email_reg">Email</label>
<input type="text" name="email" id="email_reg" placeholder="Email">
<label for="haslo_reg">Password</label>
<input type="password" name="password" id="pass_reg" placeholder="Password">
<button type="submit">Register</button>
</form>
reg_script.php:
if (!empty($_POST['login']) && !empty($_POST['password']) && !empty($_POST['email'])) {
$login = $mysqli->real_escape_string($_POST['login']);
$password = $mysqli->real_escape_string($_POST['password']);
$email = $mysqli->real_escape_string($_POST['email']);
if ($mysqli->query("INSERT INTO users (login, password, email) VALUES('$login', '$password', '$email')")) {
echo "ok";
}
else {
echo "error";
}
}
else {
echo "empty";
}
AJAX
function check_reg() {
$.ajax({
url: 'reg_script.php',
type: "POST",
data: "login=" + $('#login_reg').val() + "&password=" + $('#pass_reg').val() + "&email=" + $('#email_reg').val(),
success: function(result) {
if (result == 'ok') {
alert('ok');
}
else if (result == 'error') {
alert('error');
}
else if (result == 'empty') {
alert('empty');
}
},
});
}
Any ideas what the problem might be?
EDIT: I should've added that I used this tutorial: http://developertips.net/post/display/web/3/dynamic-login-form-with-ajax-php/ and managed to get the login form working just fine, it's just the registration form that's acting up.
Change
<form onsubmit="check_reg();return false;" method="post" name="reg_form" id="reg">
<label class="error" id="reg_error"></label>
<label for="login_reg">Login</label>
<input type="text" name="login" id="login_reg" placeholder="Login">
<label for="email_reg">Email</label>
<input type="text" name="email" id="email_reg" placeholder="Email">
<label for="haslo_reg">Password</label>
<input type="password" name="password" id="pass_reg" placeholder="Password">
<button type="submit">Register</button>
</form>
to:
<form>
<label class="error" id="reg_error"></label>
<label for="login_reg">Login</label>
<input type="text" name="login" id="login_reg" placeholder="Login">
<label for="email_reg">Email</label>
<input type="text" name="email" id="email_reg" placeholder="Email">
<label for="haslo_reg">Password</label>
<input type="password" name="password" id="pass_reg" placeholder="Password">
<input type="button" onclick="check_reg()">Register</button>
</form>
That way, your HTML file will call your check_reg() which then calls your php-file. You don't need method=post and so on in HTML-file. All this information is already in your function.
Btw, your data-attribute in check_reg() function, I recommend that you change that to serializeArray() instead.
One more thing I just realized:
success: function(result) {
The result-variable contains the error-messages form the serverside (php). so all you have to do is:
success: function(result) {
alert(result);
Here you are using POST request, but sending data as querystring as used for GET request.
Use data in form of object:
data: {'login': $('#login_reg').val() ,'password':$('#pass_reg').val() ,'email':$('#email_reg').val()}
You can also check with print_r($_POST) in your php file, so that you can see, whether data is posted or not.
So use follwing code in ajax:
function check_reg() {
$.ajax({
url: 'reg_script.php',
type: "POST",
data: {'login': $('#login_reg').val() ,'password':$('#pass_reg').val() ,'email':$('#email_reg').val()},
success: function(result) {
if (result == 'ok') {
alert('ok');
}
else if (result == 'error') {
alert('error');
}
else if (result == 'empty') {
alert('empty');
}
},
});
}

Form doesn't submit on callback

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

Categories