Form not serializing - javascript

I've got a form which is loaded through ajax, and posted using ajax.
When try to send its data, nothing is added to post, here's a short version of code
<form id="userForm">
<input type="text" name="username" />
<button type="submit">Send</button>
</form>
Javascript:
(function($){
$.fn.ajaxForm = function() {
var $form = $(this);
$form.submit(function(event){
event.preventDefault();
$.ajax({
data: $form.serialize(),
type: 'post',
});
});
}
})(jQuery);
<script type="text/javascript">
$("#userForm").ajaxForm();
</script>
Everything works fine, request is sent, but $form.serialize() is empty

And i only had to ask.....
I've also added disabling of fields to the form after submitting which was the reason for the serialize not working. Removed that and it's now fine, sorry for bothering.

Related

Post variables to php file and load result on same page with ajax

I have tried searching quite a bit but can't seem to make anything work.
I am trying to make a form that sends info to a PHP file and displays the output of the PHP file on the same page.
What I have so far:
HTML:
<html>
<form id="form">
<input id="info" type="text" />
<input id="submit" type="submit" value="Check" />
</form>
<div id="result"></div>
</html>
JS:
<script type="text/javascript">
var info= $('#info').val();
var dataString = "info="+info;
$('#submit').click(function (){
$.ajax({
type: "POST",
url: "/api.php",
data: dataString,
success: function(res) {
$('#result').html(res);
}
});
});
</script>
PHP:
<?php
$url = '/api.php?&info='.$_POST['info'];
$reply = file_get_contents($url);
echo $reply;
?>
When I set the form action to api.php, I get the result I am looking for. Basically what I want is to see the same thing in the "result" div as I would see when the api.php is loaded.
I cannot get any solutions to work.
Your click event is not stopping the actual transaction of the page request to the server. To do so, simply add "return false;" to the end of your click function:
$('#submit').click(function (){
$.ajax({
type: "POST",
url: "/api.php",
data: dataString,
success: function(res) {
$('#result').html(res);
}
});
return false;
});
Additionally, you should update the type="submit" from the submit button to type="button" or (but not both) change .click( to .submit(
Thanks everyone for your help, I have it working now.
I was doing a few things wrong:
I was using single quotes in my php file for the URL and also for the $_POST[''] variables.
I needed to add return false; as Steve pointed out.
I did not have a "name" for the input elements, only an ID.
I think Your code evaluate dataString before it is filled with anything. Try to put this into function of $.ajax. The code below.
/* ... */
$('#submit').click(function (){
$.ajax({
var info= $('#info').val();
var dataString = "info="+info;
/* ... */

Prevent page reload and redirect on form submit ajax/jquery

I have looked through all the similar posts out there but nothing seems to help. This is what I have
HTML:
<section>
<form id="contact-form" action="" method="post">
<fieldset>
<input id="name" name="name" placeholder="Name" type="text" />
<input id="email" name="email" placeholder="Email" type="text" />
<textarea id="comments" name="comments" placeholder="Message"></textarea>
<div class="12u">
Send Message
Clear Form
</div>
<ul id="response"></ul>
</fieldset>
</form>
</section>
JavaScript/jQuery:
function sendForm() {
var name = $('input#name').val();
var email = $('input#email').val();
var comments = $('textarea#comments').val();
var formData = 'name=' + name + '&email=' + email + '&comments=' + comments;
$.ajax({
type: 'post',
url: 'js/sendEmail.php',
data: formData,
success: function(results) {
$('ul#response').html(results);
}
}); // end ajax
}
What I am unable to do is prevent the page refresh when the #form-button-submit is pressed. I tried return false; I tried preventDefault() and every combination including return false; inside the onClick. I also tried using input type="button" and type="submit" instead and same result. I can't solve this and it is driving be nuts. If at all possible I would rather use the hyperlink due to some design things.
I would really appreciate your help on this.
Modify the function like this:
function sendForm(e){
e.preventDefault();
}
And as comment mentions, pass the event:
onclick = sendForm(event);
Update 2:
$('#form-button-submit').on('click', function(e){
e.preventDefault();
var name = $('input#name').val(),
email = $('input#email').val(),
comments = $('textarea#comments').val(),
formData = 'name=' + name + '&email=' + email + '&comments=' + comments;
$.ajax({
type: 'post',
url: 'js/sendEmail.php',
data: formData,
success: function(results) {
$('ul#response').html(results);
}
});
});
function sendForm(){
// all your code
return false;
}
I was also bit engaged in finding solution to this problem, and so far the best working method I found was this-
Try using XHR to send request to any url, instead of $.ajax()...I know it sounds bit weird but try it out!
Example-
<form method="POST" enctype="multipart/form-data" id="test-form">
var testForm = document.getElementById('test-form');
testForm.onsubmit = function(event) {
event.preventDefault();
var request = new XMLHttpRequest();
// POST to any url
request.open('POST', some_url, false);
var formData = new FormData(document.getElementById('test-form'));
request.send(formData);
This would send your data successfully ...without page reload.
Have you tried using
function sendForm(event){
event.preventDefault();
}
Simple and Complete working code
<script>
$(document).ready(function() {
$("#contact-form").submit(function() {
$("#loading").show().fadeIn('slow');
$("#response").hide().fadeOut('slow');
var frm = $('#contact-form');
$.ajax({
type: frm.attr('method'),
url: 'url.php',
data: frm.serialize(),
success: function (data) {
$('#response').html(data);
$("#loading").hide().fadeOut('slow');
$("#response").slideDown();
}, error: function(jqXHR, textStatus, errorThrown){
console.log(" The following error occured: "+ textStatus, errorThrown );
} });
return false;
});
});
</script>
#loading could be an image or something to be shown when the form is processing, to use the code simply create a form with ID contact-form
Another way to avoid the form from being submitted is to place the button outside of the form. I had existing code that was working and created a new page based on the working code and wrote the html like this:
<form id="getPatientsForm">
Enter URL for patient server
<br/><br/>
<input name="forwardToUrl" type="hidden" value="/WEB-INF/jsp/patient/patientList.jsp" />
<input name="patientRootUrl" size="100"></input>
<br/><br/>
<button onclick="javascript:postGetPatientsForm();">Connect to Server</button>
</form>
This form cause the undesirable redirect described above. Changing the html to what is shown below fixed the problem.
<form id="getPatientsForm">
Enter URL for patient server
<br/><br/>
<input name="forwardToUrl" type="hidden" value="/WEB-INF/jsp/patient/patientList.jsp" />
<input name="patientRootUrl" size="100"></input>
<br/><br/>
</form>
<button onclick="javascript:postGetPatientsForm();">Connect to Server</button>
I expect anyone to understand my idea very well as it's a very simple idea.
give your required form itself an id or you can get it by any other way you prefer.
in the form input "submit" call an onclick method from your javascript file.
in this method make a variable refer to your from id the addEventListener on it and make a preventDefault method on "submit" not on "click".
To clarify that see this:
// element refers to the form DOM after you got it in a variable called element for example:
element.addEventListener('submit', (e) => {
e.preventDefault();
// rest of your code goes here
});
The idea in brief is to deal with the form by submit event after dealing with submit button by click event.
Whatever is your needs inside this method, it will work now without refresh :)
Just be sure to deal with ajax in the right way and you will be done.
Of course it will work only with forms.
The way I approached this: I removed the entire form tag and placed all the form elements such as input, textarea tags inside a div and used one button to call a javascript function. Like this:
<div id="myform">
<textarea name="textarea" class="form-control">Hello World</textarea>
<button type="submit" class="btn btn-primary"
onclick="javascript:sendRequest()">Save
changes</button>
<div>
Javascript:
function sendRequest() {
$.ajax({
type: "POST",
url: "/some/url/edit/",
data: {
data: $("#myform textarea").val()
},
success: function (data, status, jqXHR) {
console.log(data);
if (data == 'success') {
$(`#mymodal`).modal('hide');
}
}
});
return true;
}
I thought why use a form when we are sending the actual request using AJAX. This approach may need extra effort to do things like resetting the form elements but it works for me.
Note:
The above answers are more elegant than this but my use case was a little different. My webpage had many forms and I didn't think registering event listeners to every submit button was a good way to go. So, I made each submit button call the sendRequest() function.

Jquery ajax simple form not working

I'm sending form data to a PHP file via AJAX, using jquery I hoped I could send the data easily seeing as it's only one text box etc. On submit click event the form data should be serialised and sent to submit.php, then I should get an alert from the php file with the response. Why doesn't it work?
Thanks.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script>
$('#submit').click(function (e) {
e.preventDefault();
$.ajax({type:'POST', url: 'submit.php', data:$('#myform').serialize(), success:
function(response) {
alert(response);
}});
});
</script>
Then the HTML:
<form id="myform" >
<input type="text" name="content" value="button should be on same line" /><input
type="submit" class="button" value="Submit" id="submit" />
</form>
You haven't initalized the DOM ?
$(document).ready(function(){
// do your work here
});
EDIT :
Try this:
$("#submit").live("click", function (e) {
e.preventDefault();
$.ajax({type:'POST', url: 'submit.php', data:$('#myform').serialize(), success:
function(response) {
alert(response);
}});
});
});
First, try to determine that the form is submitting correctly. try submitting to
url: '/submit.php'
instead, as that may not have been the correct path.
Second, try sending the value unserialized and see if you get a correct.

Posting form data Jquery

I am trying to build a mobile app but am having some trouble getting the basics of Jquery/Javascript.
I am trying to make it so I can type in any value I want into the input field and then post it, it would post above and allow me to type more into the input field and it would post above the last post.
Here is my code so far. Stumped where to go next or if I am going in the right direction.
<!DOCTYPE HTML>
<HTML>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$('#commentForm').submit(function(){ //listen for submit event
$.each(params, function(i,param){
$('<input />').attr('type', 'show')
.attr('value', param.value)
.appendTo('#commentForm');
});
return true;
});
</script>
<BODY>
<form id="commentForm" method="POST">
<textarea cols="30" rows="6" name="comment" title="Enter a comment">
</textarea>
<input type="submit" value="Post"/>
<input type="reset" value="Reset"/>
</form>
<div id="box">
</div>
</BODY>
</HTML>
Give the submit button an id called "submit"
function onSuccess(data, status) {
data = $.trim(data);
//make a div with id "notification" before running this code
$("#notification").html(data);
$.mobile.hidePageLoadingMsg(); //used on jquery mobile to hide a loader
}
function onError(data, status) {
data = $.trim(data);
$("#notification").html(data);
$.mobile.hidePageLoadingMsg(); //used on jquery mobile to hide a loader
}
$("#submit").click(function() {
$.mobile.showPageLoadingMsg(); //used on jquery mobile to show a loader
var formData = $("#commentForm").serialize(); //get all data from form
//do the POST thingies
$.ajax({
type: "POST",
url: "url_to_your_php_interpreter",
cache: false,
data: formData,
success: onSuccess,
error: onError
});
return false;
});
I'm using this script to login an user.
PS: everything you will "echo" from php interpreter will be shown on div with id "notification" wich you will (probably) create

Is there a way in JavaScript to retrieve the form data that *would* be sent with a form without submitting it?

If I have an HTML form, let’s say...
<form id='myform'>
<input type='hidden' name='x' value='y'>
<input type='text' name='something' value='Type something in here.'>
<input type='submit' value='Submit'>
</form>
... and then I use jQuery to respond to the form submission event, e.g.
$('#myform').submit(function() {
...
return false;
});
Now suppose I want to submit the form as an AJAX call instead of actually submitting it the “traditional” way (as a new page). Is there an easy way to get a JS object containing the data that would be sent, which I can pass into $.post()? So in the above example it would look something like...
{
x: 'y',
something: 'Type something in here.'
}
or do I have to bake my own?
See the serialize() method.
$('#myform').submit(function() {
jQuery.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function () {
//
}
});
return false;
});
As you're already using jQuery, use jQuery.serialize().
$('#myform').submit(function() {
var $form = $(this);
var data = $form.serialize();
// ...
});

Categories

Resources