JQuery serialize ajax loaded form - javascript

The serialize() function returns an empty string , This is my code :
Code to return form :
$.ajax({
url: 'api/form',
type: 'get',
crossDomain: true,
}).done(function(response){
fields = JSON.parse(response);
html = '';
$.each(fields, function(index,field){
html += field;
});
html += '<div class="btn-clear"></div><button class="btn payment">Pay</button></div>';
$("#cart-content").html(html);
}).fail(function() {
console.log('Failed');
});
Javascript code executed after user clicks payment button :
$("body").on('click','.payment',function() {
var frmData = $("#customer").serialize();
console.log(frmData);
});
But it log an empty string !!
The form after it's ajax loaded :
<form id="customer"><div class="form-group">
<label class="control-label">Full name</label>
<input name="name" class="form-control" type="text">
</div><div class="form-group">
<label class="control-label">E-mail</label>
<input name="email" class="form-control" type="text">
</div><div class="form-group">
<label class="control-label">Mobile</label>
<input name="mobile" class="form-control" type="text">
</div><div class="form-group">
<label class="control-label">Country</label>
<select id="country" name="country" class="form-control" type="text"><!-- countries ... --></select>
</div></form>

Try your serialize like this
$("#form").submit(function () {
var data = $('#form').serialize();
Use the form ID as the target. Here I used #form. Submit the form, serialize the forms inputs.

Related

PHP is not returning data to AJAX

I'm testing a login form that submits data via Ajax to the PHP processing file. Once I click the submit button it just redirects me to PHP file and not returning data from PHP. The form is inside a bootstrap modal. I'm just new to jquery and ajax so I hope someone helps. Thanks
HTML
<form action="login-process.php" id="test-form" method="post">
<div class="form-group">
<input type="hidden" name="login-form">
<input type="email" class="form-control form-control-lg" name="login-email" id="loginEmail" placeholder="Email address" required>
</div>
<div class="form-group">
<input type="password" class="form-control form-control-lg" name="login-pass" id="loginPassword" placeholder="Password" required>
</div>
<button type="submit" class="btn btn-lg btn-block btn-primary mb-4">Sign in</button>
</form>
JQuery script is placed at site footer after jquery.js cdn
$(document).ready(function(){
// Process form
$('#test-form').submit(function(event){
// get form data
var formData = {
'email' : $('input[name=login-email]').val(),
'password' : $('input[name=login-pass]').val();
};
// process the form
$.ajax({
type : 'POST', // define the HTTP method we want to use
url : 'process.php', // url to send data
data : formData, // data object
dataType : 'json', // what type of data to expect back from server
encode : true
})
// using done promise call back
.done(function(data){
// log data to console
console.log(data);
if (data.email-msg) {
alert("success");
}
});
// stop the form from submitting and refresing the page
event.preventDefault();
});
});
process.php
<?php
$data = array(); // array to hold pass back data
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$email = $_POST['login-email'];
$password = $_POST['login-pass'];
$data['email-msg'] = $email;
$data['pw-msg'] = $password;
echo json_encode($data);
} ?>
try this brother
$(document).ready(function(){
$('#test-form').on('submit', function(event){
event.preventDefault();
$.ajax({
url:"action="login-process.php" ",
method:"POST",
data:$(this).serialize(),
success:function(data){
console.log("data send");
}
})
});
});
<form id="test-form" method="post">
<div class="form-group">
<input type="hidden" name="login-form">
<input type="email" class="form-control form-control-lg" name="login-email" id="loginEmail" placeholder="Email address" required>
</div>
<div class="form-group">
<input type="password" class="form-control form-control-lg" name="login-pass" id="loginPassword" placeholder="Password" required>
</div>
<button type="submit" class="btn btn-lg btn-block btn-primary mb-4">Sign in</button>
</form>
You Have syntax error in javascript code.
change your code
var formData = {
'email' : $('input[name=login-email]').val(),
'password' : $('input[name=login-pass]').val();
};
to
var formData = {
'email' : $('input[name=login-email]').val(),
'password' : $('input[name=login-pass]').val()
};
It will solve the problem

Dropzone js validate on submit

I have a form where I am using dropzone.js for file upload. Now I am validating all the input fields. But i'm not able to validate the file before submission. If the file is uploaded, then the submission should work. Otherwise it should throw an error like - "please upload the file". How can i achieve this?
HTML code:
<form action="/action">
<div class="form-row">
<div class="form-group col-md-6">
<input type="text" class="form-control" id="first_name" name="first_name" placeholder="First Name" required>
</div>
<div class="form-group col-md-6">
<input type="text" class="form-control" id="last_name" name="last_name" placeholder="Last Name" required>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-12">
<textarea class="form-control" id="message" name="message" placeholder="Message"></textarea>
</div>
</div>
<div class="form-row">
<div id="resume" class="dropzone form-control"></div>
</div>
<input type="submit" class="btn btn-primary mt-10" id="item-submit" value="submit">
</form>
Javascript :
<script type="text/javascript">
$(document).ready(function () {
$("div#resume").dropzone({ url: "/change-this-later" });
var dropzone3;
Dropzone.autoDiscover = false;
dropzone3 = new Dropzone('#resume', {
maxFiles: 1,
});
$('#item-submit').click(function(e) {
e.preventDefault();
e.stopPropagation();
if ($('form#resume').valid()) {};
});
});
</script>
You can add a callback event which is called if the upload is successful
//indicates file upload is complete and is successful
var uploaded = false;
$("div#resume").dropzone({
url: "/change-this-later",
success: function (file, response) {
uploaded = true;
}
});
//Check the value of 'uploaded' when validating rest of fields
So I come around this. Since I submit all my images and fields in the same button, I just acceded to the files array in side the dropzone and validate that it's lenght wasn't 0. $animalImage is my dropzone.
var validateImages = function (animal) {
if ($animalImage.files.length == 0) {
swal({
title: 'Advertencia',
type: 'info',
html: "Debe de guardar al menos una imágen",
showCloseButton: true,
focusConfirm: false
});
return false;
}
return animal;
};
Hope it helps, side note a submit trough ajax so I just used dropzone for the user experience.

Select Option in AngularJS returning object not value

I'm still learning AngularJS, so im not quite sure as to the best way to implement this;
I'd be fine with doing this in ordinary HTML, but wasn't able to use the "selected" property, so i switched to an Angular element - which im new to using.
I have a form, with a Drop down box, where the user selects either "User" or "Administrator". A User has the value of "2", where Administrator has the value of "1".
By default, 'User' is the pre-selected item in the list.
My problem is, when the form is being submitted (via AJAX) to PHP, the form is submitting an Object like {value : "2", name : "User"} where i want it to just submit the value, ie: "2".
HTML code:
<div class="form-group col-md-6">
<label for="usrlevel">User Level:</label>
<select class="form-control form-control-sm"
data-ng-init="formData.usrlevel = usrlevels[0]"
data-ng-model="formData.usrlevel"
data-ng-options="x.name for x in usrlevels">
</select>
</div>
Javascript Code:
app.controller("admController", function ($scope, $http, $location) {
$scope.usrlevels = [
{value : "2", name : "User"},
{value : "1", name : "Administrator"}
];
$scope.addForm = function() {
var ans="";
$http({
method : 'POST',
url : 'php/addstaff.php',
data : $.param($scope.formData),
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } //set the headers so angular passing info as form data (not request payload)
}).then(function (response) {
console.log(response.data);
ans = response.data;
if (!ans.success) {
// Add Error handling
} else {
$('#addModal').modal('hide');
$scope.getStaff(); //refreshes table display
}
}).catch(function(response){
console.log(response.data);
});
};
And here's an image of the debugger, showing that for 'usrlevel' the form is submitting an object, when it should just be submitting the value of the selected item.
Thus, in the debugger, it should just be showing usrlevel:"2"
UPDATE:
As people seem to be under the impression that only the userlevel should be submitted by the AJAX call (I thought the debugger window image would make it clear that the userlevel is 1 element in the form) here's the actual HTML form.
<form data-ng-submit="addForm()" name="addform" method="POST">
<div class="form-group">
<label for="name">Full Name:</label>
<input type="text" class="form-control form-control-sm" name="name" data-ng-model="formData.name" id="name" placeholder="">
</div>
<div class="form-group">
<label for="address">Address:</label>
<input type="text" class="form-control form-control-sm" name="address" data-ng-model="formData.address" id="address" placeholder="">
</div>
<div class="form-group">
<label for="suburb">Suburb:</label>
<input type="text" class="form-control form-control-sm" name="suburb" data-ng-model="formData.suburb" id="suburb" placeholder="">
</div>
<div class="form-group">
<label for="phone">Phone:</label>
<input type="tel" class="form-control form-control-sm" name="phone" data-ng-model="formData.phone" id="phone" placeholder="">
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="postcode">Post Code:</label>
<input type="text" class="form-control form-control-sm" name="postcode" data-ng-model="formData.postcode" id="postcode" placeholder="">
</div>
<div class="form-group col-md-6">
<label for="usrlevel">User Level:</label>
<select class="form-control form-control-sm" data-ng-init="formData.usrlevel = usrlevels[0]" data-ng-model="formData.usrlevel" data-ng-options="x.name for x in usrlevels"></select>
</div>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control form-control-sm" name="email" data-ng-model="formData.email" id="email" placeholder="">
</div>
<div class="form-group">
<label for="suburb">Password:</label>
<input type="password" class="form-control form-control-sm" name="password" data-ng-model="formData.password" id="password" placeholder="">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
<button type="reset" value="Reset" class="btn btn-secondry">Clear</button>
You are asking why u get whole object on select and not only value selected.
This is because you used
data-ng-options="x.name for x in usrlevels"
Which will set X to model on select, if you want only name/any other attr of x to be set to model you need to use
data-ng-options="x.value as x.name for x in usrlevels" data-ng-model="formData.value"
As tell angular select x show it as y.
to make default selection work
now you need to update $score.formData.value with value of selected user object.
so forexample in ur controller
app.controller("admController", function ($scope, $http, $location) {
$scope.usrlevels = [
{value : "2", name : "User"},
{value : "1", name : "Administrator"}
];
$scope.formData = { value: "1"} // prepare formData and set user with value 1 (Admin) to be selected by default
finally send whole formData.
http({
method : 'POST',
url : 'php/addstaff.php',
data : $scope.formData,
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } //set the headers so angular passing info as form data (not request payload)
}).then(function (response) {
...etc
Again pass only wt u need to data of ajax, dont pass whole object!
Problem is with your model. Well, an easy to understand syntax would look like this
angular.module("app",[]).controller('ctrl', function($scope){
$scope.users= [{value : "2", name : "User"},{value : "1", name : "Admin"}]
$scope.user = "2";
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl" >
<select ng-model="user">
<option ng-repeat="i in users" value="{{i.value}}">{{i.name}}</option>
</select>
Value is : {{user}}
</div>
And now you can use $scope.user as selected value to send wherever you want.
To send it as payload to your request, you can use something like
..
data : {"userLevel" :$scope.user },
..
Use the as clause in ng-options:
<div class="form-group col-md-6">
<label for="usrlevel">User Level:</label>
<select class="form-control form-control-sm"
̶d̶a̶t̶a̶-̶n̶g̶-̶i̶n̶i̶t̶=̶"̶f̶o̶r̶m̶D̶a̶t̶a̶.̶u̶s̶r̶l̶e̶v̶e̶l̶ ̶=̶ ̶u̶s̶r̶l̶e̶v̶e̶l̶s̶[̶0̶]̶"̶
data-ng-model="formData.usrlevel"
̶d̶a̶t̶a̶-̶n̶g̶-̶o̶p̶t̶i̶o̶n̶s̶=̶"̶x̶.̶n̶a̶m̶e̶ ̶f̶o̶r̶ ̶x̶ ̶i̶n̶ ̶u̶s̶r̶l̶e̶v̶e̶l̶s̶"̶>̶
data-ng-options="x.value as x.name for x in usrlevels">
</select>
</div>
Also the initial value of the ng-model should be set to a primitive instead of an object:
$scope.formData.usrlevel = $scope.usrlevels[0].value;
It is better to POST data as application/json, but if your backend only supports application/x-www-form-urlencoded, use the AngularJS built-in param serializer:
$scope.addForm = function() {
var ans="";
$http({
method : 'POST',
url : 'php/addstaff.php',
̶d̶a̶t̶a̶ ̶ ̶ ̶ ̶:̶ ̶$̶.̶p̶a̶r̶a̶m̶(̶$̶s̶c̶o̶p̶e̶.̶f̶o̶r̶m̶D̶a̶t̶a̶)̶,̶
data : $scope.formData,
transformRequest: $httpParamSerializerJQLike,
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } //set the headers so angular passing info as form data (not request payload)
})
As others had mentioned, there was a problem with ng-options which is why it returned an object and not just the value.
But then, after changing ng-options it no longer had 'User' as the default selected item in the drop down - and this was then a problem with ng-init.
Old HTML
<select class="form-control form-control-sm"
data-ng-init="formData.usrlevel = usrlevels[0]"
data-ng-model="formData.usrlevel"
data-ng-options="x.name for x in usrlevels">
</select>
New HTML
<select class="form-control form-control-sm"
data-ng-model="formData.usrlevel"
data-ng-init="formData.usrlevel = formData.usrlevel || usrlevels[0].value"
data-ng-options="x.value as x.name for x in usrlevels">
</select>

Avoid Refreshing page submiting the form

Whenever using this form that I made (in Portuguese), refreshing removes all previously entered data from the page. Why does this happen, and how can I fix it? Thank you for your time.
<script type="text/javascript">
function submitForm(){
// Initiate Variables With Form Content
var nome = $("#nome").val();
var email = $("#email").val();
var telefone = $("#telefone").val();
var assunto = $("#assunto").val();
var mensagem = $("#mensagem").val();
$.ajax({
type: "POST",
url: "send-contact2.php",
data: "nome=" + nome + "&email=" + email + "&telefone=" + telefone + "&assunto=" + assunto + "&mensagem=" + mensagem,
cache:false,
success: function (data) {
alert(data);
}
});
}
</script>
<form id="myForm">
<div class="col col-md-6">
<input type="text" name="nome" id="nome" required value="" tabindex="1" placeholder="Nome">
<input type="text" name="email" id="email" required value="" tabindex="2" placeholder="E-mail">
<input type="text" name="telefone" id="telefone" required value="" tabindex="2" placeholder="Telefone">
<select id="assunto" name="assunto" required>
<option value="outros">Outros assuntos</option>
<option value="encomendas">Encomendas</option>
</select>
</div>
<div class="col col-md-6">
<textarea name="mensagem" id="mensagem" cols="29" rows="8" placeholder="Mensagem"></textarea>
</div>
<div class="col col-md-12 ">
<button name ="submit" type="submit" onclick="return submitForm();">Enviar</button>
</div>
</form>
Your function also needs to return false to stop the click event behaviour from submitting the form:
function submitForm(){
// your code...
return false;
}
Better still, hook to the submit event of the form directly and do away with the clunky onclick handlers, and use serialize() to gather the form data for you:
<button name="submit" type="submit">Enviar</button>
<script type="text/javascript">
$(function() {
$('#myForm').submit(function(e) {
e.preventDefault(); // stop form submission
$.ajax({
type: "POST",
url: "send-contact2.php",
data: $(this).serialize(),
cache: false,
success: function (data) {
alert(data);
}
});
}
});
</script>
Try to change onClick action to onSubmit and add return false after method. Like this:
<button name ="submit" type="submit" onsubmit="submitForm(); return false;">Enviar</button>
Good practice will be add method="POST" to your form attributes.

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