submit form with button outside form using ajax - javascript

I try to post a form using ajax the current code does not really work. When I press the save button the form get submitted n + 1 times. i.e After refreshing the page it submit once, next time I submit two form get submitted, third time... etc.
I have spend a lot of time researching this already (2 days) and I have not found a questions quite similar to what I am asking.
I am on a steep learning curve here so I hope someone can point out to me what I am doing wrong.
I think I might have mixed something up. The steps up to submit is.
Form values is being filled in.
A button is pressed to show a modal to confirm to submit the form (The submit button is actually inside this modal and not inside the form itself).
Form is submitted.
$('#confirmYes').click(function() {
$('#confirm-object').modal('hide'); // close confirm modal
$('#newForm').submit(function (e) {
e.preventDefault();
let formData = $(this).serialize();
$.post({
type: 'POST',
url: '/api/pois/',
data: formData
})
<form id="newForm">
<input type="text" id="name" name="name">
<input type="text" id="company" name="company">
</form>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-success" form="newForm" id="confirmYes">Save</button>
</div>

The issue is because you are creating a new submit event handler in every click. From the description of what you want to do, you instead need to create a single submit handler when the page loads, and trigger it when the button is clicked. Something like this:
$('#newForm').submit(function(e) { // handle the submit event
e.preventDefault();
let formData = $(this).serialize();
$.post({
type: 'POST',
url: '/api/pois/',
data: formData
})
})
$('#confirmYes').click(function() {
$('#confirm-object').modal('hide');
$('#newForm').submit(); // trigger the submit event
});

Simply remove the $('#newForm').submit(function (e) {}); :
.submit(function (e) {}) is creating an event handler for the submit event of your form, it's not submitting it.
$('#confirmYes').click(function() {
$('#confirm-object').modal('hide'); // close confirm modal
let formData = $('#newForm').serialize();
$.post({
type: 'POST',
url: '/api/pois/',
data: formData
});
});

$('#confirmYes').click(function() {
let formData = $('#newForm').serialize();
$.post({
type: 'POST',
url: '/api/pois/',
data: formData
});
);
<form id="newForm">
<input type="text" id="name" name="name">
<input type="text" id="company" name="company">
</form>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-success" id="confirmYes">Save</button>
</div>

Related

JQuery Serilize Data Input Is Empty

I have form containing a button, when clicked it displays a modal window with another form containing an input and a send / cancel button.
I want to serialize the data in this modal form and send it to a remote server via AJAX.
For some reason when I look the the console I can't see the serialized data, I can only see Email=
Can someone look at my code and tell me where I'm going wrong please? Should this work?
HTML
<form id="feedbackForm">
<input class="button" id="bad" src="bad.png" type="image">
</form>
<div aria-hidden="true" class="modal" id="modal" role="dialog" tabindex="-1">
<form id="emailForm">
<div class="form-group">
<input class="form-control" name="Email" type="text">
</div>
<div class="modal-footer">
<button class="btn" type="submit">Send</button>
<button class="btn" data-dismiss="modal" id="closeModal" type="button">Cancel</button>
</div>
</form>
</div>
AJAX
<script>
$(document).ready(function() {
var request;
$("#feedbackForm").on("touchstart, click", function(e) {
e.preventDefault();
var serializedData = $("#emailForm").serialize();
$('#modal').modal('toggle');
$("#emailForm").on("submit", function(e) {
e.preventDefault();
request = $.ajax({
url: "MyURL",
type: "post",
data: serializedData
});
request.done(function(response, textStatus, jqXHR) {
console.log(serializedData); // displays Email=
});
});
});
});
</script>
If I understand correctly when the user clicks the touchstart
You serialize the form
You open the modal containing the form
You overwrite the submit event to send your ajax
The thing is that your variable has already been given the values of the form before it is populated with the user data. (If he is opening the modal for the first time)
Just get your data from a function of ajax submit at the correct moment like this:
data: getSerializedData()
and the function
function getSerializedData(){
return $("#emailForm").serialize();
}

Use jQuery to submit 1 Ajax form on page with several unique forms

I have a Bootstrap page that is dynamically created using PHP, and on the page there are 25+ forms that are used to edit records.
The form submits to the server using jQuery Ajax script which works as expected on the first form, but when the second form is edited and submitted it submits form 1 and 2, and when I go to form 3 it will submit forms 1, 2, and 3
Here is the HTML:
<tr id="375987">
<td width="20%">audio controls to play wav file</td>
<td width="80%">
<div class="form-group">
<form id="375987">
<textarea class="form-control" id="rec_txt" name="rec_txt" rows="4">There is text from the Database</textarea>
<input type="text" id="event_num" name="event_num" value="" />
<button type="submit" id="correct_stt" class="btn btn-outline-success my-2 my-sm-0" OnClick="update_stt()">Edit</button>
<input type="hidden" id="rec_id" name="rec_id" value="375987" />
<input type="hidden" name="act" value="correct_stt" />
</form>
</div>
</td>
<td>
<a href="#" class="btn btn-primary a-btn-slide-text" onClick="hiderow('375987')">
<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
<span><strong>Hide</strong></span>
</a>
</td>
</tr>
<!-- 25+ forms ..... -->
And here is the Java:
function update_stt() {
var url = "function_ajax.php"; // the script where you handle the form input.
$('form[id]').on('submit', function(e) {
$.ajax({
type: 'POST',
url: url,
data: $(this).serialize(),
success: function(data) {
console.log('Submission was successful.');
console.log(data);
$(e.target).closest('tr').children('td,th').css('background-color', '#000');
},
error: function(data) {
console.log('An error occurred.');
console.log(data);
},
});
e.preventDefault();
});
}
How can I identify only the id of the form that I want submitted, or submit only the form on that row?
You use a submit button which will automatically submit the form, but you also add a click event to it using the onclick attribute, so it will execute the associated function and submit the form. All that is unnecessarily complicated.
Remove the onclick attribute on your button:
<button type="submit" id="correct_stt" class="btn btn-outline-success my-2 my-sm-0">Edit</button>
And change your code to:
$('#375987').on('submit', function(e) {
var url = "function_ajax.php"; // the script where you handle the form input.
$.ajax({
type: 'POST',
url: url,
data: $(this).serialize(),
success: function(data) {
console.log('Submission was successful.');
console.log(data);
$(e.target).closest('tr').children('td,th').css('background-color', '#000');
},
error: function(data) {
console.log('An error occurred.');
console.log(data);
},
});
e.preventDefault();
});
If you want all your forms to use the same function, then simply replace the selector $('#375987') with $('form'):
$('form').on('submit', function(e) { ... }
If you only want to select some forms, not all, then you can give them the same class and then select them by that class, like <form class="ajaxed">:
$('form.ajaxed').on('submit', function(e) { ... }
You can give id to forms and use
$('#formid').submit();
in your case
$('#375987').submit();
But that id is used by your tr div too. You should consider using id for form only
It's because each time you click the button and call update_stt() you are attaching again the .on() listener.
This is why you end up with more and more submit requests.
$('form[id]').on('submit', function (e) {
This line of code should only be called once not on every click.
ALSO: you said you build these on the backend so you could pass the ID straight to the function:
update_stt(375987)
Then you can use this:
function update_stt(passedNumber) { ...
Then you can use the id number in the call
Your mixing jQuery and vanilla JS a lot here, might make sense to try a larger refactor.

How do you execute a new AJAX everytime a submit button is clicked?

I have a form that is executed every time a submit button is clicked. When the submit button is clicked, a modal is shown and the modal is populated with JSON data. The application /addresschecker checks against the addresses posted and sends me an error message if I get a code return number of 2003. If not I select the return data via JSON using jQuery's $.each
The application works but when I close the modal, refill out the form and click submit, the form does not make a new call to /addresschecker I looked in my network tab of chrome and it seems to be using the old data. I am thinking that I need to force a new Ajax call everytime a user clicks on the submit button or clear the cache somehow. Not sure why I'm seeing old data
<form id="Validate">
<input class="form-control" id="adr1" name="address1" type="text" placeholder="Address 1" />
<input class="form-control" id="adr2" name="address1" type="text" placeholder="Address 1" />
<button type="submit" >Submit</button>
</form>
<div class="modal hide">
<!-- JSON Data returned -->
<div id="Message_1"></div>
<div id="Message_2"></div>
<div id="error_message"></div>
</div>
// My main form code
submitHandler: function(form) {
$.ajax({
url: '/addresschecker',
type: 'post',
cache: false,
dataType: 'json',
data: $('form#Validate').serialize(),
success: handleData
});
function handleData(data) {
var mesgcheck = data.message;
if (data.code == '2003') {
$("#error_messag").html(mesgcheck);
} else {
// Display Modal
$(".modal").removeClass("hide");
$.each(data, function(i, suggest) {
$(".adr1").val(suggest.address1);
$(".adr2").val(suggest.address2);
});
}
}
}
Let ajax handle your request.
Use this:
<input type="button" value="submit">
Instead of type submit.

JavaScript ActiveElement is form not button with Safari

I have a list of forms on my site with JS/AJAX that submits the forms on click. The JavaScript determines the submit type based on the active element. This has been working find across multiple browser.
Problem: Basically Safari (Version 10.0.2) on MAC considers the activeElement the form instead of the button so the getAttribute returns null. Is there a way to get the clicked element? I need to know which button the user clicked.
HTML Stuff:
<div id="#Records">
<form action="update.php" method="post">
...
<input name="submit" type="submit" data-action="send" value="send stuff" />
<input name="submit" type="submit" data-action="update" value="update" />
<input name="submit" type="submit" data-action="delete" value="delete" />
</form>
</div>
JavaScript stuff
$("#Records form").submit(function (e) {
e.preventDefault();
var url = this.action;
var data = $(this).serializeArray();
var action = document.activeElement.getAttribute('data-action');
data.push({ name: 'submit', value: action });
$.ajax({
type: "POST",
data: data,
cache: false,
url: url
}).done(function (data) {
$("#Records").html(data);
}).fail(function (result) {
ShowMessage("Error updating record!");
});
return false;
});
Can't you get the element using e.currentTarget instead of the active element? Something like
var action = $(e.currentTarget).attr('data-action');
(I'm assuming button click leads to the submit)
Ok, based on Tiny Giant and other comments I have changed the code to this. Not sure it is the best method but seems to work everywhere I have tested.
note simplified, comments welcome
HTML
<div id="#Records">
<form action="update.php" method="post">
...
<input type="button" onclick="return $(this).processRequest(this, 'send');" data-action="send" value="send stuff" />
<input type="button" onclick="return $(this).processRequest(this, 'update');" data-action="update" value="update" />
<input type="button" onclick="return $(this).processRequest(this, 'delete');" data-action="delete" value="delete" />
</form>
</div>
JavaScript
jQuery.fn.processRequest =
function(button, action)
{
var form = $(button).parents('form');
var url = form[0].action;
var data = $(form).serializeArray()
data.push({ name: 'submit', value: action });
$.ajax({
type: "POST",
data: data,
cache: false,
url: url
}).done(function (data) {
$("#Records").html(data);
}).fail(function (result) {
ShowMessage("Error updating record!");
});
return false;
}

(button || input) type=submit - missing value in $_POST variable in jQuery AJAX

I have login form where are two buttons - "login" and "forgot password?" And I need to check what button user clicked.
<form id="loginForm">
<div class="login-error" id="login-error"></div>
<input type="text" id="email" name="email">
<input type="password" id="password" name="password">
<input type="submit" name="submit" value="Login">
<button type="submit" name="submit" value="Forgot password?">Forgot password?</button>
</form>
var_dump($_POST) says:
array(2) { ["email"]=> string(0) "" ["password"]=> string(0) "" }
I am trying both ways (input type=submit and button type=submit) but none of them send the "submit" value.
(I am using jquery ajax)
$("#loginForm").click(function(){
/* Stop form from submitting normally */
event.preventDefault();
/* Get some values from elements on the page: */
var values = $(this).serialize();
/* Send the data using post and put the results in a div */
$.ajax({
url: "login.php", /* here is echo var_dump($_POST); */
type: "post",
data: values,
success: function(data){
$("#login-error").html(data);
},
error:function(){
$("#result").html('There is error while submit');
}
});
});
Please do you know where the problem can be? I know, there are lot of threads about value of button but nothing works for me. I also tried this example:
http://www.w3schools.com/tags/tryit.asp?filename=tryhtml_button_value2
The .serializeArray() or .serialize() method uses the standard W3C rules for successful controls to determine which elements it should include; in particular the element cannot be disabled and must contain a name attribute. No submit button value is serialized since the form was not submitted using a button. Data from file select elements is not serialized.
Refer..
http://api.jquery.com/serialize
http://api.jquery.com/serializeArray
jQuery serializeArray doesn't include the submit button that was clicked
This is one way to do it, concatening data string with specific clicked button name attribute:
HTML:
<form id="loginForm">
<div class="login-error" id="login-error"></div>
<input type="text" id="email" name="email">
<input type="password" id="password" name="password">
<button type="button" name="login" class="submit">Login</button>
<button type="button" name="forgot" class="submit">Forgot password?</button>
</form>
JQ:
$("#loginForm").on('click', '.submit', function (event) {
/* Stop form from submitting normally */
event.preventDefault();
/* Get some values from elements on the page: */
var values = $(this).closest('form').serialize() + '&' + this.name;
console.log(values);
/* Send the data using post and put the results in a div */
$.ajax({
url: "login.php",
/* here is echo var_dump($_POST); */
type: "post",
data: values,
success: function (data) {
$("#login-error").html(data);
},
error: function () {
$("#result").html('There is error while submit');
}
});
});
But better would be to target specific server side script depending which button is clicked, e.g:
HTML:
<form id="loginForm">
<div class="login-error" id="login-error"></div>
<input type="text" id="email" name="email">
<input type="password" id="password" name="password">
<button type="button" name="login" class="submit" data-url="login.php">Login</button>
<button type="button" name="forgot" class="submit" data-url="forgot.php">Forgot password?</button>
</form>
JQ:
$("#loginForm").on('click', '.submit', function (event) {
/* Stop form from submitting normally */
event.preventDefault();
/* Get some values from elements on the page: */
var values = $(this).closest('form').serialize();
/* Send the data using post and put the results in a div */
$.ajax({
url: $(this).data('url'),
/* here is echo var_dump($_POST); */
type: "post",
data: values,
success: function (data) {
$("#login-error").html(data);
},
error: function () {
$("#result").html('There is error while submit');
}
});
});
It will be a lot easier to check if you name the submit input and the button differently.
You currently have this set up like this:
<input type="submit" name="submit" value="Login">
<button type="submit" name="submit" value="Forgot password?">Forgot password?</button>
Try changing the name of the button to something like:
name="forgot"
then you can run a check on it such as
if (isset($_POST['submit'])){
stuff here
}
and a separate check for
if (isset($_POST['forgot'])){
stuff here
}
If there is not event in function then it will not prevent the submit function and by default get will be called and and $_POST will be empty for sure
Change
$("#loginForm").click(function(){
/* Stop form from submitting normally */
event.preventDefault();
To
$("#loginForm").click(function(event){
/* Stop form from submitting normally */
event.preventDefault();
Make one more change
data: values,
To
data:$("#loginForm").serialize(),
Remove one submit type there should be only one submit type make it type of button and call onbutton click functiuon to submit via ajax it will work same as submit.

Categories

Resources