Dynamically changed value in jQuery not seen in sent jsp form - javascript

I am submitting the form on click button, but whatever I have changed that data is not sent but the previous data is sent, is there a way in which I can commit the data of the field in forms then send??
$j("body").on('click', "#btn_snd",function(){
Retrieve_Property_name();
$j(this).closest("form").submit();
});
});
The changes are done using ajax
function Retrieve_Property_name()
{
$j(".class_cat").hide();
var property_name = $j("#property_name").val();
$j.ajax({
type : "POST",
url : "ShowCat.jsp",
data : "property_name=" + property_name ,
success : function(data) {
if(data.trim()=="No")
{
$j("#Cat_name_hidden").val("General");
alert("Inside No");
}
else if(data.trim()=="Yes")
{
alert("Inside yes");
if($j("#Cat_name").val()==null)
{
$j("#Cat_name_hidden").val(" NULL");
}
else
{
//
alert("Categories:-"+$j("#Cat_name").val());
$j("#Cat_name_hidden").val($j("#Cat_name").val());
//
arr1 = $j("#Cat_name").val();
}
$j(".class_cat").show();
}
alert();
}
});
}
This is the change function

Instead of calling the submit function from the on function:
$j(this).closest("form").submit();
can you do this after your ajax call completes within the success function:
$j("#btn_snd").closest("form").submit();
My guess is that the form gets submitted before the ajax request completes and hence the old values are posted. So ideally the change function would be:
function Retrieve_Property_name()
{
$j(".class_cat").hide();
var property_name=$j("#property_name").val();
$j.ajax({
type : "POST",
url : "ShowCat.jsp",
data : "property_name=" + property_name ,
success : function(data) {
if(data.trim()=="No")
{
$j("#Cat_name_hidden").val("General");
alert("Inside No");
}
else if(data.trim()=="Yes")
{
alert("Inside yes");
if($j("#Cat_name").val()==null)
{
$j("#Cat_name_hidden").val(" NULL");
}
else
{
//
alert("Categories:-"+$j("#Cat_name").val());
$j("#Cat_name_hidden").val($j("#Cat_name").val());
//
arr1 = $j("#Cat_name").val();
}
$j(".class_cat").show();
}
alert();
$j("#btn_snd").closest("form").submit();
}
});
}

Related

How to prevent form submit?

