Form doesn't submit form data populated via AJAX - javascript

I'm having the following problem with my code below: when 'productSearchResult' is populated via AJAX, the contents are not included when the form is submitted using the 'Add' button.
UPDATE 1:
Strangely it is working, but only the first time productSearchQuery is populated. Any subsequent populations of productSearchQuery run into the problem above.
HTML:
<form name="productSearch">
<input name="productSearchQuery" type="textbox">
</form>
<form name="productAdd">
<div id="productSearchResult"></div>
</form>
<a>Add</a>
<div id="addResult"></div>
HTML loaded via AJAX into productSearchResult:
<input type="radio" name="productId" value="3944">
<input type="radio" name="productId" value="3946">
<input type="radio" name="productId" value="3999">
JS:
<script type="text/javascript">
function postData(type, url, data, targetDiv) {
$.ajax({
type: type,
url: url,
data: data,
success: function(response) {
$(targetDiv).html(response);
},
error: function() {
alert('Error! Plese try again.');
}
});
return false;
};
$(document).ready(function() {
$('input[name=productSearchQuery]').keyup(function() {
// submit the form
postData('POST', 'search.php', $('form[name=productSearch]').serialize(), '#productSearchResult');
});
$('a').click(function() {
postData('POST', 'add.php', $('form[name=productAdd]').serialize(), '#addResult');
});
});
</script>
UPDATE 2:
OK, first off I want to apologise for not including this code in my original post, I honestly didn't suspect it could be the cause. I've fixed my code after rolling back the JS which is returned with the radio buttons. I can't understand why the new JS causes the problem above, whereas the old JS does not.
Here's the old JS that works fine:
$('tr.product input[type=radio]').hide();
$('tr.product').mouseover(function() {
$(this).addClass('blueHover');
}).mouseout(function() {
$(this).removeClass('blueHover');
});
$('tr.product').click(function(event) {
$('tr.product').removeClass('blueChecked');
$(this).closest('tr').addClass('blueChecked');
if (event.target.type !== 'radio') {
$(':radio', this).attr('checked', true);
}
});
Here's the new JS that causes the problems above:
$('tr.product input[type=radio]').hide();
$(document).on({
mouseenter: function () {
$('td', $(this).parent()).addClass('blueHover');
},
mouseleave: function () {
$('td', $(this).parent()).removeClass('blueHover');
},
click: function (event) {
$('tr.product').removeClass('blueChecked');
$(this).closest('tr').addClass('blueChecked');
if (event.target.type !== 'radio') {
$(':radio', $(this).parent().parent()).attr('checked', false);
$(':radio', $(this).parent()).attr('checked', true);
}
}
}, 'tr.product td');

Try this instead
<script type="text/javascript">
function postData(type, url, data, targetDiv) {
$.ajax({
type: type,
url: url,
contentType: 'application/json',
data: data,
success: function(response) {
$(targetDiv).html(response);
},
error: function() {
alert('Error! Plese try again.');
}
});
return false;
};
$(document).ready(function() {
$('input[name=productSearchQuery]').keyup(function() {
// submit the form
postData('POST', 'search.php', $('form[name=productSearch]').serialize(), '#productSearchResult');
});
$('a').click(function() {
postData('POST', 'add.php', $('form[name=productAdd]').serialize(), '#addResult');
});
});
</script>

You have to use jQuery on method.
$('body').on('click', 'a', function() {
postData('POST', 'add.php', $('form[name=productAdd]').serialize(), '#addResult');
});

Related

How to run JavaScript code on Success of Form submit?

