I'm having a hard time sending a form using POST as well as JS. The reason for this setup is sending a form to DotMailer emailing program as well as Magento through AWS at the same time, with both having different means of sending. I'm thinking it gets sent to AWS before it actually has a chance to POST?
The data is JSON-ified before being sent to AWS which i presume would be an issue for POST for the mailing program?
Help will be much appreciated!
The code form code:
<form name="signup" id="signup" action="https://example.com/signup.ashx" method="post" autocomplete="off" class="redeye-form loyalty-form" onsubmit="return validate_signup(this, true)" data-form-id="loyalty-form">
<input type="hidden" name="ci_isconsentform" value="true">
<input type="hidden" name="userid" value="230531">
<input type="hidden" name="SIGb7f7109acfe72442f3b9937c47f1c0e7a78f60e9bec1ba7a7084e947eebceef2" value="">
<input type="hidden" name="addressbookid" value="574883" />
<input type="hidden" name="ReturnURL" value="">
<input type="hidden" id="ci_consenturl" name="ci_consenturl" value="">
<div>
<label class="wrap" for="FIRSTNAME">Imię: <span class="requiredfield">*</span></label>
<input name="cd_FIRSTNAME" id="FIRSTNAME" type="text" data-parameter="firstname" class="text regex" placeholder="" data-regex="^.{1,}$" data-regex-message="Wpisz poprawne imie (przynajmniej jeden znak)"aria-required="false" />
</div>
<div>
<label class="wrap" for="LASTNAME">Nazwisko: <span class="requiredfield">*</span></label>
<input name="cd_LASTNAME" id="LASTNAME" type="text" data-parameter="lastname" class="text regex" placeholder="" data-parameter="lastname"aria-required="false" />
</div>
<div>
<label class="wrap" for="POSTCODE">Kod pocztowy:</label>
<input type="text" class="text regex" name="cd_POSTCODE" id="POSTCODE" aria-required="false" />
</div>
<div>
<label class="wrap" for="email">Adres e-mail: <span class="requiredfield">*</span></label>
<input type="text" name="email" id="email" required aria-required="true" data-parameter="email" class="text regex">
</div>
<div class="newsletter text">
<p>
<input type="checkbox" name="ci_userConsentCheckBox" id="ci_userConsentCheckBox" data-parameter="doubleoptin" value="c">Consent text 1</p>
<input type="checkbox" name="sprawdzanko" id="sprawdzanko" value="1"><span>Consent text 2</span>
<p>Consent text 3</p>
<p>Kliknięcie w przycisk "Wyślij" znajdujący się poniżej oznacza akceptację Regulaminu.</p>
</div>
<input type="submit" class="c-btn c-btn--secondary" onmousedown="doSubmitEvents();" name="btnsubmit" id="btnsubmit" value="Wyślij" disabled> <p><span class="requiredfield">*</span>Wymagane pola</p>
</form>
The sending JS:
<script>
jQuery( document ).ready(function() {
const storeCode = "rg_pl";
var site = {
"url" : "https://reporting.example.com",
"id" : "14555",
"notify" : "examplesingleoptinwelcome"
};
var form = document.getElementsByTagName("form")[0];
var loyaltyForm = form.classList.contains('loyalty-form') == true;
jQuery("form.redeye-form .c-btn--secondary").click(function(e) {
e.preventDefault();
jQuery('.popup').remove();
var validityErrors = 0;
jQuery("input.required").each(function( index ) {
jQuery(this).removeClass("invalid");
if (!jQuery(this).val()) {
jQuery(this).after("<div class='popup'>Please enter something here</div>");
setTimeout(function() {
jQuery('.popup').remove();
}, 7000);
jQuery(this).addClass("invalid");
validityErrors++;
}
});
jQuery("select.required").each(function( index ) {
jQuery(this).removeClass("invalid");
if (!jQuery(this).val()) {
jQuery(this).after("<div class='popup'>Please enter something here</div>");
setTimeout(function() {
jQuery('.popup').remove();
}, 7000);
jQuery(this).addClass("invalid");
validityErrors++;
}
});
jQuery("input.regex").each(function( index ) {
jQuery(this).removeClass("invalid");
var patt = new RegExp(jQuery(this).data("regex"));
var result = patt.test(jQuery(this).val());
if (result !== true) {
var message = jQuery(this).data("regex-message");
jQuery(this).after("<div class='popup'>" + message + "</div>");
setTimeout(function() {
jQuery('.popup').remove();
}, 7000);
jQuery(this).addClass("invalid");
validityErrors++;
}
});
if (validityErrors == 0) {
var result = {};
var location = (window.location != window.parent.location)
? document.referrer
: document.location.href;
result["form-location"] = location;
var url = site.url + "/cgi-bin/rr/blank.gif";
var formTitle = jQuery("form.redeye-form").data("form-id");
result["subject"] = formTitle;
url = url.concat("?nourl=" + encodeURI(formTitle));
url = url.concat("&" + encodeURI(formTitle) + "=" + encodeURI(formTitle));
jQuery("form.redeye-form input").each(function( index ) {
if ( jQuery(this).is("input:text") ){
var parameter = jQuery(this).data("parameter");
var value = jQuery(this).val();
}
if ( jQuery(this).is("input:checkbox") ){
var parameter = jQuery(this).data("parameter");
var value = jQuery(this).is(':checked');
}
if ( jQuery(this).is("input:hidden") ){
var parameter = jQuery(this).data("parameter");
var value = jQuery(this).val();
}
result[parameter] = value;
url = url.concat("&" + encodeURI(parameter) + "=" + encodeURI(value));
});
jQuery("form.redeye-form select").each(function( index ) {
var parameter = jQuery(this).data("parameter");
var value = jQuery(this).val();
url = url.concat("&" + encodeURI(parameter) + "=" + encodeURI(value));
});
if (jQuery("input[data-parameter='doubleoptin']").is(":checked") == true) {
url = url.concat('¬ify=' + site.notify);
url = url.concat("&emailpermit=" + "yes");
url = url.concat("&newsletter=" + site.id);
} else {
url = url.concat("&emailpermit=" + "no");
url = url.concat("&newsletter=" + site.id);
}
url = url.concat("&domain_id=" + site.id);
var date = new Date();
result["date"] = date.getFullYear() + '-' + ('0' + date.getDate()).slice(-2) + '-'
+ ('0' + (date.getMonth()+1)).slice(-2);
result["url"] = window.location.href;
result["storeCode"] = storeCode;
var redEyeForm = jQuery( "form.redeye-form" );
redEyeForm.replaceWith( "<div class='successmessage'>Dziękujemy za wysłanie formularza</div>" );
// if (result["doubleoptin"] == "c") {
// result["doubleoptin"] = 1;
// } else {
// result["doubleoptin"] = 0;
// }
if (loyaltyForm == true){
console.log(result);
jQuery.ajax({
type: "POST",
url: 'https://example.execute-api.eu-west-1.amazonaws.com/Deployment',
contentType: 'application/json',
data: JSON.stringify(result),
success: function(res){
redEyeForm.replaceWith( "<div class='successmessage'>Dziękujemy za wysłanie formularza</div>" );
},
error: function(){
redEyeForm.replaceWith( "<div class='successmessage'>Wystąpił błąd</div>" );
}
});
}
}
});
});
</script>
EDIT: Could this accomplish what I need?
if (loyaltyForm == true){
console.log(result);
jQuery.ajax({
type: "POST",
url: 'https://h3uxa21uxf.execute-api.eu-west-1.amazonaws.com/Deployment',
contentType: 'application/json',
data: JSON.stringify(result),
success: function(res){
var $form = $(#signup);
$.ajax({
type : "POST",
cache : false,
url : $form.attr('action'),
data : $form.serializeArray(),
success : function(data) {
redEyeForm.replaceWith( "<div class='successmessage'>Dziękujemy za wysłanie formularza</div>" );
},
});
}
error: function(){
redEyeForm.replaceWith( "<div class='successmessage'>Wystąpił błąd</div>" );
}
});
}
}
});
});
I have a couple of examples you can build on.
Option 1 - You can submit to URL 1 via ajax and then submit the form as if user has clicked the button to URL 2.
Option 2 - Submit to URL 1 and then on success - submit to URL 2 - both via AJAX
// Option 1 - Ajax to submit first and then conduct default submit action for form
function ajaxAndSubmit(e){
e.preventDefault(); // Stop the default action of the submit button
var formData = $('#sample-form').serialize(); // Serialize the data
// Start ajax 1
$.ajax( {
type: "POST",
url: 'some url',
data: formData,
success: function( response ) {
console.log( response );
//Mimic default action
$('#sample-form').submit();
}
} );
}
// Option 2 - handle both in ajax
function ajaxAndSubmitWithAjax(e){
e.preventDefault(); // Stop the default action of the submit button
var formData = $('#sample-form').serialize(); // Serialize the data
// Start ajax 1
$.ajax( {
type: "POST",
url: 'some url',
data: formData,
success: function( response ) {
console.log( response );
// Submit via ajax
$.get('some-url.php?' + $('#sample-form').serialize()); // Using GET
$.post('some-url.php', $('#sample-form').serialize()); // Using POST
}
} );
}
Related
im new at this so i couldnt work this out with required fields on script.
html form
<form name="rezform" onsubmit="return validation()" id="loginForm" method="" action="" novalidate="novalidate">
javascript
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
function insertData() {
var rez_ad = $("#rez_ad").val();
var rez_saat = $("#rez_saat").val();
var rez_gsm = $("#rez_gsm").val();
var rez_tarih = $("#rez_tarih").val();
var rez_email = $("#rez_email").val();
var rez_tip = $("select#rez_tip").val();
var rez_sayi = $("select#rez_sayi").val();
var rez_aciklama = $("#rez_aciklama").val();
// AJAX code to send data to php file.
$.ajax({
type: "POST",
url: "rez/insert-data.php",
data: {
rez_ad: rez_ad,
rez_saat: rez_saat,
rez_gsm: rez_gsm,
rez_email: rez_email,
rez_tarih: rez_tarih,
rez_tip: rez_tip,
rez_sayi: rez_sayi,
rez_aciklama: rez_aciklama
},
dataType: "JSON",
success: function(data) {
$("#message").html(data);
$("#message").addClass("alert alert-success");
},
error: function(err) {
alert(err);
}
});
}
</script>
insert-data.php
/*
Developer: Ehtesham Mehmood
Site: PHPCodify.com
Script: Insert Data in PHP using jQuery AJAX without Page Refresh
File: Insert-Data.php
*/
include('db.php');
$rez_ad=$_POST['rez_ad'];
$rez_saat=$_POST['rez_saat'];
$rez_gsm=$_POST['rez_gsm'];
$rez_email=$_POST['rez_email'];
$rez_tarih=$_POST['rez_tarih'];
$rez_tip=$_POST['rez_tip'];
$rez_sayi=$_POST['rez_sayi'];
$rez_aciklama=$_POST['rez_aciklama'];
$stmt = $DBcon->prepare("INSERT INTO rezervasyon(rez_ad,rez_saat,rez_gsm,rez_email,rez_tarih,rez_tip,rez_sayi,rez_aciklama) VALUES(:rez_ad, :rez_saat,:rez_gsm,:rez_email,:rez_tarih,:rez_tip,:rez_sayi,:rez_aciklama)");
$stmt->bindparam(':rez_ad', $rez_ad);
$stmt->bindparam(':rez_saat', $rez_saat);
$stmt->bindparam(':rez_gsm', $rez_gsm);
$stmt->bindparam(':rez_email', $rez_email);
$stmt->bindparam(':rez_tarih', $rez_tarih);
$stmt->bindparam(':rez_tip', $rez_tip);
$stmt->bindparam(':rez_sayi', $rez_sayi);
$stmt->bindparam(':rez_aciklama', $rez_aciklama);
if($stmt->execute())
{
$res="Rezervasyonunuz tarafımıza ulaşmıştır. En yakın sürede girmiş olduğunuz GSM numaranıza dönüş yapılacaktır.";
echo json_encode($res);
}
else {
$error="Sistemsel bir hata meydana geldi lütfen bir süre sonra tekrar deneyiniz veya iletişime geçiniz.";
echo json_encode($error);
}
?>
So my problem is when i click my send button on html/php data is going mysql even if the inputs and select boxes are empty/not selected. So I have to do it required like in html input or select box. I dont know how to do it properly in javascript. I have found another script but couldnt work it same as like this one. So how can i put required field on this one and if you can explain it the logic it would be nice !
Also do we have a trick for bot protection on javascript form ?
Thanks !
And have a nice day.
You can do something like create a validation function for check whether input fields are empty or not.
function validation() {
submit = true;
var rez_ad = $("#rez_ad").val();
if ( rez_ad.trim() == "" ) {
//Do what ever you like with when empty submission.
alert('Input is empty.');
submit = false;
}
return submit;
}
Then in form on submit return this function.
<form action="" onsubmit="return validation()" method="POST">
function insertData() {
var rez_ad=$("#rez_ad").val();
var rez_saat=$("#rez_saat").val();
var rez_gsm=$("#rez_gsm").val();
var rez_tarih=$("#rez_tarih").val();
var rez_email=$("#rez_email").val();
var rez_tip=$("select#rez_tip").val();
var rez_sayi=$("select#rez_sayi").val();
var rez_aciklama=$("#rez_aciklama").val();
if(rez_ad == "" || rez_saat == "" || rez_gsm == "" || rez_tarih == "" || rez_email == "" || rez_tip == "" || rez_sayi == "" || rez_aciklama == "" ){
$("#message").html("some field is empty!!");
}else{
// AJAX code to send data to php file.
$.ajax({
type: "POST",
url: "rez/insert-data.php",
data: {rez_ad:rez_ad,rez_saat:rez_saat,rez_gsm:rez_gsm,rez_email:rez_email,rez_tarih:rez_tarih,rez_tip:rez_tip,rez_sayi:rez_sayi,rez_aciklama:rez_aciklama},
dataType: "JSON",
success: function(data) {
$("#message").html(data);
$("#message").addClass("alert alert-success");
},
error: function(err) {
alert(err);
}
});
}
}
<form name="rezform" onsubmit="return validation()" id="loginForm" method="POST" action="#" >
Since you are using jquery, use $('form').submit() method to return false if the validation is not success. other wise return true.
$( "form" ).submit(function( event ) {
if ( $( "input:first" ).val() === "correct" ) {
$( "span" ).text( "Validated..." ).show();
return;
}
$( "span" ).text( "Not valid!" ).show().fadeOut( 1000 );
event.preventDefault();
});
I have created a jsbin page for the reference given by jquery: https://jsbin.com/dokabod/1/edit?html,output
#alex also post the samething. I just corrected some of the errors he had. like return submit. below code working perfectly.
<form action="index.php" onsubmit="return insertData()" method="POST">
<input type="text" name="name" id="rez_ad">
<input type="text" name="name" id="rez_saat">
<input type="text" name="name" id="rez_gsm">
<input type="text" name="name" id="rez_tarih">
<input type="text" name="name" id="rez_email">
<input type="text" name="name" id="rez_tip">
<input type="text" name="name" id="rez_sayi">
<input type="text" name="name" id="rez_aciklama">
<input type="submit" name="" value="Send">
</form>
<div id="message"></div>
function insertData() {
submit = true;
var rez_ad=$("#rez_ad").val();
var rez_saat=$("#rez_saat").val();
var rez_gsm=$("#rez_gsm").val();
var rez_tarih=$("#rez_tarih").val();
var rez_email=$("#rez_email").val();
var rez_tip=$("#rez_tip").val();
var rez_sayi=$("#rez_sayi").val();
var rez_aciklama=$("#rez_aciklama").val();
if(rez_ad == "" || rez_saat == "" || rez_gsm == "" || rez_tarih == "" || rez_email == "" || rez_tip == "" || rez_sayi == "" || rez_aciklama == "" ){
$("#message").html("some field is empty!!");
submit = false;
return submit;
}else{
// AJAX code to send data to php file.
$.ajax({
type: "POST",
url: "rez/insert-data.php",
data: {rez_ad:rez_ad,rez_saat:rez_saat,rez_gsm:rez_gsm,rez_email:rez_email,rez_tarih:rez_tarih,rez_tip:rez_tip,rez_sayi:rez_sayi,rez_aciklama:rez_aciklama},
dataType: "JSON",
success: function(data) {
$("#message").html(data);
$("#message").addClass("alert alert-success");
},
error: function(err) {
alert(err);
}
});
}
}
I want my submit button to pull the value from the input box next to it, change the '#' to a '-' and then pass it on so that I can pull information respective to that user and then populate the field in HTML. But the page just refreshes and a '?' gets added to the url.
$("#usernameBtn").click(function() {
var unTouchedID = $("#userid").val();
var usrID = unTouchedID.replace("#", "-");
$.ajax({
url: "https://owapi.net/api/v3/u/" + usrID + "/stats",
dataType: 'json',
data: "",
success: function (data) {
$('#heroStats_elims').html('<h2>'+ data.us.stats.competitive.average_stats.eliminations_avg + '</h2>');
//var avgElims = //data.us.stats.competitive.average_stats.eliminations_avg
}
}); });
<div class="form-group">
<input type="text" class="form-control" placeholder="Enter Battle.net Tag" id="userid">
</div>
<button type="submit" class="btn btn-default" id="usernameBtn">Submit</button>
You need to use event.preventDefault(); as #Andrew mentioned to prevent the default behavior of submitting the page.
$("#usernameBtn").click(function(e) {
e.preventDefault();
var unTouchedID = $("#userid").val();
var usrID = unTouchedID.replace("#", "-");
$.ajax({
url: "https://owapi.net/api/v3/u/" + usrID + "/stats",
dataType: 'json',
data: "",
success: function (data) {
$('#heroStats_elims').html('<h2>'+ data.us.stats.competitive.average_stats.eliminations_avg + '</h2>');
//var avgElims = //data.us.stats.competitive.average_stats.eliminations_avg
}
});
});
<div class="form-group">
<input type="text" class="form-control" placeholder="Enter Battle.net Tag" id="userid">
</div>
<button type="submit" class="btn btn-default" id="usernameBtn">Submit</button>
Alright , I made a form with a validation , okay , when I want to connect the validation in laravel I use this way
this is pages controller
public function getContact(){
self::$data['title'] = 'Contact us';
return view('content.contact',self::$data);
}
public function postContact(test $request){
}
}
this is the routes :
Route::get('contact','PagesController#getContact');
Route::post('contact', 'PagesController#postContact');
and this is the form
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript" href="{{asset('js/class.FormValidation.js')}}"></script>
<script type="text/javascript" href="{{asset('js/landin_validation.js')}}"></script>
<link rel="stylesheet" type="text/css" href="{{asset ('js/style.css')}}"/>
</head>
<body>
<form action="" method="post" class="landing-form">
{!! csrf_field() !!}
<label>Fill your details here - </label><br/><br/>
<input placeholder="Full name:" type="text" name="name" class="field-name" />
<input placeholder="Email:" type="text" name="email" class="field-email" />
<input placeholder="Phone Number:" type="text" name="phone" class="field-phone" />
<input type="submit" name="submit" value="Send" />
Okay so , I tried a lot to connect the validation with the form , but since it's laravel so I know the requests way but I tried a lot to connect it with this validation but doesnt work ,
this is landin_validation.js
var formValidate = new FormValidation();
$(document).ready(function () {
$('form.landing-form').submit(function () {
// Collect client info from fields
var name = $.trim( $('input[type="text"].field-name').val() );
var email = $.trim( $('input[type="text"].field-email').val() );
var phone = $.trim( $('input[type="text"].field-phone').val() );
// Reset input fields error class
$('input[type="text"]').removeClass('error');
// Form validation
if (!formValidate.testName(name) ) {
$('input[type="text"].field-name').addClass('error');
$('input[type="text"].field-name').val('');
$('input[type="text"].field-name').attr('placeholder', '* Valid full name is required!');
} else if ( !formValidate.testEmail(email) ) {
$('input[type="text"].field-email').addClass('error');
$('input[type="text"].field-email').val('');
$('input[type="text"].field-email').attr('placeholder', '* Valid email is required!');
} else if ( !formValidate.testPhone(phone) ) {
$('input[type="text"].field-phone').addClass('error');
$('input[type="text"].field-phone').val('');
$('input[type="text"].field-phone').attr('placeholder', '* Valid phone is required!');
} else {
// Open ajax call to save client details + send mail to customer
$.ajax({
url: "form_handler.php",
type: "POST",
dataType: "html",
async: "false",
data: {name: name, email: email, phone: phone},
beforeSend: function () {
var messege = '<img src="ajax-loader.gif" border="0">';
messege += ' Sending... ';
$('form.landing-form label').html(messege);
},
success: function (response) {
if (response == true) {
setTimeout(function(){
$('div.form-wrapper').html('<label>Your details has been send!</label>');
}, 2000);
} else {
$('div.form-wrapper').html('<label>Something went wrong, please try again later...</label>');
}
}
});
}
// Stop form submission
return false;
});
});
And this is FormValidation.js
function FormValidation(){
this.nameReg = [
/^([a-zA-Z\s]+){2,255}$/
];
this.emailReg = [
/^[_a-z0-9-]+(.[_a-z0-9-]+)*#[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,3})$/
];
this.phoneReg = [
/^[0-9]{3}-[0-9]{3}-[0-9]{4}$/i,
/^[0-9]{3}.[0-9]{3}.[0-9]{4}$/i,
/^\([0-9]{3}\)-[0-9]{3}-[0-9]{4}$/i,
/^[0-9]{9,10}$/i
];
this.testName = function( nameInput ){
return this.inputCheck(this.nameReg, nameInput);
};
this.testEmail = function( emailInput ){
return this.inputCheck(this.emailReg, emailInput);
};
this.testPhone = function( phoneInput ){
return this.inputCheck(this.phoneReg, phoneInput);
};
this.inputCheck = function( regArray, inputData ){
var valid = false;
$.each( regArray, function( key, val ){
if( val.test( inputData ) ){
valid = true;
}
});
return valid;
};
}
I just want to know the way to connect the form with this validation.
I think it's not good idea to validate form data with js.Аccording to me you should validate from the server-side.If you want to have good user experience you can use this javascript lib - http://t4t5.github.io/sweetalert/
this is javacript and ajax dont know what is error i tried this without ajax its working but with ajax not working.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js">
</script>
<script type="text/javascript" >
$(function() {
$(".submit").click(function() {
var name = $("#User_Name").val();
var email = $("#User_Email").val();
var mobno = $("#User_Email").val();
var landlineno = $("#user_MobileNo").val();
var proprTd = $("#propertyids").val();
var dataString = 'User_Name='+ name + 'User_Email=' + email + 'User_Email=' + mobno + 'user_MobileNo=' + landlineno + 'propertyids=' + proprTd;
if(name=='' || email=='' || mobno=='' || landlineno=='')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "SaveContactDetails.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
</script>
this is html code
dont know what is error i tried this without ajax its working but with ajax not working.
<form method="post" name="form" >
<input type="hidden" name="propertyid" id="propertyids" value="<?php echo $Propid ?>" >
<input id="individual" name="rdoiam" value="individual" type="radio" class="input-38-ieo">
Individual
<input id="Agent" name="rdoiam" value="individual" type="radio" class="input-38-ieo">
Agent
<input id="builder" name="rdoiam" value="individual" type="radio" class="input-38-ieo">
Builder <span id="ReqTypeErrorDiv12968081_left" class="span-41-ieo"></span> </li>
<li class="li-42-ieo">
<label class="label-43-ieo">Name<span class="span-37-ieo">*</span></label>
:
<input type="text" id="User_Name" name="User_Name" maxlength="30" class="input-45-ieo11">
<input type="text" class="input-276-ieo11" id="Mobileno" name="user_MobileNo" maxlength="12">
<input type="text" class="input-276-ieo11" id="userLandlineno" name="userLandlineno" maxlength="12">
</form>
and this is php file
<?php
include 'config.php';
$iam ="";
$User_Name="";
$User_Email="";
$user_MobileNo="";
$user_LandlineNo="";
$txtMessage="";
if (isset($_POST['rdoiam']))
{
$iam =$_POST['rdoiam'];
}
if (isset($_POST['User_Name']))
{
$User_Name=$_POST['User_Name'];
}
if (isset($_POST['User_Email']))
{
$User_Email=$_POST['User_Email'];
}
if (isset($_POST['user_MobileNo']))
{
$user_MobileNo=$_POST['user_MobileNo'];
}
if (isset($_POST['userLandlineno']))
{
$user_LandlineNo=$_POST['userLandlineno'];
}
if(isset($_POST['txtMessage']))
{
$txtMessage=$_POST['txtMessage'];
}
$Propid=$_POST['propertyid'];
$iam =trim($iam);
$User_Name=trim($User_Name);
$User_Email=trim($User_Email);
$user_MobileNo=trim($user_MobileNo);
$user_LandlineNo=trim($user_LandlineNo);
$txtMessage=trim($txtMessage);
$str="Call sp_SaveContactDetails('".$iam."','".$User_Name."','".$User_Email."','".$user_MobileNo."','".$user_LandlineNo."','".$txtMessage."','".$Propid."')";
// $sql=mysql_query($str);
if(!mysql_query($str))
{
die('Error:'.mysql_error());
}
else
{
}
?>
You are missing & in your data string:
var dataString = 'User_Name='+ name + 'User_Email=' + email + 'User_Email=' + mobno + 'user_MobileNo=' + landlineno + 'propertyids=' + proprTd;
It has to be:
var dataString = 'User_Name='+ name + '&User_Email=' + email + '&User_Email=' + mobno + '&user_MobileNo=' + landlineno + '&propertyids=' + proprTd;
Thats why its not sending proper data, as you want. Of course, you can serialize all your data...
Also you should be using encodeURIComponent because if the user adds a & or =, your string is going to break.
var dataString = 'User_Name='+ name + 'User_Email=' + email + 'User_Email=' + mobno + 'user_MobileNo=' + landlineno + 'propertyids=' + proprTd;
That is not how you build a querystring
The string looks like User_Name=nameUser_Email=email...., you are missing the & between each. Also you should be using encodeURIComponent because if the user adds a & or =, your string is going to break.
Look at jQuery serialize() it does all of it for you.
Or just use serialize function, you are using jQuery anyway.
$( "form" ).on( "submit", function( event ) {
event.preventDefault();
var formData = $( this ).serialize();
$.ajax({
type: "POST",
url: "SaveContactDetails.php",
data: formData,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
});
Before sending ajax you can always add your validation.
You can use this
<script>
$(function () {
$('form#person').on('submit', function(e) {
$.ajax({
type: 'post',
url: 'show.php',
data: $('form').serialize(),
success: function (data) {
alert(data);
}
});
e.preventDefault();
});
});
</script>
I want to send form data from ajax to php. My ajax retrieves the form data but it doesnt send it i dont see anything wrong with the code maybe i need a much more professional help. Thanks in advance
HTML5 syntax
<div align="center"><a id="hi">Header</a></div>
<a id="signup" data-add-back-btn="true" style="float:right;" data-icon="arrow-r">Sign- In</a>
</div>
<form class="check-user" action="php/sup.php" method="POST">
<label>Username</label>
<input id="Susername" name="username" placeholder="username" type="text" >
</div>
<div align="center" data-role="fieldcontain" style="width:100%;overflow:hidden" data-position="static">
<label>Email</label>
<input id="Semail" name="email" placeholder="email" type="email" >
</div>
<div align="center" data-role="fieldcontain" style="width:100%;overflow:hidden" data-position="static">
<label>Password</label>
<input id="Spassword" name="password" placeholder="password" type="password" >
</div>
<!---input type="submit" style="visibility:hidden;" id="send"/-->
</form>
Ajax syntax
$('#signup').live('click', function(){
//var name = document.getElementById('Susername').value;
//var email = document.getElementById('Semail').value;
//var pass = document.getElementById('Spassword').value;
var that = $('form.check-user'),
urls = that.attr('action'),
methods = that.attr('method'),
data = {};
that.find('[name]').each(function(index, element) {
var that = $(this),
name = that.attr('name'),
element = that.val();
alert(name+'='+element+' '+methods);
data[name] = element;
});
$.ajax(
{
url: urls,
type: methods,
data : data,
beforeSend: function(response){alert('Sending');},
success: function(response){ alert('success');},
error: function(response){alert('failed');},
complete: function(response){alert('finished');},
}
);
return false;
});
PHP syntax
session_start();
$name = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
if(isset($name) && isset($email) && isset($password))
{
echo $name;
$_SESSION['username'] = $name;
}
else
{
die('data not set');
}
You can use serialize method on form, it will gather everything correct.
$('#signup').live('click', function(){
var that = $('form.check-user'),
urls = that.attr('action'),
methods = that.attr('method'),
data = that.serialize();
$.ajax(
{
url: urls,
type: methods,
data : data,
beforeSend: function(response){alert('Sending');},
success: function(response){ alert('success');},
error: function(response){alert('failed');},
complete: function(response){alert('finished');},
}
);
return false;
});
Try this,
$('#signup').live('click', function(){
$.ajax({
url:’’,//url to submit
type: "post",
dataType : 'json',
data : {
'Susername' : $('#Susername').val(),
'Semail' : $('#Semail').val(),
'Spassword' : $('#Spassword').val()
},
success: function (data)
{
}
});
return false;
});
I solved it works this way on the php side you do this
$name = isset(json_decode($_POST['username']));//htmlentities($values[0]);
$email = isset(json_decode(($_POST['email'])));//htmlentities($values[1]);
$password = isset(json_decode($_POST['password']));//htmlentities($values[2]);
The Ajax side
$(document).ready(function(e) {
$('#signup').live('click', function(){
//var name = document.getElementById('Susername').value;
//var email = document.getElementById('Semail').value;
//var pass = document.getElementById('Spassword').value;
var that = $('form.check-user'),
urls = that.attr('action'),
methods = that.attr('method'),
data = {};
data = that.serialize();
console.log(data);
$.ajax(
{
url: urls,
type: methods,
dataType:'json',
data : data,
beforeSend: function(response){$.mobile.showPageLoadingMsg(true);},
success: function(response){ $.mobile.showPageLoadingMsg(false);},
error: function(xhr, textStatus, errorThrown){alert(textStatus);},
complete: function(response){},
}
);
return false;
});
});