I have a login form and a captcha field. I need a javascript source to check this captcha input then send post data to action but my code seems to be wrong, the e.preventDefault function doesn't work because captcha field true or false post data's still sent. please help.
This my javascript Function:
$(document).ready(function () {
$("#signupform").submit(function (event) {
var captchacode = $("#captchatexbox").val();
if (captchacode != "") {
var url = "/Account/ValidateCaptcha?Code=" + captchacode;
$.ajax({
url: url,
cache: false,
success: function (data) {
if (data == 0) {
alert("Invalid captcha");
event.preventDefault();
//Form post data still sent?
}
}
});
}
else alert("Captcha not null");
});
});
You need to move event.preventDefault(); up so it comes before the ajax call.
Use $("#signupform").submit(); in an else block to programmatically submit the form.
$(document).ready(function () {
$("#signupform").submit(function (event) {
event.preventDefault();
var captchacode = $("#captchatexbox").val();
if (captchacode != "") {
var url = "/Account/ValidateCaptcha?Code=" + captchacode;
$.ajax({
url: url,
cache: false,
success: function (data) {
if (data == 0) {
alert("Invalid captcha");
//Form post data still sent?
} else {
$("#signupform").submit();
}
}
});
}
else alert("Captcha not null");
});
});
You would need have the form event.preventDefault(); before making the ajax request.
$("#signupform").submit(function (event) {
event.preventDefault();
When the ajax request is returned, you can submit the form using:
if (data != 0) {
$("#signupform").submit();
}

e.PreventDefault and ajx submit not working together [return true] is not working

I have a function to check whether email exist, but I want to submit the form only if the email doesn't exist
So I wrote following function:
$("#form-1").on("submit",function(e){
e.preventDefault();
var given_email=document.getElementById("email");
var data = $("#form-1").serialize();
$.ajax({
type : 'POST',
url : 'check.php',
data : data,
beforeSend: function() {
$(".submit").val('sending ...');
},
success : function(response) {
var response = JSON.parse(response);
if(response.status=='error'){
alert("Sorry This Email Already Used ");
return false;
} if(response.status=='true') {
return true;
$(this).submit();
}
}
});
});
Now if it return true also i cant submit the form . Please help.
i saw this question and answer e.preventDefault doesn't stop form from submitting . But no effect
Notes
even i tried
if(response.status=='true') { $("#form-1").submit(); } .
But this also not working
The return statement is returning before the form is submitted
if(response.status == 'true') {
//return true; // returns before the form is submitted
$(this).submit();
return true; // move return after submit
}
Suggestion
You are thinking about this, the wrong way, let PHP handle the checking and insert in the backend.
First Solution
In your PHP do something like
$querycheck = mysqli_query($con,"SELECT * FROM Persons");
$countrows = mysqli_num_rows($querycheck );;
if($countrows == '1')
{
echo json_encode(['message' => 'Sorry This Email Already Used']);
}
else
{
// insert statement here
echo json_encode(['message' => 'Submitted']);
}
In your JS
$("#form-1").on("submit",function(e){
e.preventDefault();
var given_email=document.getElementById("email");
var data = $("#form-1").serialize();
$.ajax({
type : 'POST',
url : 'check.php',
data : data,
beforeSend: function() {
$(".submit").val('sending ...');
},
success : function(response) {
var response = JSON.parse(response);
alert(response.message); // display the message here to the user.
}
});
});
Second Solution
save the form in a variable.
$("#form-1").on("submit",function(e){
e.preventDefault();
const form = $(this); // get the current form
var given_email=document.getElementById("email");
var data = $("#form-1").serialize();
$.ajax({
type : 'POST',
url : 'check.php',
data : data,
beforeSend: function() {
$(".submit").val('sending ...');
},
success : function(response) {
var response = JSON.parse(response);
if(response.status=='error'){
alert("Sorry This Email Already Used ");
return false;
} if(response.status=='true') {
form.submit(); // submit the form here
return true;
}
}
});
});

Not working return in jquery ajax

this is my code:
$("#MainContent_btnSave").click(function () {
if (($("#MainContent_txtFunc").val() == "") || ($("#MainContent_cmbLoc").val() == "")) {
alert("Please fill options.");
return false;
}
else {
$("#msgbox-loading").show();
$.ajax({
type: "POST",
url: "Ajax.aspx",
data: { func: "getexist", catfunc: $("#MainContent_txtFunc").val(), catdes: $("#MainContent_txtDesc").val() },
success: function (data) {
var parsed = $(data);
var exist = parsed.filter("[id=exist]").text();
if (exist == "NO") {
return true;
}
if (exist == "Yes") {
alert("already defined.");
$("#msgbox-loading").hide();
return false;
}
},
error: function (xhr, ajaxOptions, thrownError) {
$("#msgbox-loading").hide();
HidePopup('popup');
alert(xhr.status + " " + thrownError);
}
});
};
});
My code is check mandatory and If empty mandatory, an error message display and or if not empty mandatory, first display the loading and then Ajax run.
After running Ajax i want if page send "NO" run button postback and if page send "Yes" stop button postback.
but Unfortunately, after run ajax and page send "Yes" run button post back.
please help.
you can use .ajaxComplete() for commands that you want to fire after ajax completed

Jquery Form on submit show success message

I have a form that uses Jquery to show a message for
*field required error message
I am trying to get it to show a success message if the form is submitted.
The form submits as long as the req fields are filled in.
Does anyone know how I can modify this code to show the "success" div if
all the "req" fields are filled out?
Thanks
$(function() {
function validateform() {
var valid = true;
$(".req").css("border","1px solid #ccc");
$(".req").each(function() {
if ( $(this).val() == "" || $(this).val().replace(/\s/g, '').length == 0 ) {
$(this).css("border","1px solided");$(".required").css("display","block");
valid = false;
}
});
return valid;
}
$("#submit").click( function() {
$('#myform').submit( validateform );
$('$name').submit();
});
});
submitHandler: function(form){
$(form).ajaxSubmit({
target: '#preview',
success: function() {
$('#form id').slideDown('slow'),
<!-- RESET THE FORM FIELDS AFTER SUBMIT STARTS HERE-->
$("#form")[0].reset();
<!--RESET THE FORM FIELDS AFTER SUBMIT ENDS HERE--->
}
});
}
There are two simple ways that will allow you to render a success message. You can either use ajax with the callback success function, or if you want a full post, you you can check at the top of your file if a certain POST was set, and if so, render a success message.
Here is an example of checking POST:
if(isset($_POST['name attribute posting'])) {
$util->showSuccessMessage();
//OR echo "<div class='popup'></div>"
}
And here is an example of using Ajax's success callback function:
function submitForm() {
$.ajax({
url : 'this_file.php',
type: 'POST',
success : showSuccessMessage //function call
})
}
$(function() {
function validateform() {
var valid = true;
$(".req").css("border","1px solid #ccc");
$(".req").each(function() {
if ( $(this).val() == "" || $(this).val().replace(/\s/g, '').length == 0 ) {
$(this).css("border","1px solided");
$(".required").css("display","block");
valid = false;
}
});
return valid;
}
$("#submit").click( function() {
$('#myform').submit(function()
{
if( validateform)
{
$('$name').submit();
}
} );
});
});
reference submit

How to save var value outside ajax success function?

I am trying to make some form validation functions. Here is what I have:
<script>
$(document).ready(function() {
var myObj = {};
$('#username').keyup(function () {
id = $(this).attr('id');
validateUsername(id);
});
function validateUsername(id){
var username = $("#"+id).val();
$.ajax({
url : "validate.php",
dataType: 'json',
data: 'action=usr_id&id=' + username,
type: "POST",
success: function(data) {
if (data.ok == true) {
$(myObj).data("username","ok");
} else {
$(myObj).data("username","no");
}
}
});
} // end validateusername function
$('#submit').click(function(){
if (myObj.username == "ok") {
alert("Username OK");
} else {
alert("Username BAD");
}
});
}); // end doc ready
So you can see, when a key is pressed in the textbox, it checks if it's valid. The "data.ok" comes back correctly. The problem is based on the response, I define $(myObj).username. For some reason, I can't get this value to work outside the validateusername function. When clicking the submit button, it has no idea what the value of $(myObj).username is.
I need to use something like this, because with multiple form fields on the page to validate, I can do something like:
if (myObj.username && myObj.password && myObj.email == "ok")
... to check all my form fields before submitting the form.
I know I must just be missing something basic.... any thoughts?
EDIT: SOLVED
All I had to do was change var myObj = {}; to myObj = {}; and it's working like a charm. I think I've been staring at this screen waaaaay too long!
You're not accessing the data that you stored properly. Access the username value this way:
$(myObj).data("username")
Resources:
Take a look at jQuery's .data() docs.
Very simple jsFiddle that shows how to properly set and retrieve data with jQuery's .data() method.
I would store the promise in that global variable and then bind an event to the done event within your submit button click.
$(document).ready(function() {
var myObj = false;
$('#username').keyup(function () {
id = $(this).attr('id');
validateUsername(id);
});
function validateUsername(id){
var username = $("#"+id).val();
myObj = $.ajax({
url : "validate.php",
dataType: 'json',
data: 'action=usr_id&id=' + username,
type: "POST",
success: function(data) {
$('#username').removeClass('valid invalid');
if (data.ok == true) {
$('#username').addClass('valid');
}
else {
$('#username').addClass('invalid');
}
}
});
} // end validateusername function
$('#submit').click(function(){
// if myObj is still equal to false, the username has
// not changed yet, therefore the ajax request hasn't
// been made
if (!myObj) {
alert("Username BAD");
}
// since a deferred object exists, add a callback to done
else {
myObj.done(function(data){
if (data.ok == true) {
alert("Username BAD");
}
else {
alert("Username OK");
}
});
}
});
}); // end doc ready
you may want to add some throttling to the keyup event though to prevent multiple ajax requests from being active at once.

Categories

Resources