I have an Asp.Net MVC web application. I want to run some code on the successful response of the API method which is called on form submit.
I have the below Code.
#using (Html.BeginForm("APIMethod", "Configuration", FormMethod.Post, new { #class = "form-horizontal", id = "formID" }))
{
}
$('#formID').submit(function (e) {
$.validator.unobtrusive.parse("form");
e.preventDefault();
if ($(this).valid()) {
FunctionToBeCalled(); //JS function
}
}
But FunctionToBeCalled() function gets called before the APIMethod(), but I want to run the FunctionToBeCalled() function after the response of APIMethod().
So I made the below changes by referring this link. But now the APIMethod is getting called twice.
$('#formID').submit(function (e) {
$.validator.unobtrusive.parse("form");
e.preventDefault();
if ($(this).valid()) {
//Some custom javasctipt valiadations
$.ajax({
url: $('#formID').attr('action'),
type: 'POST',
data: $('#formID').serialize(),
success: function () {
console.log('form submitted.');
FunctionToBeCalled(); //JS function
}
});
}
}
function FunctionToBeCalled(){alert('hello');}
So I am not able to solve the issue.
If you want to execute some work on success, fail, etc. situation of form submission, then you would need to use Ajax call in your view. As you use ASP.NET MVC, you can try the following approach.
View:
$('form').submit(function (event) {
event.preventDefault();
var formdata = $('#demoForm').serialize();
//If you are uploading files, then you need to use "FormData" instead of "serialize()" method.
//var formdata = new FormData($('#demoForm').get(0));
$.ajax({
type: "POST",
url: "/DemoController/Save",
cache: false,
dataType: "json",
data: formdata,
/* If you are uploading files, then processData and contentType must be set to
false in order for FormData to work (otherwise comment out both of them) */
processData: false, //For posting uploaded files
contentType: false, //For posting uploaded files
//
//Callback Functions (for more information http://api.jquery.com/jquery.ajax/)
beforeSend: function () {
//e.g. show "Loading" indicator
},
error: function (response) {
$("#error_message").html(data);
},
success: function (data, textStatus, XMLHttpRequest) {
$('#result').html(data); //e.g. display message in a div
},
complete: function () {
//e.g. hide "Loading" indicator
},
});
});
Controller:
public JsonResult Save(DemoViewModel model)
{
//...code omitted for brevity
return Json(new { success = true, data = model, message = "Data saved successfully."
}
Update: If SubmitButton calls a JavaScript method or uses AJAX call, the validation should be made in this method instead of button click as shown below. Otherwise, the request is still sent to the Controller without validation.
function save(event) {
//Validate the form before sending the request to the Controller
if (!$("#formID").valid()) {
return false;
}
...
}
Update your function as follows.
$('#formID').submit(function (e) {
e.preventDefault();
try{
$.validator.unobtrusive.parse("form");
if ($(this).valid()) {
$.ajax({
url: $('#formID').attr('action'),
type: 'POST',
data: $('#formID').serialize(),
success: function () {
console.log('form submitted.');
FunctionToBeCalled(); //JS function
}
});
}
}
catch(e){
console.log(e);
}
});
Check the browser console for fetching error. The above code will prevent of submitting the form.
I think line $.validator.unobtrusive.parse("form") were throwing error.
For that use you need to add the following jQuery libraries.
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-unobtrusive/3.2.11/jquery.validate.unobtrusive.min.js"></script>
I think you should remove razor form tag if you want to post your form using ajax call and add post api URL directly to ajax request instead of getting it from your razor form tag using id:
Here is the revised version of your code :
<form method="post" id="formID">
<!-- Your form fields here -->
<button id="submit">Submit</button>
</form>
Submit your form on button click like:
$('#submit').on('click', function (evt) {
evt.preventDefault();
$.ajax({
url: "/Configuration/APIMethod",
type: 'POST',
dataType : 'json',
data: $('#formID').serialize(),
success: function () {
console.log('form submitted.');
FunctionToBeCalled(); //JS function
}
});
});
function FunctionToBeCalled(){alert('hello');}
You need to use Ajax.BeginForm, this article should help [https://www.c-sharpcorner.com/article/asp-net-mvc-5-ajax-beginform-ajaxoptions-onsuccess-onfailure/ ]
The major thing here is that I didn't use a submit button, I used a link instead and handled the rest in the js file. This way, the form would nver be submitted if the js file is not on the page, and with this js file, it initiates a form submission by itself rather than th form submitting when the submit button is clicked
You can adapt this to your solution as see how it respond. I have somthing like this in production and it works fine.
(function() {
$(function() {
var _$pageSection = $('#ProccessProductId');
var _$formname = _$pageSection.find('form[name=productForm]');
_$formname.find('.buy-product').on('click', function(e) {
e.preventDefault();
if (!_$formname.valid()) {
return;
}
var formData = _$formname.serializeFormToObject();
//set busy animation
$.ajax({
url: 'https://..../', //_$formname.attr('action')
type: 'POST',
data: formData,
success: function(content) {
AnotherProcess(content.Id)
},
error: function(e) {
//notify user of error
}
}).always(function() {
// clear busy animation
});
});
function AnotherProcess(id) {
//Perform your operation
}
}
}
<div class="row" id="ProccessProductId">
#using (Html.BeginForm("APIMethod", "Configuration", FormMethod.Post, new { #class = "form-horizontal", name="productForm" id = "formID" })) {
<li class="buy-product">Save & Proceed</li>
}
</div>

AJAX/jQuery generated inputs not recognized by other jQuery scripts

I have what I assume is a relatively simple issue. For testing purposes I have made it so simple so as to locate the issue.
I have a jQuery script that works alongside AJAX to return some results next to checkboxes, here it is below:
$.ajax({
type:'GET',
url: '/customers/details/emails',
dataType:'json',
data: {
'customerID': $('select[name=payer_id]').val(),
'_token': $('input[name=_token]').val(),
},
success: function(data) {
$('.errorTitle').addClass('hidden');
$('.errorContent').addClass('hidden');
if ((data.errors)) {
setTimeout(function () {
$('#createOrigin').modal('show');
toastr.error('Check your inputs!', 'Error Alert', {timeOut: 5000});
}, 500);
if (data.errors.title) {
$('.errorTitle').removeClass('hidden');
$('.errorTitle').text(data.errors.title);
}
if (data.errors.content) {
$('.errorContent').removeClass('hidden');
$('.errorContent').text(data.errors.content);
}
} else {
$.each(data, function(i,val) {
$('<tr>').append(
$('<td>').html('<input type="checkbox" id="emailCheckboxSelect">'),
$('<td>').text(val)).appendTo('#customerEmails');
});
}
}
});
As you can see near the end, for each result a table row is appended, with a checkbox with an id of "emailCheckboxSelect".
Now to my problem, these are obviously dynamically created elements so I believe this is the issue with this script (a simple dummy just to locate the issue). Here is that script that should work:
$(function(){
$('#emailCheckboxSelect').click(function(){
alert('clicked');
});
});
This doesn't work with the dynamically created elements. However, I did add <input type="checkbox" id="emailCheckboxSelect">Checkbox directly to my page, and this does set off the alert.
So what am I doing wrong and what do I need to do so that jQuery can recognize dynamically created elements?
Try to bind the click event after the $.each(data, function() {}) inside the sucess: function() {}
You are using multiple elements with same id in the DOM : Element IDs should be unique within the entire document.
use classes instead
your code will look like:
$.ajax({
type: 'GET',
url: '/customers/details/emails',
dataType: 'json',
data: {
'customerID': $('select[name=payer_id]').val(),
'_token': $('input[name=_token]').val(),
},
success: function(data) {
$('.errorTitle').addClass('hidden');
$('.errorContent').addClass('hidden');
if ((data.errors)) {
setTimeout(function() {
$('#createOrigin').modal('show');
toastr.error('Check your inputs!', 'Error Alert', {
timeOut: 5000
});
}, 500);
if (data.errors.title) {
$('.errorTitle').removeClass('hidden');
$('.errorTitle').text(data.errors.title);
}
if (data.errors.content) {
$('.errorContent').removeClass('hidden');
$('.errorContent').text(data.errors.content);
}
} else {
$.each(data, function(i, val) {
$('<tr>').append(
$('<td>').html('<input type="checkbox" class="emailCheckboxSelect" />'),
$('<td>').text(val)).appendTo('#customerEmails');
});
$('.emailCheckboxSelect').click(function(e) {
alert('clicked');
});
}
}
});
Try changing your click event to something like
$('td').on('click', '.emailCheckboxSelect', function () {
alert('clicked');
});
This would work on dynamically created elements. Also, use class instead of id for dynamically created elements.

Unable to submit the ajax form multiple times after using .submit() function

This is my code:
var onloadCallback = function() {
$( "#submit" ).each(function() {
grecaptcha.render($( this ).attr('id'), {
'sitekey' : '6Lcjvi4UAAAAAIR7_ckItF2HfMEFHx427WUDdGDk',
'callback' : onsubmitforgotpass
});
});
};
function onsubmitforgotpass(token) {
$(document).ready(function() {
$("form.formajax").submit(function() {
$.ajax({
type: "POST",
url: "admin/login/forgotpass.php",
data: $("form.formajax").serialize(),
cache: false,
success: function(result) {
$(".forgotpassresult").html(result);
$(".forgotpassresult").css("opacity", "1");
}
});
return false;
});
$("form.formajax").submit();
});
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form action="" method="post" class="formajax">
<input type="text">
<input type="submit" id="submit">
</form>
I am unable to submit this ajax form multiple times.
It is probably because of these 2 lines:
$("form.formajax").submit(function()
and
$("form.formajax").submit();
If I replace those line with $("#submit").click(function() and $("#submit").click();
Then I can submit the form multiple times.
Anyway to submit the form multiple times using .submit(); function? (It will help me in some other part of my code also, so I do not want to use click();
hey please test the following things:
Please remove the actions
action="abc.com"
to
action=""
add ajax call on button click like below example:
$("#submit").click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "admin/login/forgotpass.php",
data: $("form.formajax").serialize(),
cache: false,
success: function(result) {
$(".forgotpassresult").html(result);
$(".forgotpassresult").css("opacity", "1");
}
});
});
});

Redirection after successful form submit

I have a form which should submit data after pressing the submit button. After tagging a few input fields as required the form always shows me when there is no input in the required field after pressing the submit button - so far, so good.
What I would like to realize is that there is a redirection to another page if the submission was successful. If there are some empty required fields the form should show me, without redirecting me to another page.
By now I have the following code:
Submit button:
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" name="submityes" id="submityes" class="btn btn-danger">Submit</button>
</div>
</div>
Also I have the following js function to submit the form and to redirect me to another page:
$('document').ready(function () {
"use strict";
$(function () {
$('#submityes').click(function () {
$.ajax({
type: "POST",
/* url: "process.php", //process to mail
data: $('form.contact').serialize(), */
success: function (msg) {
window.location.replace("/submit_resolved.php");
},
error: function () {
alert("error");
}
});
});
});
});
The problem I have right now is that I will always be redirected to the "submit_resolved.php" page, whether all required fields are complete or not.
How can I solve this problem? I only want to be redirected when all required fields are not empty.
You should bind to the submit event, not click event:
UPDATED TO MATCH THE COMMENTS
$(function () {
var submityesClicked;
//catch the click to buttons
$('#submityes').click(function () {
submityesClicked = true;
});
$('#submitno').click(function () {
submityesClicked = false;
});
$('#webform').submit(function (e) {
e.preventDefault();//prevent the default action
$.ajax({
type: "POST",
/*url: "process.php", //process to mail
data: $('form.contact').serialize(),*/
success: function (msg) {
window.location.replace(submityesClicked ? "/submit_resolved_yes.php" : "/submit_resolved_no.php");
},
error: function () {
alert("error");
}
});
});
});
The submit event is triggered only if the form is valid.
Note that the submit event is triggered by the form but the click event is triggered by the input element.
Do redirection on complete. Not on success
$('document').ready(function () {
"use strict";
$(function () {
$('#submityes').click(function () {
$.ajax({
type: "POST",
/* url: "process.php", //process to mail
data: $('form.contact').serialize(), */
success: function (msg) {
//window.location.replace("/submit_resolved.php");
},
complete: function () {
window.location.replace("/submit_resolved.php");
},
error: function () {
alert("error");
}
});
});
});
});
I assume you are validating form in process.php so, you have to return error if validation fail from process.php like this.
header('HTTP/1.1 500 Internal Server Booboo');
header('Content-Type: application/json; charset=UTF-8');
die(json_encode(array('message' => 'ERROR', 'code' => 1337)));
check this link: Return errors from PHP run via. AJAX?
Hope this may be helpful to you.
The simplest thing you can do is to add "required" attribute to you input elements.Example:
<form action="/action_page.php">
Username: <input type="text" name="usrname" required>
<input type="submit">
</form>
It's a HTML5 attribute, so no JavaScript required. And it is supported by all major browsers. Check this link:
http://caniuse.com/#search=required
Anyway, you shouldn't rely just on front-end verification. Check those inputs on back-end, too.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<form action="">
Username: <input type="text" id="usrname" required>
<button type="button" name="submityes"
id="submityes" class="btn btn-danger">Submit</button>
</form>
</div>
function isValid(){
var usrname = $("#usrname").val();
if(usrname == ""){
return false;
}
return true;
}
$(function () {
$('#submityes').submit(function () {
if(isValid() == true){
$.ajax({
type: "POST",
/*url: "process.php", //process to mail
data: $('form.contact').serialize(),*/
success: function (msg) {
alert("success");
window.location.replace("/submit_resolved.php");
},
});
}else{
alert("error");
}
});
});

Facing AJAX issue with JSP

I am working on a small tool which just consists of a single JSP which is used for view as well as for processing the AJAX response.
If the call is of type 'GET', I am showing a form the user.
<form id="submitForm" method="post">
<div class="ui-widget">
<label for="tags">Please Select the Merchant : </label>
<input id="tags" name="mechant" style="width:300px;height:40px;border: 0.5px solid;border-radius: 5px;">
<input type="submit" value="Get Data" style="border: 0.5px solid;border-radius: 5px;">
</div>
</form>
And following is the code which will make the call.
$("#submitForm").submit(function() {
$.ajax({
url: 'serve_tx_2.jsp',
type: 'POST',
data: {q: $('#tags').val()},
success: function(data) {
$('#data').html(data);
alert('Load was performed.');
},
beforeSend: function() {
// $('.loadgif').show();
},
complete: function() {
// $('.loadgif').hide();
}
});
//return false;
});
Once the user submits the form which goes as 'POST' the logic in the same JSP is returning the response.
Right now I am trying with a very simple logic.
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write("Hello World");
Now when this response is return the whole of initial page is washed off and I just see "Hello World" on the page. Even though as per my understanding only the div with id "data" should be updated with value.
Kindly anyone have a look and let me know what might be going wrong here.
Thanks in advance.
You could try preventing the default handler as well as prevent bubbling up the DOM.
$("#submitForm").submit(function(event) {
// Prevent the default action
event.preventDefault();
// Pevent propagation of this event up the DOM
event.stopPropagation();
$.ajax({
url: 'serve_tx_2.jsp',
type: 'POST',
data: {q: $('#tags').val()},
success: function(data) {
$('#data').html(data);
alert('Load was performed.');
},
beforeSend: function() {
// $('.loadgif').show();
},
complete: function() {
// $('.loadgif').hide();
}
});
//return false;
});

Categories

Resources