Uncaught SyntaxError: Unexpected identifier using Submit Handler - javascript

I am Creating validation script and ajax call. I face the problem is that
alert message is not working in if condition
I can't figure out what's going on here, when I run the script, in Chrome it says:
Uncaught SyntaxError: Unexpected identifier
Below is my code :
$("#myCA-Form").validate({
rules:{
field1:"required",
city:"required",
email:{
required:true,
email:true
},
phone:{
required:true,
number: true,
minlength:9,
maxlength:10
}
},
messages:{
name:"Please enter your username..!",
email:"Please enter your email..!",
phone:"Enter your mobile no"
},
submitHandler: function(form) {
var formData = $(form).serialize();
var id = $('#product_id2').val();
var name = $('#field1').val();
$.ajax({
url: "https://eaxmple.co.in/test.aspx?"+formData,
type: "POST",
cache: false,
dataType: "jsonp",
crossDomain: true,
data: {formd : formData },
success: function(data) {
}
});
if(id=='100105')
{
alert("sdfsd");
document.getElementById("msg").innerHTML='submit Successfully!!!';
}
}
});

There is no problem in your code. its working perfectly. I hope the problem is somewhere other
This is the exact copy of your code, with added HTML code
$("#myCA-Form").validate({
rules:{
field1:"required",
city:"required",
email:{
required:true,
email:true
},
phone:{
required:true,
number: true,
minlength:9,
maxlength:10
}
},
messages:{
name:"Please enter your username..!",
email:"Please enter your email..!",
phone:"Enter your mobile no"
},
submitHandler: function(form) {
var formData = $(form).serialize();
var id = $('#product_id2').val();
var name = $('#field1').val();
$.ajax({
url: "https://eaxmple.co.in/test.aspx?"+formData,
type: "POST",
cache: false,
dataType: "jsonp",
crossDomain: true,
data: {formd : formData },
success: function(data) {
}
});
if(id=='11')
{
alert("sdfsd");
document.getElementById("msg").innerHTML='submit Successfully!!!';
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
<form id="myCA-Form">
<input name="field1" type="text"/>
<input name="city" type="text"/>
<input name="email" type="text"/>
<input name="phone" type="text"/>
<input value="11" id="product_id2" type="hidden"/>
<button class="save-post">Save Post</button>
</form>

You should not append formdata to the URL, if you want something like that you should be looking at GET method instead of POST. You might wanna read more about POST and GET.

Related

Trying to send files to the controller using Ajax and puglin Krajee file input in Laravel [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I am having trouble sending multiple data types to laravel controller using ajax,
can someone help me ?.
What do I need to work in the code below:
send the text inputs, including the pdf file, via ajax to the controller,
using the submit button instead of the krajee plugin button
I'm using:
AJAX,
JQUERY,
LARAVEL,
KRAJEE INPUT FILE PUGLIN https://plugins.krajee.com/file-input
My code is based on this:
Krajee file-input submit files on form submit
DD return from controller:
array:5 [
"_token" => "TfazfXdJuIIyNe59MNx8DfJJvCl7ePkj66jsW6Vl"
"cliente_titulo" => "teste name"
"cliente_data" => "2021/12"
"cliente_cliente" => "Test"
"cliente_condominio" => "Test"
]
CONTROLLER CODE FUNCTION:
public function create(Request $request){
dd($request->all());
}
HTML CODE :
<form method="POST" id="upload" enctype="multipart/form-data">
{{ csrf_field() }}
<input id="cliente_titulo" type="text" class="form-control" name="cliente_titulo" >
<input id="cliente_cliente" type='text' name="cliente_cliente" class="form-control
autocomplete="off" >
<input id="cliente_condominio" type="text" class="form-control" name="cliente_condominio">
<input id="cliente_pdf" name="cliente_pdf" type="file" class="file-loading"
enctype="multipart/form-data" data-allowed-file-extensions='["pdf"]' >
<button id="confirm-create" type="submit" class="btn btn-success" >CREATE</button>
</form>
JS CODE:
<script>
var formData = new FormData();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
$("#cliente_pdf").on('filebatchpreupload', function(event, data, previewId, index) {
var form = data.form, files = data.files, extra = data.extra,
response = data.response, reader = data.reader;
$.each(files, function (key, value) {
if(value != null){
formData.append("pdf", value, value.name);
}
});
});
$('#upload').submit(function() {
$('#cliente_pdf').fileinput({
language: "pt-BR",
allowedFileExtensions: 'pdf',
maxFileCount: 1,
});
var model_data = $("#upload").serializeArray();
$.each(model_data,function(key,input){
formData.append(input.name,input.value);
});
$.ajax({
url: "create",
type: "POST",
datatype: "json",
data: formData,
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
success: function (data){
console.log('certo');
},
error: function (data){
console.log('error');
}
});
return false;
});
</script>
ATTEMPTS:
HTML:
<form method="POST" id="upload_form" enctype="multipart/form-data">
<input id="cliente_titulo" type="text" class="form-control" name="cliente_titulo" >
<input id='cliente_data' type='text' class="form-control" name="cliente_data" autocomplete="off" >
<input id="cliente_cliente" type='text' id_cliente="" value="" name="cliente_cliente" class="form-control {{ url_ativa('visualizarLogin') }}" data-toggle="modal" data-target="#full-colored-cliente" autocomplete="off" >
<input id="cliente_condominio" type="text" class="form-control" name="cliente_condominio" >
<input id="cliente_pdf" name="pdf" type="file" enctype="multipart/form-data" data-allowed-file-extensions='["pdf"]' required>
<button id="confirm-create" type="submit" class="btn btn-success" style="display:none"><strong>CRIAR FLIPBOOK</strong><span class="glyphicon glyphicon-ok"></span></button>
</form>
JS:
$("#cliente_pdf").fileinput({
language: "pt-BR",
uploadUrl: "{{ url('create') }}",
uploadAsync: true,
allowedFileExtensions: 'pdf',
maxFileCount: 1,
showUpload: false,
purifyHtml: true,
uploadExtraData: function(){
return {
_token: $("input[name='_token']").val();
}
},
fileActionSettings: {
showUpload: false,
},
});
$('#upload_form').on('submit',function(e){
e.preventDefault();
var formData = new FormData($(this).get(0));
$.ajax({
method: 'POST',
url: 'create',
dataType: 'json',
cache: false,
processData: false,
contentType: false,
data:formData,
beforeSend: function(){
console.log('enviando');
},
success: function(data){
console.log('sucesso');
},
cache: false,
contentType: false,
processData: false,
error:function(){
console.log('erro');
}
});
});
CONTROLLER
use Illuminate\Http\Request;
class FlipbookController {
public function create(Request $request){
dd($request->file());
or
dd($request->all());
or
dd($request->files());
or
dd($request->file('pdf'));
}
}
o unico que obetive resultado foi o
dd($request->all());
DD return from controller:
array:5 [
"_token" => "TfazfXdJuIIyNe59MNx8DfJJvCl7ePkj66jsW6Vl"
"cliente_titulo" => "teste name"
"cliente_data" => "2021/12"
"cliente_cliente" => "Test"
"cliente_condominio" => "Test"
]
I can't get the uploaded file
Where am i going wrong
You get your file object under the request files method.
$request->files(); or $request->file();
For Krajee Request look like below
$("#file-1").fileinput({
theme: 'fa',
uploadUrl: '{{ url }}',
showUpload: true,
uploadAsync: false,
uploadExtraData: function () {
return {
_token: $("input[name='_token']").val()
};
},
maxFileSize: 3000000,
});

Invisible google captcha v2 is not working properly

The following code is working fine when the form is submitted correctly with all valid data in the first attempt. If there is any server side error after submitting the form then when user resubmits the form the recaptcha does not reset.
Following is the sample code:
html-form
<script src="https://www.google.com/recaptcha/api.js"></script>
<div>
<form name="signupForm" method="POST" action="/signup">
<div class="form-group mobile-number">
<input type="tel" id="mobileNo" class="form-control" name="mobileNumber" maxlength="10"
autofocus>
<label for="mobile"> Your Mobile no. </label>
</div>
<div class="g-recaptcha"
data-sitekey="{key}"
data-callback="setResponse"
data-badge="inline"
data-size="invisible">
</div>
<input type="hidden" id="captcha-response" name="captcha-response"/>
<button id="submitButon" type="submit">Sign me up!</button>
</form>
</div>
javascript
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
function setResponse(response) {
document.getElementById('captcha-response').value = response;
submitForm();
}
function submitForm() {
var $form = $("form");
var data = JSON.stringify($form.serializeObject());
var myJsonObject = JSON.parse(data);
data = JSON.stringify(myJsonObject);
$.ajax({
type: "POST",
url: "dummy url",
contentType: "application/json",
xhrFields: {withCredentials: true},
data: data,
success: function (data, textStatus, request) {
// success
},
error: function (xhr, err) {
// logics here
grecaptcha.execute();
setResponse;
}
});
}
</script>
<script>
jQuery(document).ready(function () {
//homepage form
$('form[name="signupForm"]').validate({
onfocusout: function (element) {
$(element).valid();
},
rules: {
mobileNumber: {
required: true,
minlength: 10,
maxlength: 10
}
},
// Specify validation error messages
messages: {
mobileNumber: "A valid mobile number is of 10-digit",
},
//submit handler
submitHandler: function (form) {
submitForm();
}
});
});
</script>
I think the error is in ajax call but not able to figure out why the captcha is not resetting again.

How to Add ajax form processing for html mail form

I currently finished creating ( modify a themeforest template ) a website and all i need to do now is to set up contact form to receive mail from my customers
/* *****************************************************************
* FORM VALIDATION
* ************************************************************** */
$("#contactForm").validate({
rules: {
fullname: {
required: true
},
email: {
required: true,
email: true
},
message: {
required: true
}
},
messages: {
fullname: {
required: "Please enter your name"
},
email: "Please enter a valid email address",
message: "Please enter your message"
},
submitHandler: function () {
// Add your ajax form processing here.
}
});
This is the code form config.js file. How do i set up with my mail ( contact#website.com )
$.ajax({type:'POST', url: 'contact.php', data:$('#contactForm').serialize(), success: function(response) { $('#contactForm').find('.form-control').html(response);}});
this is the final syntax that works perfectly
try this
var data = new FormData($("#contactForm")[0]);
$.ajax({
url : 'your url ',
type : 'post',
data : data,
mimeType : 'multipart/form-data'
contentType: false,
processData: false,
success: function(data){
}
});

change subject of formspree with ajax

I'm using formspree within an angular app. Everything is working except I can't seem to change the subject of the email.
Html...
<form id="bookingForm" action="https://formspree.io/your#email.com"
method="POST">
<input type="text" name="{{client.name}}">
<input type="{{client.email}}" name="_replyto">
<input type="hidden" name="_subject" value="Request from {{client.name}}">
<!-- some other info -->
<input type="submit" value="Send">
</form>
JS...
$bookingForm = $('#bookingForm');
$bookingForm.submit(function(e) {
e.preventDefault();
$.ajax({
url: '//formspree.io/your#email.com',
method: 'POST',
data: {
client: $scope.client.name,
email: $scope.client.email,
phone: $scope.client.phone,
// some other info
},
dataType: 'json',
});
});
The _replyto seems to be working but _subject is not.
Add '_subject' to your post request and remove the name attribute from the subject input field:
$bookingForm = $('#bookingForm');
$bookingForm.submit(function(e) {
e.preventDefault();
$.ajax({
url: '//formspree.io/your#email.com',
method: 'POST',
data: {
client: $scope.client.name,
email: $scope.client.email,
phone: $scope.client.phone,
_subject: "Text here"
},
dataType: 'json',
});
});

Form Validation with Success

When I submit the form without filling in any information it quickly displays the error message then fades. I only want the form to fade if there's no error messages and the validation is successful. I think I may need to use an if statement for success or something to do with a submit handler?
So far I have this - https://jsfiddle.net/wnmLmcm8/
$(document).ready(function () {
$("form").submit(function (e) {
e.preventDefault();
$.ajax({
type: this.method,
url: this.action,
data: {
name: $('#name').val(),
email: $('#email').val()
},
success: function () {
$('#emailform').fadeOut("slow");
}
});
});
$("form").validate({
rules: {
email: {
required: true,
email: true,
remote: "http://localhost:3000/inputValidator"
}
}
});
});
Here is a working version of your jsFiddle: https://jsfiddle.net/ywhpdLen/3/
This snippet works, based off of your jsFiddle, but your jsFiddle does not work. I had to pull the code into my own dev environment, locally.
The popup stays until you click in the text field.
Adding "required" to the input elements & using the default ".validate()" extension does the job. If you're looking to customize it, I'd highly recommend looking at https://jqueryvalidation.org/documentation/
<div id="emailform">
<form method="post" action="form.php">
<hr>
<label for="name">Name</label>
<br>
<input type="text" name="name" id="name" class="NewsLetter1" required/>
<br>
<label for="email">Email</label>
<br>
<input type="text" name="email" id="email" class="NewsLetter2" required/>
<input type="submit" value="Submit">
<hr>
</form>
</div>
<script>
$(document).ready(function () {
$("form").submit(function (e) {
e.preventDefault();
$.ajax({
type: this.method,
url: this.action,
data: {
name: $('#name').val(),
email: $('#email').val()
},
success: function () {
$('#emailform').fadeOut("slow");
},
failure: function (ex) {
}
});
});
$("form").validate();
});
</script>
Per comments, below: It looks like your ajax call is still happening and form.submit() is firing off. You may want to remove your form.submit() call and include it in the validate call, like so.
$("form").validate({
submitHandler:function(form){
$.ajax({....})
}
});
Do it with submit handler like...
$(document).ready(function ()
{
$("form#sub_form").validate({
rules: {
UserName: "required",
Useremail: {
required: true,
email: true
},
Userpwd:{
required: true,
minlength:8
},
Con_Userpwd:{
required:true,
equalTo:"#reg-pass"
},
contact:{
required:true,
minlength:10
}
},
messages: {
UserName: "Please specify your name",
Useremail: {
required: "We need your email address to contact you",
email: "Your email address must be in the format of name#domain.com"
},
Userpwd:{
required: "Enter Your Password",
minlength:"Please Enter minimum 8 digit password"
},
Con_Userpwd: {
required:"Please re-enter your password",
equalTo:"Password not matched"
},
contact:{
required:"Phone Number Required",
minlength:"Minimum 10 Digits Required"
}
},
submitHandler: function(form) {
var msg = $("form#sub_form").serialize();
$.ajax({
type: "POST",
url: "register_checkout.php",
data: msg,
success: function (html) {
$(".popup").delay(5000).fadeOut(1500);
setTimeout(function(){window.location='one-page-checkout.php'},3000);
//return false;
}
else
{
$("#reg_message").slideUp();
$("#reg_message").slideDown().html(html);
}
}
}
);
Try putting your ajax into submitHandler of validation plugin
$("form").validate({
rules: {
email: {
required: true,
email: true,
remote: "http://localhost:3000/inputValidator"
}
},
submitHandler:function(form){
$.ajax({....})
}
});
When running into problems use debug:true
for instant solution use "required" https://jsfiddle.net/et7qcrye/
<input type="text" name="name" id="name" class="NewsLetter1" required/>

Categories