JQuery Serilize Data Input Is Empty - javascript

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();
}

Related

submit form with button outside form using ajax

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>

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.

show confirmation modal dialog after form submission

I have a form and I need it to do 2 things once the submit button is clicked:
I need the form data to be processed in the acknowledge.php that I have created.
I need the modal dialog to display confirmation.
My form:
<form class="quote-form" method="post" action="acknowledge.php">
<div class="form-row">
<label>
<span>Full Name</span>
<input type="text" name="name">
</label>
</div>
<div class="form-row">
<label>
<span>Email</span>
<input type="email" name="email">
</label>
</div>
<div class="form-row">
<label>
<span>Phone</span>
<input type="number" name="phone">
</label>
</div>
<div class="form-row">
<label>
<span>Nature of Enquiry</span>
<select name="enquiry">
<option selected>General Enquiry</option>
<option>Logo Design</option>
<option>Web Design</option>
<option>Branding</option>
<option>Social Media</option>
<option>Email/Web Hosting</option>
</select>
</label>
</div>
<div class="form-row">
<label>
<span>Message</span>
<textarea name="message"></textarea>
</label>
</div>
<div class="form-row">
<button type="button" name="send">Get A Quote</button>
</div>
</form>
I'm new to Javascript and AJAX but I have copied some code from some similar threads and tried to customize it to my site
<script type="text/javascript">
$(".quote-form").submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
data: $(".quote-form").serialize(),
url: 'url',
success: function(data) {
$("#myModal").modal("show");
}
});
return false;
});
});
</script>
<!--Modal container-->
<div id="myModal" class="modal">
<!-- Modal content-->
<div class="modal-content">
<span class="close">x</span>
<p>Some text in the Modal..</p>
</div>
</div>
When the submit button is clicked nothing happens. Even the acknowledge.php does not execute. What am I doing wrong?
you need to wrap your code in a document.ready() function:
<script type="text/javascript">
$(function(){
$(".quote-form").submit(function(e){
e.preventDefault();
$.ajax({
type : 'POST',
data: $(".quote-form").serialize(),
url : 'url',
success: function(data) {
$("#myModal").modal("show");
}
});
return false;
});
});
</script>
UPDATE
you need to change the type of your button to submit like this
<button type="submit" name="send">Get A Quote</button>
A number of things that have been holding you up:
In your javascript, you have a trailing }); right at the end.
Your button is doing nothing to trigger the submit event in the javascript. You should alter the button or use a proper submit input. Or use type="submit".
You're not doing anything with data in your success callback. So when the modal opens, nothing else happens.
Your URL in the AJAX request is not set. You could use this.action to use the form's action URL here.
I've made some changes that you can preview in my fiddle.
There are some parts of the fiddle that you should ignore, such as the ajax url and data options. Those should be something like:
$.ajax({
type: 'POST',
url: this.action,
data: $(this).serialize(),
//...
});
What we obviously do not know now is whether you have included your dependency scripts like jQuery and bootstrap into your page.
For example: <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> is the bootstrap javascript.
Make sure that jQuery is above bootstrap, or bootstrap will fail to load as it depends on jQuery. You may need to use the bootstrap CSS as well.
Lastly, you need to check that your action in the form is the correct URL, and that the data in your form that is sent is processed and echoed back as HTML.
You will also want to go to the bootstrap documentation, get a better example of the modal, and check out the forms area to spruce up this form.
You could use developer tools in your browser and note any errors thrown by javascript in the console if you still have problems. (Ctrl+Shift+I).
You didn't need to wrap anything in a document ready.
You doing two things wrong
First you need to wrap your code with document.ready
$(function(){
});
Then you need to fix your url
var form = $(".quote-form");
$.ajax({
type : 'POST',
data: form .serialize(),
url : form.attr('action'),
success: function(data) {
$("#myModal").modal("show");
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});

How to submit forms input values using post to server side script

I have a lot of buttons, each opens its form . How do I get the input value of form opened at the moment, and post it on my server, like post("/addOrders", valueOfinputs)?
https://jsfiddle.net/ave6uvez/21/
<div class="rows">
<div class="row">
<button class="open">Buy</button>
<form id="myform" action="/index" method="post">
<div class="form-group">
<label for="exampleInputEmail1">Name</label>
<input type="namee" name ="name" >
</div>
<div class="form-group">
<label for="exampleInputPassword1">Phone</label>
<input type="phone" name = "phone" >
</div>
<button class="ave" >Close</button>
<INPUT type="submit" id = "submit" class = "close" value="Submit">
<!---- <button id="submit" class="close"></button>-->
</form>
</div>
</div>
try this,
$("#submit").click(function(e){
$.post("/addOrders",$("#myForm").serialize());
return null;
})
.serialize() will put all form elements data into the request
Also you need to give different id for different Forms submit button and you have to do the above code for each submit button
Hope this works for you.
This is a simple reference:
// this is the id of the forms, set the form ids accordingly.
$("#idForm").submit(function(e) {
var url = "path/to/your/script.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#idForm").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});

Error sending a form via AJAX

I am very new to jQuery and I'm looking for an explanation as to why this code does not seem to work. I think it is something with the "action" not sure. Can someone help me understand my mistake here. thanks
<script src="/jquery.validationEngine.js"></script>
<script>
$("#contact_body").submit(function(e) {
e.preventDefault(); // Prevents the page from refreshing
var $this = $(this); // `this` refers to the current form element
if ($("#contact_body").validationEngine('validate')) {
//Post Data to Node Server
$.post(
$this.attr("action"), // Gets the URL to sent the post to
$this.serialize(), // Serializes form data in standard format
function(data) { /** code to handle response **/ },
"json" // The format the response should be in
);
//Notify User That the Email Was Sent to the Server & Thanks!
//$('#contactThanksModal').modal('show');
$('#contactModal').modal('hide');
alert("success");
}
else {
//handle Invalid Email Format Error
alert("error");
}
});
</script>
<!--pop up contact form -->
<div id="contact" class="modal hide fade in" style="display: none;">
<div class="modal-header">
<a class="close" data-dismiss="modal">x</a>
<h3>Send us a message</h3>
</div>
<div class="modal-body">
<form id="contact_body"class="contact_body" name="contact_body" action="/contact">
<label class="label" for="form_name">Your Name</label><br>
<input type="text" name="form_name" id="form_name" class="input-xlarge"><br>
<label class="label" for="form_email">Your E-mail</label><br>
<input type="form_email" name="form_email" class="input-xlarge"><br>
<label class="label" for="form_msg">Enter a Message</label><br>
<textarea name="form_msg" class="input-xlarge"></textarea>
</form>
</div>
<div class="modal-footer">
<input class="btn btn-success" type="submit" value="Send!" id="submit">
Nah.
</div>
<!-- <div id="thanks"><p><a data-toggle="modal" href="#contact" class="btn btn-primary btn-large">Modal powers, activate!</a></p></div> -->
You need to wrap your JQuery scripts in a
$(document).ready(function() {
...your_code_here...
});
This will then wait for the whole document to load before trying to attach events to objects.
Without this you may be trying to bind events to objects that have yet to be "created".
You need to put your code in a document ready handler:
<script src="/jquery.validationEngine.js"></script>
<script>
$(function() {
$("#contact_body").submit(function(e) {
// your code...
});
});
</script>
Your code is currently trying to add the submit() handler before the element exists in the DOM.

Categories

Resources