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>
Related
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
}
} );
}
I have an ajax function on my form to check duplicate accounting code, but the form won't submitting even though there's no duplicate (that have to be submitted and processed to insert to database).
Here's my Html code :
<form action="<?php print base_url(); ?>input/insertLedgerGroup" name="form_ldgroup" onsubmit="return checkDupCode()" id="frmledger" method="post" accept-charset="utf-8">
my Ajax code :
function checkDupCode() {
var c1 = document.forms["form_ldgroup"]["coa1"].value;
var c2 = document.forms["form_ldgroup"]["coa2"].value;
var wrn1 = "Coa Code";
var wrn2 = "Sudah Terpakai !";
$.ajax({
type: "POST",
url: "<?php print base_url()."input/checkDupCoa"; ?>",
data: {"hsl": c1, "hsl2": c2, "csrf_token" : $("input[name=csrf_token]").val()},
dataType: 'json',
success: function(hasil) {
if(Object.keys(hasil).length>0){
alert(wrn1+" "+hasil['code1']+"."+hasil['code2']+" "+wrn2);
}else{
$("#frmledger").submit();
}
}
});
return false;
}
When you call:
$("#frmledger").submit();
is like calling your checkDupCode function again and again. But every time you call this function you return false, no submit.
In order to avoid this you can use the HTMLFormElement.submit() element method. In this way you don't call again your checkDupCode function.
In the following snippet I added the error callback in order to create the evidence:
function checkDupCode() {
var c1 = document.forms["form_ldgroup"]["coa1"].value;
var c2 = document.forms["form_ldgroup"]["coa2"].value;
var wrn1 = "Coa Code";
var wrn2 = "Sudah Terpakai !";
$.ajax({
type: "POST",
url: "input/checkDupCoa",
data: {"hsl": c1, "hsl2": c2, "csrf_token": $("input[name=csrf_token]").val()},
dataType: 'json',
success: function (hasil) {
if (Object.keys(hasil).length > 0) {
alert(wrn1 + " " + hasil['code1'] + "." + hasil['code2'] + " " + wrn2);
} else {
$("#frmledger").submit();
}
},
error: function() {
$("#frmledger")[0].submit();
}
});
return false;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="<?php print base_url(); ?>input/insertLedgerGroup" name="form_ldgroup" onsubmit="return checkDupCode()"
id="frmledger" method="post" accept-charset="utf-8">
<input type="text" name="coa1" value="coa1">
<input type="text" name="coa2" value="coa2">
<input type="submit" value="Submit">
</form>
I am currently learning jquery AJAX, i am trying to change my standar php post to AJAX but not working, it's still prosses with php, not AJAX. Not even in the console show anything. Can anyone check my code ?
I am using Codeigniter. And you can asume the php part is working fine ..
HTML :
<form action="<?=base_url()?>operator_pt/unggah/unggah_semua" id="unggahsemua" method="POST" name="unggahsemua" role="form">
<?php foreach($data as $rod)
$tahun = $rod->id_smt;
$jurusan = $rod->id_sms;
?>
<div id="form-tahun" class="form-group">
<input type="hidden" class="form-control" id="tahun" name="tahun" value="<?php echo $tahun;?>">
</div>
<div id="form-jurusan" class="form-group">
<input type="hidden" class="form-control" id="jurusan" name="jurusan" value="<?php echo $jurusan;?>">
</div>
Sedang Mengunggah :
<div id="statmhs"> </div>
<div id="statidmhs"> </div>
<div id="statdsnpt"> </div>
<i class="fa fa-circle-o-notch fa-spin" style="font-size:24px"></i>
JS :
$(document).ready(function() {
$('#unggahsemua').submit(function(event) {
$('.form-group').removeClass('has-error');
$('.help-block').remove();
var formData = {
'tahun' : $('input[name=tahun]').val(),
'jurusan' : $('input[name=jurusan]').val(),
};
// process the form
$.ajax({
type : 'POST',
url : '<?=base_url()?>operator_pt/unggah/unggah_semua', // the url where we want to POST
data : formData,
dataType : 'json',
encode : true
})
.done(function(data) {
console.log(data);
$('#statmhs').append('<div class="help-block">' + data.infounggahmhs + '</div>');
$('#statidmhs').append('<div class="help-block">' + data.infounggahidmhs + '</div>');
$('#statdsnpt').append('<div class="help-block">' + data.infounggahdsnpt + '</div>');
.fail(function(data) {
console.log(data);
});
event.preventDefault();
});
});
You have errors in your Javascript code..
You missed the closing brackets before the .fail method. Also you had an extra comma after the last entry of your formData object
Try changing to this:
$(document).ready(function () {
$('#unggahsemua').submit(function (event) {
$('.form-group').removeClass('has-error');
$('.help-block').remove();
var formData = {
'tahun': $('input[name=tahun]').val(),
'jurusan': $('input[name=jurusan]').val()
};
// process the form
$.ajax({
type: 'POST',
url: '<?=base_url()?>operator_pt/unggah/unggah_semua', // the url where we want to POST
data: formData,
dataType: 'json',
encode: true
})
.done(function (data) {
console.log(data);
$('#statmhs').append('<div class="help-block">' + data.infounggahmhs + '</div>');
$('#statidmhs').append('<div class="help-block">' + data.infounggahidmhs + '</div>');
$('#statdsnpt').append('<div class="help-block">' + data.infounggahdsnpt + '</div>');
})
.fail(function (data) {
console.log(data);
});
event.preventDefault();
});
});
You have to stop default execution of form submit as you have to do it with ajax.
$(document).ready(function () {
$('#unggahsemua').submit(function (event) {
event.preventDefault() //<------- Add this line
$('.form-group').removeClass('has-error');
$('.help-block').remove();
var formData = {
'tahun': $('input[name=tahun]').val(),
'jurusan': $('input[name=jurusan]').val()
};
// process the form
$.ajax({
type: 'POST',
url: '<?=base_url()?>operator_pt/unggah/unggah_semua', // the url where we want to POST
data: formData,
dataType: 'json',
encode: true
})
.done(function (data) {
console.log(data);
$('#statmhs').append('<div class="help-block">' + data.infounggahmhs + '</div>');
$('#statidmhs').append('<div class="help-block">' + data.infounggahidmhs + '</div>');
$('#statdsnpt').append('<div class="help-block">' + data.infounggahdsnpt + '</div>');
})
.fail(function (data) {
console.log(data);
});
});
});
if you use form action="" method="POST" name="" role="form", make sure in config.php change $config['csrf_protection'] = TRUE; to FALSE.
But, if you want to set it TRUE you must use form_open()
I am getting xml file content using jquery and binding in to textbox, if anybody change the value in the text box , same has to be reflected in the source xml file, how to do that, i am new to xml.
Here is the code i am using to get the data from xml file.
<html><head>
<link rel="stylesheet" type="text/css" media="all" href="style.css" />
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "GET",
url: "employees.xml",
dataType: "xml",
success: function(xml) {
$(xml).find('Employee').each(function() {
var id = $(this).attr('id');
var name = $(this).find('Name').text();
var designation= $(this).find('Designation').text();
// alert(id + '|' + name + '|' + designation);
$('<div class="items" id="' + id + '"></div>').html('<input type="text" value="' + name + '">').appendTo('#page-wrap');
});
}
});
});
function saveXMLFiles() {
$("#page-wrap").find('id').each(function() {
var description = $(this).find('Designation').text();
alert(description);
});
}
</script>
</head>
<body>
<div id="page-wrap">
<h1>
Employees</h1>
</div>
<input type="button" value="Save" onclick="saveXMLFiles();" />
First create a web method for updating the XML in your server side.
Again you have to write an ajax request for updating the XML.
This is purely depends on your server-side.
Keep these things in mind:
You have to take the value of xml in a variable that is accessible to all the functions so that you can change it when somebody change the value in text box
Pass the value of updated xml to the server;
So do like this;
<script type="text/javascript">
$(document).ready(function() {
var globalXML = null;
$.ajax({
type: "GET",
url: "employees.xml",
dataType: "xml",
success: function(xml) {
globalXML = xml;//this is going to set in global variable
$(xml).find('Employee').each(function() {
var id = $(this).attr('id');
var name = $(this).find('Name').text();
var designation= $(this).find('Designation').text();
// alert(id + '|' + name + '|' + designation);
$('<div class="items" id="' + id + '"></div>').html('<input type="text" value="' + name + '">').appendTo('#page-wrap');
});
}
});
});
function saveXMLFiles() {
$("#page-wrap").find('id').each(function() {
var description = $(this).find('Designation').text();
//change to globalXML;
//and send it to server;
$.ajax({
type: "POST",
url: "saveEmployeesToXML",//path to post
data: globalXML,
success: function(response) {
alert(response);
}
});
}
});
alert(description);
});
}
</script>
I am Trying to upload file without reloading or redirecting page to other page.
I have tried...
upload.php
<form enctype='multipart/form-data' action='/' method='POST' class="AjaxSubmit" id='newwork' name='newwork'>
Choose New Work<br />
<input name='uploadednewwork' type='file' /><br />
<button id="btnFrmPost1" class="button" onclick="up()" >New Work</button>
</form>
script.js
function up() {
$('#btnFrmPost1').click(function() {
event.preventDefault();
var $form = $(this);
var url = "/subpages/upload_new_work.php";
var data = $form.serialize()
$.ajax({
type: "POST",
dataType: "json",
url: url,
data: data,
success: function (resp) {
var jdata = eval(resp);
var $jAlrtSuccess = $('<div>' + jdata.responseText + '</div>');
$($jAlrtSuccess).dialog({modal:true});
},
error: function (xhr, status, error) {
var $jAlrtError = $('<div>' + xhr.responseText + '</div>');
$($jAlrtError).dialog({modal:true});
}
});
return false;
});
}
I have tried all this code...
but i wont get result...
can any one please tell me how to solve this problem...