not able to submit form without page reloading - javascript

I have the following code that i wish to use to submit form without reloading the page, but it reloads the entire page and when checked in console the script.php page is also not getting executed.
Code on index.php page
<script>
$(function() {
$(".submit").click(function() {
var name = $("#name").val();
var dataString = 'name=' + name;
console.log(dataString);
$.ajax({
type: "POST",
url: "script.php",
data: dataString,
success: function() {
$('#result').html(response);
}
});
return false;
});
});
</script>
<form method="post" name="form">
<input id="name" name="name" type="text" />
<input type="submit" value="Submit" class="submit" />
</form>
<div id="result"></div>
code on script.php page
<?php
$name=$_POST['name'];
echo $name;
?>
Can anyone please tell how i can submit the form without reloading the page and also display the result from script.php page on index.php page

update your function. pass event object in function. and use event.preventDefault() to prevent default submit action.
$(".submit").click(function(e) {
e.preventDefault();

try this
<script>
$(function() {
$(".submit").click(function(event) {
event.preventDefault();
var name = $("#name").val();
var dataString = 'name=' + name;
console.log(dataString);
$.ajax({
type: "POST",
url: "script.php",
data: dataString,
success: function() {
$('#result').html(response);
}
});
return false;
});
});
OR
<input type="button" class="submit" />Submit

You need to send the data from the script.php page back to your index.php page. Swich out the little bit of ajax for this:
$.ajax({
type: "POST",
url: "script.php",
data: "datastring",
dataType: "json",
success: function(dataType){
$("#result").html(dataType);
}
});
In your script.php:
<?php
$name=$_POST['name'];
echo json_encode($name);
?>

Do not mix form submit and button click.
If you are a click event of button then use type="button" and if you are doing $("form").submit() then use type="submit".
Also check for
$(".submit").click(function(e) {
e.preventDefault();
and check your ajax post data , do
$.ajax({
type: "POST",
url: "script.php",
//changes made here
data: { name: $("#name").val()},
//changes made here. you have not written response
success: function(response) {
$('#result').html(response);
}
});

Instead of listening to the input's click event, you should listen to the form's submit.
<script>
$(function() {
$("#name-form").on('submit', function(e) {
e.preventDefault(); // prevent form submission
var name = $("#name").val();
var dataString = 'name=' + name;
console.log(dataString);
$.ajax({
type: "POST",
url: "script.php",
data: dataString,
success: function(response) {
$('#result').html(response);
}
});
});
});
</script>
<form id="name-form" method="post" name="form">
<input id="name" name="name" type="text" />
<input type="submit" value="Submit" class="submit" />
</form>
<div id="result"></div>

Related

how to clear form after submit the form and pass the data to php file without reloading page

how to clear form after submit the form and pass the data to php file without reloading page...the form data is pass the php file and it stored the data base.but i was unable to clear the form data after submit the form.if i reset the form using javascrip but data not pass the data base.if i pass the data to php the form is not clear.is there a way for me achive both target?thank you..
here my snipt code...
<iframe name="votar" style="display:none;"></iframe>
<form action="confirm.php" id="sfm" method="POST" target="votar">
<input type="text" placeholder="Name" name="name" value="" required/>
<input type="submit" value="Submit My Project " />
</form>
Using AJAX you can do this.
$('#submitBtn').click(function () {
$.ajax({
url: 'confirm.php',
data: $('#sfm').serialize(),
type: "post",
success: function (data) {
$('input[type="text"]').val('');
}
});
return false;
});
you can try this
in index.php
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'get',
url: 'ajax.php',
data: $('form').serialize(),
success: function (data) {
$('#name').val('');
alert('data');
//your return value in data
}
});
});
});
</script>
</head>
<body>
<form action="ajax.php" id="sfm" method="POST" target="votar">
<input type="text" placeholder="Name" name="name" id="name" value="" required/>
<input type="submit" value="Submit My Project " />
</form>
</body>
</html>
and in ajax.php
<?php
$name = $_GET['name'];
//do what you want to do using name
echo "what you need to return";
Have you thought about to use Ajax to handle the form submit?
Form submit with AJAX passing form data to PHP without page refresh
try making $_POST array empty after submitting and saving the form
$_POST='';
After getting success response you can clear form input
$('#sfm').submit(function () {
var form = $(this);
$.ajax({
url: 'phpfile.php',
data: form.serialize(),
type: "POST",
success: function (data) {
$('input[type="text"]').val('');
}
});
return false;
});
You can do like this, first get form inputs value and then reset
You can also able to reset after success response
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
var that = $(this);
var params = that.serialize();
that.get(0).reset();
console.log(params);
$.ajax({
type: 'GET',
url: 'submit.php',
data: params,
success: function (data) {
console.log(data);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="confirm.php" id="sfm" method="POST" target="votar">
<input type="text" placeholder="Name" name="name" value="" required/>
<input type="submit" value="Submit My Project " />
</form>
SERVER SIDE
<?php
$name = $_GET['name'];
echo 'success';
exit();
?>

Response from Servlet page is shown in new page

I am using Ajax and jQuery to submit a dynamic form.
It works fine, but the response from Servlet is shown in a new page.
function call(formid) {
alert(formid);
var form = $(formid); // id of form tag
form.submit(function () {
$.ajax({
type: form.attr('method'), //post method
url: form.attr('action'), //ajaxformexample url
data: form.serialize(), // serialize input data values
success: function (data) {
var result=data;
$('#content').html(result); //showing result
}
});
return false; // not refreshing page
});
}
How I can show response from Servlet in same page?
(out.println("<br/>Massage = "+message+"<br/>"););
You are experiencing this because you are not stopping what a form submit does:
So, according to .submit( handler ) change your line:
form.submit(function () {
to:
form.submit(function (e) {
e.preventDefault(); // stop form submit and do your ajax call
UPDATE
According to your comment I suggest you to try the following code:
function submitFrm(obj, e) {
e.preventDefault();
var form = $(obj).closest('form'); // id of form tag related to the current button
var formid = form.attr('id');
alert(formid);
$.ajax({
type: form.attr('method'), //post method
url: form.attr('action'), //ajaxformexample url
data: form.serialize(), // serialize input data values
success: function (data) {
var result=data;
$('#content').html(result); //showing result
}
});
}
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<form id="formid">
First name:<br>
<input type="text" name="firstname"><br>
Last name:<br>
<input type="text" name="lastname">
<input type="submit" value="Submit" onclick="submitFrm(this, event);">
</form>

Ajax call won't work when onclick is present

I am submitting a form with a textarea in it that will get saved by a php script. I am doing this via ajax (below) but also calling onclick another javascript function. The ajax call won't work if the onclick is there, while it will when it's not there. What should I do?
<script type="text/javascript">
$("document").ready(function(){
$(".newcomment").submit(function(){
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "newcomment.php",
data: data,
});
return false;
});
});
</script>
My submit button is this:
<input type="submit" id="button" onclick="return hideform()" name="submit" value="Salva">
Try to merge the hideform() with submit and remove the inline-event onClick.
HTML :
<input type="submit" id="button" onclick="return hideform()" name="submit" value="Salva">
JS :
$("document").ready(function(){
$(".newcomment").submit(function(){
hideform(); <<---- HIDE THE FORM HERE
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "newcomment.php",
data: data,
});
return false;
});
});
Hope this helps.

Disabling button on ajax submit

I have this button that I want to disable when my ajax is running, and then being enabled again once it's done.
My HTML:
<form name="send" class="stacked form-send-disable" id="form">
<label for="senderID">Your phone number here (senderID)</label>
<input type="tel" name="senderID" id="senderID" autofocus="on" class="input-1-2" placeholder="Your number" maxlength="9">
<label class="error" id="senderID_error" for="senderID">Please enter your own number here.</label>
<label for="recipient" id="recipient_label">Your recipient(s)</label>
<input type="text" name="recipient" id="recipient" class="input-1" maxlength="50" placeholder="e.g 748930493 - add multiple numbers by using a comma ' , '.">
<label class="error" id="recipient_error" for="recipient">You need to enter at least one number here.</label>
<label for="message">Write your message</label>
<textarea type="text" name="message" class="input-1" placeholder="(Write something clever..)" id="message"></textarea>
<label class="error" for="message" id="message_error">You can't send empty messages.</label>
<input type="submit" name="submit" class="button btn btn-green block disabled-btn" id="submit_btn" value="Send the message(s)">
</form>
ajax:
<---- Some form validation going on up here ------>
var dataString = 'recipient=' + recipient + '&message=' + message + '&senderID=' + senderID;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "/index.php/sms/sender/",
data: dataString,
success: function() {
$('#send-message').append("<div id='feedback'></div>");
$('#feedback').html("<p><i class='fa fa-check fa-2x'></i> Your message has been succesfully sent!</p>")
.append("")
.hide()
.fadeIn()
.delay(4000)
.fadeOut();
$.ajax({
type: "POST",
url: "/index.php/pipit/message_sent",
data: dataString,
});
}
});
return false;
});
I tried to do the following in my document:
Jquery:
$('#form').submit(function(){
$('input[type=submit]', this).attr('disabled', 'disabled');
});
But nothing happens. I guess I have to somehow call this within the ajax, so that it applies to the button that way?
Thanks in advance.
UPDATE
$(':submit', this).prop('disabled', true);
$.ajax({
type: "POST",
url: "/index.php/sms/sender/",
data: dataString,
success: function() {
$('#send-message').append("<div id='feedback'></div>");
$('#feedback').html("<p><i class='fa fa-check fa-2x'></i> Your message has been succesfully sent!</p>")
.append("")
.hide()
.fadeIn()
.delay(4000)
.fadeOut();
$.ajax({
type: "POST",
url: "/index.php/pipit/message_sent",
data: dataString,
}).always(function(){$(':submit', this).prop('disabled', false);});;
}
I updated with the above code (big thanks to A.Wolff), and my ajax request still works, however there is no change on the button, which i assume is because of lack of css for this particular state of the button, how do I go about this?
Thanks to the other replies, i will try them out.
I made a working demo that disables the form whilst the ajax request is happening. I hope its of some use. See: http://jsfiddle.net/EWkpR/
$("#form").on("submit", function(event) {
//stop the default submission:
event.preventDefault();
//create an alias to this form
$form = $(this);
//create the feedback element
$feedback = $("<div id='feedback'>Please wait...</div>");
$form.before($feedback);
//validate the form:
var valid = true;
/*[some form validation here]*/
//use jQuery's serialize to build the form submission params:
var dataString = $(this).serialize();
console.log(dataString);
//check if invalid
if(!valid){
//not valid. tell the user
$feedback.html("<p>Some message about invalid fields!</p>");
} else {
//valid.
$form.disable();//disable the form;
//do the ajax
$.ajax({
type: "POST",
url: "/index.php/sms/sender/",
data: dataString,
success: function() {
$feedback
.html("<p><i class='fa fa-check fa-2x'></i> Your message has been succesfully sent!</p>")
.fadeIn()
.delay(4000)
.fadeOut("normal",
function(){$form.enable();}//callback to fade the form back in
);
$.ajax({
type: "POST",
url: "/index.php/pipit/message_sent",
data: dataString,
});
}
});
}
return false;
});
//plugin function to disable form fields
$.fn.disable = function(){
this.fadeTo(1,.5);
this.find("input").attr("disabled", true);
};
//plugin function to enable form fields
$.fn.enable = function(){
this.fadeTo(1,1);
this.find("input").removeAttr("disabled");
};
You can set the button as disabled before the AJAX runs and re-enable it once the ajax has completed.
$.ajax({
beforeSend: function() {
$("input[type=submit]", $("#form")).attr("disabled", "disabled");
},
...
complete: function () {
$("input[type=submit]", $("#form")).removeAttr("disabled");
}
});
Edit: I notice there is a class on the button disabled-btn if this needs to be added and removed as the button is disabled/re-enabled then you can do this by chaining the following to the above:
.addClass("disabled-btn");
...
.removeClass("disabled-btn");
I would assume if this is the case then the class should be removed from the actual element to start with.
You could use:
//using allias for nested ajax:
var _self = this;
$(':submit', _self ).prop('disabled', true);
//your nested ajax request
$.ajax(...).always(function(){$(':submit', _self ).prop('disabled', false);});

HTML/JQuery: Button submits once when it shouldn't at all

I'm using jQuery to allow the form to submit, so I don't want the form to submit on it's own.
Here's my form:
<form class="navbar-form navbar-right" id="signform">
<div class="form-group">
<input type="text" placeholder="Username" class="form-control">
</div>
<div class="form-group">
<input type="password" placeholder="Password" class="form-control">
</div>
<button id="signbtn" class="btn btn-success">Sign in</button>
</form>
Here's my JQuery code:
var signingIn = false;
$(document).ready(function() {
$('#signbtn').click(function() {
if (signingIn) return;
signingIn = true;
var img = $('<img id="loader" style="padding-left: 10px;" src="loader.gif"/>');
$(this).after(img);
var data = $('signform').serialize();
$.ajax({
url: '/logs',
type: 'post',
data: data,
done: function() {
$('#loader').remove();
alert('success');
}
});
});
});
Now when I go to the url: website.com/index.html and click Sign in, it refreshes the page (what I don't want at all) and goes to website.com/index.html? - Now when I click it again, nothing happens (exactly what I want all the time so my added elements through jQuery isn't lost).
You want to use jQuery ajax call like so:
$(document).on('click','button#signbtn', function(){
var $form = $('form#signform');
var url = $form.attr('action');
$.ajax({
type: "POST",
enctype: 'mutipart/form-data',
url: url,
data: $form.serialize(), // serializes the form's elements.
success: function(data){// whatever you want your code to do on success}
})
return false; // avoid to execute the actual submit of the form.
});
$(function() {
$( '#signform' ).submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: $(this).attr( 'action' ),
data: $(this).serialize(),
success: function(result) {
// Do something on success
}
});
});
});

Categories

Resources