I have the following html snippit from my view and js code to handel the form request.
$('#quick-enquiry').on('submit', function(e) {
e.preventDefault();
$(".submit").prop("disabled", true);
data = $(this).serialize();
action = $(this).attr('action');
$.ajax({
type: 'POST',
url: action,
data: data,
headers: {
"X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content")
},
success: function(data) {
if ($.isEmptyObject(data.error)) {
$("#quick-enquiry").trigger("reset");
$('.print-error-msg').find('ul').empty();
$('.print-error-msg').css('display', 'block');
$("#response-msg").toggleClass('uk-alert-danger uk-alert-success');
$('.print-error-msg').find('ul').append("<li>" + data.success + "</li>");
setTimeout(function() {
$('.print-error-msg').fadeOut();
$(".submit").prop("disabled", false);
UIkit.modal("#modal-quick-enquiry").hide();
}, 3000);
} else {
printMessageErrors(data.error);
}
}
});
});
function printMessageErrors(msg) {
$('.print-error-msg').find('ul').empty();
$('.print-error-msg').css('display', 'block');
$.each(msg, function(key, value) {
$('.print-error-msg').find('ul').append("<li>" + value + "</li>");
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.0-rc.26/js/uikit.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.0-rc.26/css/uikit.min.css" rel="stylesheet" />
<form action="{{ route('frontend-postEnquiry') }}" method="POST" id="quick-enquiry">
<input type="hidden" id="tour-id" value="1">
<div class="uk-margin">
<label class="uk-form-label" for="form-stacked-text">Full Name</label>
<div class="uk-form-controls">
<input class="uk-input uk-form-width-large" type="text" placeholder="Full Name" id="fullName" name="fullName">
</div>
</div>
<div class="uk-margin">
<label class="uk-form-label" for="form-stacked-text">Email</label>
<div class="uk-form-controls">
<input class="uk-input uk-form-width-large" type="email" placeholder="Email" id="email" name="email">
</div>
</div>
<div class="uk-margin">
<label class="uk-form-label" for="form-stacked-text">Message</label>
<div class="uk-form-controls">
<textarea class="uk-textarea uk-form-width-large" rows="4" placeholder="Some Message...." id="enquiryMessage" name="enquiryMessage"></textarea>
</div>
</div>
<p class="uk-text-right">
<button class="uk-modal-close-default" type="button" uk-close></button>
<button class="uk-button uk-button-primary submit uk-width-1-1" type="submit">Send</button>
</p>
</form>
With the above code I'm getting
419
Sorry, your session has expired. Please refresh and try again.
I've set CSRF-TOKEN in ajax and in head section also, but seems like my js code is not picking up csrf token.
I would be very thankful if anyone could highlight the mistake I've made above.
Try using this:
{{ csrf_field() }} instead of #csrf
419 error is mostly because of CSRF token issues.
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>
I have a simple form with Ajax call, but ajax call gets executed even if form is not validated.
In below code line console.log("This line should execute only if Form is validated"); gets executed when form is not validate.
Bootstrap 5 validation Codepen code
(function () {
"use strict";
const forms = document.querySelectorAll(".requires-validation");
Array.from(forms).forEach(function (form) {
form.addEventListener(
"submit",
function (event) {
if (!form.checkValidity()) {
event.preventDefault();
event.stopPropagation();
}
else
{
console.log("This line should execute only if Form is validated");
// Call Ajax Function
// AjaxCallSaveData();
}
form.classList.add("was-validated");
},
false
);
});
})();
//$(document).ready(function () {
function AjaxCallSaveData()
{
$("form").submit(function (event) {
var formData = {
name: $("#name").val(),
email: $("#email").val(),
message: $("#message").val(),
superheroAlias: $("#superheroAlias").val()
};
$.ajax({
type: "POST",
url: "SubmitFORM.php",
data: formData,
dataType: "json",
encode: true
}).done(function (data) {
console.log(data);
});
event.preventDefault();
});
}
//});
Not sure if i am doing it right?
HTML
<div class="form-body">
<div class="row">
<div class="form-holder">
<div class="form-content">
<div class="form-items">
<h3>Register you interest</h3>
<p>Fill in the data below, we will get back to you!</p>
<form class="requires-validation" action="SubmitFORM.php" method="POST" novalidate>
<div class="col-md-12 mb-3">
<input class="form-control" type="text" name="name" id="name" placeholder="Full Name" required>
<div class="valid-feedback">Username field is valid!</div>
<div class="invalid-feedback">Username field cannot be blank!</div>
</div>
<div class="col-md-12 mb-3">
<input class="form-control" type="email" name="email" id="email" placeholder="E-mail Address" required>
<div class="valid-feedback">Email field is valid!</div>
<div class="invalid-feedback">Email field cannot be blank!</div>
</div>
<div class="col-md-12 mb-3">
<textarea name="message" id="message" placeholder="Your Message"></textarea>
</div>
<div class="form-button mt-3">
<button id="submit" type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
event.preventDefault() will only stop the form from submitting. It cannot stop next lines of the JavaScript function from executing.
You should use return in place of event.preventDefault().
When my login credentials are prefilled by my browser (chrome) my fetch function doesn't send the values
html
<div class='login-frame'>
<h3>Bienvenue</h3>
<div class='form'>
<div class='input-handler'>
<label for='login'>Login</label>
<input type='text' id='login' name='login' autocomplete='on'>
</div>
<br>
<div class='input-handler'>
<label for='pass'>Mot-de-passe</label>
<input type='password' id='pass' name='pass' autocomplete='on'>
</div>
<br>
<button id='loginbutton'>CONNEXION</button>
</div>
</div>
JS
window.onload = function() {
var pass = document.getElementById('pass'),
login = document.getElementById('login'),
loginButton = document.getElementById('loginbutton');
loginbutton.onclick = (e)=> {
var creds = {
login: login.value,
pass: pass.value
}
fetch('functions/log.php', {
method: "POST",
header: {"Content-type": "application/json; charset=UTF-8"},
body: JSON.stringify(creds)
});
}
PHP
$pos = json_decode(file_get_contents('php://input', true));
echo var_dump($pos);
If I type anything, it returns
object(stdClass)#3 (2) {
["login"]=>
string(3) "qfz"
["pass"]=>
string(5) "zfqzf"
}
If I use the browser prefill, it returns
NULL
It was a mistake,
as #CBroe said, it was a security problem. Changing my html to a proper form make it works as it should
<form class='login-frame' method='post' action='#'>
<div class='login-logo'><img src='bs/img/logo_b.svg'></div>
<h3>Bienvenue</h3>
<div class='form'>
<div class='input-handler'>
<label for='login'>Login</label>
<input type='text' id='login' name='login' autocomplete='on'>
</div>
<br>
<div class='input-handler'>
<label for='pass'>Mot-de-passe</label>
<input type='password' id='pass' name='pass' autocomplete='on'>
</div>
<br>
<button type='submit' id='loginbutton'>CONNEXION</button>
</div>
</form>
I have this search bar and I can't connect it to Google as a search functionality, I tried with this guy's code but I couldn't:
<form id="frmSearch" action="index.html" class="searchform order-sm-start order-lg-last">
<div class="form-group d-flex">
<input type="text" class="form-control pl-3" placeholder="Buscar">
<button type="submit" placeholder="txtsearch" class="form-control search"><span class="fa fa-search"></span></button>
</div>
</form>
Thanks in advance!
You could use an AJAX call to a php page where you are going to implement cURL to get data from google searching url!
Of course you will need to code your own cURL in PHP: PHP + curl, HTTP POST sample code?
here you can find how to implement it!
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
document.addEventListener('DOMContentLoaded', () => {
const form = document.querySelector("form#frmSearch");
form.onsubmit = function() {
let keyword = encodeURIComponent(this.querySelector("input#keyword").value);
$.ajax({
url: `./php_curl_file.php?q=${encodeURIComponent(keyword)}`,
type: 'GET',
error: (err) => {
throw new Error(err);
},
success: (searchData) => {
console.log( searchData );
}
});
return false;
}
} );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="frmSearch" class="searchform order-sm-start order-lg-last">
<div class="form-group d-flex">
<input type="text" id="keyword" class="form-control pl-3" placeholder="Buscar">
<button type="submit" placeholder="txtsearch" class="form-control search">
<span class="fa fa-search"></span> Search
</button>
</div>
</form>
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