Posting form data Jquery - javascript

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

Related

Get input field value in same page without refreshing page php

I am trying to send my input value to a code segment in the same page, but it doesn't work. Right now, I can't get the value in the code segment. This is my current code:
<?php
if ($section == 'codesegment') {
if ($_GET['hour']) {
echo $_GET['hour'];
//here i want call my method to update db with this value of hour...
}
if ($section == 'viewsegment') {
?>
<form id="my_form" action="#" method="Get">
<input name="hour" id="hour" type="text" />
<input id="submit_form" type="submit" value="Submit" />
</form>
<script>
var submit_button = $('#submit_form');
submit_button.click(function() {
var hour = $('#hour').val();
var data = '&hour=' + hour;
$.ajax({
type: 'GET',
url: '',
data: data,
success:function(html){
update_div.html(html);
}
});
});
</script>
Any advice?
If you want to get the value without refresh your page you have to use javascript, you can try this:
$('#hour').onchange = function () {
//type your code here
}
By the way, your php script is server side, according to this, you can't use the value without post/submit/refresh
Whenever you are using
<input type="submit">
it sends the data to the action of the form, so whenever you are clicking the submit button before the onclick function gets called, it sends the data to the action and the page gets refreshed. So instead of using input element try something like this
<button id="submit_form"> Submit </button>
two things,
1. as yesh said you need to change the input submit to button type=button and add an onClick function on that button. Or you can give a the javascript function inside a function line function sampleFn(){} and call this function onSubmit of form.
2. You need to give the javascript inside document.ready function since the script execute before the dom loading and the var submit_button = $('#submit_form'); may not found. In that case there will be an error in the browser console.
Try to add errors in the post since it will help to debug easily.
It's not possible to do on the same page. you can write ajax call to another page with data where you can do the functions with the data.
Something like this
//form.php
<form id="hour-form">
<input type="text" name="hour" id="hour">
<input type="submit" name="hour-submit" >
</form>
<script type="text/javascript">
$(document).ready(function(){
$(document).on('submit', '#hour-form', function(e){
e.preventDefault();
var data = $('#hour').val();
$.ajax({
url: "post.php",
method: "POST",
data: {'hour':data},
success: function(data)
{
//if you want to do some js functions
if(data == "success")
{
alert("Data Saved");
}
}
});
});
});
//post.php
if(isset($_POST['hour']))
{
// do the php functions
echo "success";
}

JavaScript/Ajax - How to run one PHP script before posting form to another one

I am almost at my wit's end trying to figure out why my code is not working.
Here is what I am trying to do:
1) Accept several variables in a form (myform).
2) Using an onsubmit, I want to use pass one or more of those variables to a script (process_info).
3) After process_info has executed, the form should be posted to the form's action URL ('save_info.php').
As you can see in the code below, I have tried several things:
Test 1: This simple alert is shown and the form is submitted to save_info.php.
Test 2: I copied and modified this jQuery script from another page on this site. No matter what I do, the script does not run. I know this because no alert message is shown.
Test 3: After removing the jQuery(document).ready statement from Test 2, the senddata function runs. Although it runs the process_info script, the form does not get posted to save_info.
<html>
<head>
<title>Form Test</title>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javaScript">
/* Test 1: this works - form is submitted to the action URL
function senddata() { alert('here'); }
*/
/* Test 2: this does not run (no alert shown) - form is submitted to the action URL */
jQuery(document).ready(function() {
function senddata() {
var formdata = jQuery("#myform").serialize();
var decoded = decodeURIComponent(formdata);
strip = decoded.replace(/[\[\]]/g, "_");
// alert(strip);
jQuery.ajax({
type: "POST",
url: 'process_info.php',
data: strip,
success: function(){ alert('success'); },
error: function(){ alert('failure'); },
complete: function(){
jQuery("#myform").submit(); //submit the form after ajax completes
}
});
return false; //stop the form from initially submitting
}
});
/* Test 3: this runs and the AJAX URL is executed, "success" is displayed - form is NOT submitted to the action URL
function senddata() {
var formdata = jQuery("#myform").serialize();
var decoded = decodeURIComponent(formdata);
strip = decoded.replace(/[\[\]]/g, "_");
// alert(strip);
jQuery.ajax({
type: "POST",
url: 'process_info.php',
data: strip,
success: function(){ alert('success'); },
error: function(){ alert('failure'); },
complete: function(){
jQuery("#myform").submit(); //submit the form after ajax completes
}
});
return false; //stop the form from initially submitting
}
*/
</script>
</head>
<body>
<form name="myform" id="myform" onsubmit="return senddata()" action="save_info.php" method="post" enctype="multipart/form-data">
<input type="text" name="id" />
<input type="text" name="last" />
<input type="submit" value="send" />
</form>
</body>
</html>
I assume that what I am trying to do is actually possible. What am I doing wrong?
ok, I have edited your code in a way that it works and I'll explain a few changes after the code.
<html>
<head>
<title>Form Test</title>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javaScript">
/* Test 2: this does not run (no alert shown) - form is submitted to the action URL */
jQuery(document).ready(function(){
$("#myform").submit(function(event){
event.preventDefault();
var formdata = jQuery("#myform").serialize();
var decoded = decodeURIComponent(formdata);
strip = decoded.replace(/[\[\]]/g, "_");
// alert(strip);
jQuery.ajax({
type: "POST",
url: 'process_info.php',
data: strip,
success: function(){ alert('success'); },
error: function(){ alert('failure'); },
complete: function(){
jQuery("#myform")[0].submit(); //submit the form after ajax completes
}
});
return false; //stop the form from initially submitting
});
});
</script>
</head>
<body>
<form name="myform" id="myform" action="save_info.php" method="post" enctype="multipart/form-data">
<input type="text" name="id" />
<input type="text" name="last" />
<input type="submit" value="send" />
</form>
</body>
</html>
So, first I have removed onsubmit from the <form> element in the html
Then changed the function the same as you did in your comment.
The last trick is that if I wanted to use jQuery("#myform").submit(); in the complete section of the ajax it would add another listener for the form submit event and would call the function again and again and again.
So I had to access the HTML form element directly and call the submit for it, that's the trick as you can see jQuery("#myform")[0].submit();

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.

How to check username and password with database to display error message?

I created a login page(HTML) in dynamic project. I want to check username and password with mysql database and display error message on the same page if username or password are incorrect.
I don't want to use servlet here to display the error page because I want to display error message instead of error page.
How can I achieve this in dynamic webproject.
Can I use javascript, jQuery, JSP, or any combination of these?
I am not familiar with JSP but here is an overview of what you need:
index.html
<!DOCTYPE HTML>
<html>
<head>
<title>Web Form</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('form').on('submit', function(e) {
// don't let the browser submit the form
e.preventDefault();
// send form data to JSP page
$.ajax({
url: 'process.jsp',
async: true,
cache: false,
type: 'POST',
data: $(this).serialize(),
dataType: 'html',
success: function(data) {
// place message in error box
$('#error_box').html(data);
// if "Success" then redirect if you would like
if(data === 'Success!'){
// window.location = 'some other page/website';
}
}
});
});
});
</script>
</head>
<body>
<form method="POST" action="process.jsp">
<input type="text" name="username" />
<input type="password" name="password" />
<input type="submit" value="submit" />
</form>
<div id="error_box"></div>
</body>
</html>
process.jsp
// I don't know JSP
// use the POST values and check your DB
// Upon success/failure just echo the message
// <%='Success!'%>
// <%='Failed!'%>

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.

Categories

Resources