I have a form with
<form id=myform onsubmit=return validate();>
<input type=text id=name name=name>
</form>
In my javascript file I have
function validate(){
$.ajax({
dataType: 'json',
url: app.url.prefix,
method: 'POST',
data: {service: 'manage', met: 1, name: name },
success: function (data) {
if (data.exists){
return false;
}
}
});
return true;
}
This Ajax code check if the returned data has value especially the data.exists. I would like to prevent submit form based on the value of exists.
This
if (data.exists){
return false;
}
does not really work.
Your problem occurs because of async ajax function call, it returns true before ajax data returns.
I haven't checked it, But you can try something like this:
function validate(){
var self = this;
self.preventDefault();
$.ajax({
dataType: 'json',
url: app.url.prefix,
method: 'POST',
data: {service: 'manage', met: 1, name: name },
success: function (data) {
if (!data.exists){
self.submit();
}
}
});
return false;
}
$('#myform').submit(function() {
return false;
});
This should do the trick, now the form won't reload the page on pressing enter or a button.
EDIT:
Your form is also missing double-quotes
<form id="myform" onsubmit="return validate();">
<input type="text" id="name" name="name">
</form>
Solution:
I have changed my HTML and I have added onclick event than onsubmit
<form id="myform">
<input type="text" id="name" name="name">
<button type="submit" id="button" onclick="validate();">
</form>
Also in Javascript
I prevent the submit here
$("#button").on("click",function(event){
event.preventDefault();
});
Here is my function to check if not exists data so then submit form
function validate(){
$.ajax({
dataType: 'json',
url: app.url.prefix,
method: 'POST',
data: {service: 'manage', met: 1, name: name },
success: function (data) {
if (!data.exists){
$('#myform').submit();
}
}
});
Related
How can I send input values through AJAX on button click? My code is below. Thanks in advance.
while
{
<form class="commentform">
<input type="hidden" class="proid" name="proid" value="<?=$rr['id']?>">
<input type="text" class="form-control" name="comval" placeholder="Write a comment.." autocomplete="off">
<button class="btn btn-post" type="button">Post</button>
</div>
</form>
}
$(document).ready(function() {
$(document).on('click', '.btn-post', function(){
var thePostID = $(this).val;
$.ajax({
url: 'fetch_comments.php',
data: { postID: thePostID },
type: 'POST',
success: function() {
alert(data);
}
});
Firstly, the correct method is $(this).val(), not just $(this).val.
Secondly, you can simplify your code by getting the data from the closest form element using serialize(). Try this:
$(document).on('click', '.btn-post', function() {
var $form = $(this).closest('form');
$.ajax({
url: 'fetch_comments.php',
data: $form.serialize(),
type: 'POST',
success: function() {
alert(data);
}
});
});
$("form").serialize();
Serialize a form to a query string, that could be sent to a server in an Ajax request.
In jQuery, when a function got success a form getting build. Now when I submit this form it gives all data except inputType='file'. I can't get it why this is happening
here is my jQuery code when form is creating
content += '<form method="POST" action="'+formURL+'" id="data" enctype="multipart/form-data">'+
'<input type="text" name="album_id" value="'+id+'">'+
'<input type="text" name="user_id" value="'+user_id+'">'+
'<input type="file" name="image" id="image_upload">'+
'<input type="submit" value="Submit">'+
'</form>';
Here form is getting submit
$("form#data").submit(function() {
var formData = new FormData($(this)[0]);
$.post($(this).attr("action"), formData, function(data) {
console.log(data);
});
return false;
});
I am sending this form data in a controller in cakephp.
In controller I get only input field data with text type only. But I need file type too.
please use jquery.form.js for file upload.
http://malsup.com/jquery/form/
<form method="POST" action="'+formURL+'" id="data" enctype="multipart/form-data" onsubmit="return submit_form();" >
function submit_form(){
$('#data').ajaxSubmit({
method:'post',
dataType:'json',
success: function(resp){
}
});
return false;
}
You can change jquery function like this
$("form#data").submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: $(this).attr("action"),
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
Been looking at some tutorials, since I'm not quite sure how this works (which is the reason to why I'm here: my script is not working as it should). Anyway, what I'm trying to do is to insert data into my database using a PHP file called shoutboxform.php BUT since I plan to use it as some sort of a chat/shoutbox, I don't want it to reload the page when it submits the form.
jQuery:
$(document).ready(function() {
$(document).on('submit', 'form#shoutboxform', function () {
$.ajax({
type: 'POST',
url: 'shoutboxform.php',
data: form.serialize(),
dataType:'html',
success: function(data) {alert('yes');},
error: function(data) {
alert('no');
}
});
return false;
});
});
PHP:
<?php
require_once("core/global.php");
if(isset($_POST["subsbox"])) {
$sboxmsg = $kunaiDB->real_escape_string($_POST["shtbox_msg"]);
if(!empty($sboxmsg)) {
$addmsg = $kunaiDB->query("INSERT INTO kunai_shoutbox (poster, message, date) VALUES('".$_SESSION['username']."', '".$sboxmsg."'. '".date('Y-m-d H:i:s')."')");
}
}
And HTML:
<form method="post" id="shoutboxform" action="">
<input type="text" class="as-input" style="width: 100%;margin-bottom:-10px;" id="shbox_field" name="shtbox_msg" placeholder="Insert a message here..." maxlength="155">
<input type="submit" name="subsbox" id="shbox_button" value="Post">
</form>
When I submit anything, it just reloads the page and nothing is added to the database.
Prevent the default submit behavior
$(document).on('submit', 'form#shoutboxform', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'shoutboxform.php',
data: $(this).serialize(),
dataType: 'html',
success: function(data) {
alert('yes');
},
error: function(data) {
alert('no');
}
});
return false;
});
Use the following structure:
$('form#shoutboxform').on('submit', function(e) {
e.preventDefault();
// your ajax
}
Or https://api.jquery.com/submit/ :
$("form#shoutboxform").submit(function(e) {
e.preventDefault();
// your ajax
});
I am trying to submit a form using ajax post.Before that i am checking that all the form data are correct, if so the form will be submitted.Can any body tell me why the form is not submitting ?
HTML:
<form id="formElem" name="formElem" action="" method="post">
<fieldset class="step">
<legend>Account</legend>
<p>
<label for="password">Password</label>
<input type="password" name="uPassword" id="uPassword" value="<?=$uPassword;?>" AUTOCOMPLETE=OFF />
</p>
<p>
<label for="password">Verify Password</label>
<input type="password" name="uVPassword" id="uVPassword" value="<?=$uVPassword;?>" />
</p>
<p class="submit">
<button id="registerButton" type="submit">Register</button>
</p>
</fieldset>
</form>
jQuery code :
$('#registerButton').bind('click', function () {
if ($('#formElem').data('errors')) {
alert('Please correct the errors in the Form');
return false;
} else {
$(function () {
$("#formElem").on("submit", function (event) {
event.preventDefault();
$.ajax({
url: "somefile.php",
type: "post",
data: $(this).serialize(),
success: function (d) {
alert(d);
}
});
});
}); ///end of func
return true;
}
});
Why do you have event.preventDefault(); in the beginning of your submit function? It seems that that's the problem.
You don't need the click handler, in the submit handler you can check for the validity
jQuery(function ($) {
$("#formElem").on("submit", function (event) {
event.preventDefault();
if ($(this).data('errors')) {
return;
}
$.ajax({
url: "somefile.php",
type: "post",
data: $(this).serialize(),
success: function (d) {
alert(d);
}
});
});
})
You can call ajax on click of button. For any error it will go in to the if condition otherwise submit the form successfully..
$('#registerButton').bind('click', function () {
if ($('#formElem').data('errors')) {
alert('Please correct the errors in the Form');
return false;
}
$.ajax({
url: "somefile.php",
type: "post",
data: $(this).serialize(),
success: function (d) {
alert(d);
}
});
return true;
}); ///end of func
$(function() { /*code here */ }); That execute the function when the DOM is ready to be used. This means that this function is assigned to the event onDocumentReady that occurs only once (when the page loads), and you assign a function after this event, so never execute.
It's the same with this function $("#formElem").on("submit", function (event) {}); Do not tell her immediately but do you create a handle to the event onSubbmit.
I have a form that will display a list of transactions based on the name and date.
<form id="form1" name="form1" method="post" action="<?php echo base_url() ?>options/history">
Name
<input name="name" type="text" id="name" />
date
<input name="date" type="text" id="date" />
<input name="find" type="submit" id="find" value="find" />
</form>
Once the form is submitted all the relevant details are being displayed.
Can someone explain to me how I can use jquery to loads the data on the same page?
I'm new to jquery and learning stuff. I did some research and below is what I have found:
<script type="text/javascript">
$(document).ready(function() {
$('#find').click(function() {
$.ajax({
type: "GET",
cache: false,
url: "<?php echo base_url() ?>options/history",
success: function(data) {
alert('Data Loaded');
}
});
});
});
</script>
And also how do I pass the form variables to my controller? Is it possible to directly pass the values to the controller or do I have to pass it along with the URL?
<script type="text/javascript">
$(document).ready(function() {
$('#form1').submit(function() {
// get the data of the form
var data_form = $('#form1').serialize();
$.ajax({
type: "GET",
cache: false,
data: data_form,
url: "<?php echo base_url() ?>options/history",
success: function(data) {
alert('Data Loaded');
// Your data is in the var data returned, you can use it with, for example: $("#content").html(data);
}
});
// Prevent default behaviour
return false;
});
});
</script>
I am a bit confused here. But I suppose you actually want this:
$('form#form1').submit(function(evt){
$.ajax({
type: "GET",
data: $(this).serialize(),
cache: false,
url: "<?php echo base_url() ?>options/history",
success: function (data) {
alert('Data Loaded');
}
});
evt.preventDefault();
return false;
});
You can use .submit() to bind to the JavaScript's submit event instead. By returning false at the end of this handler you can stop the form submission as shown above; or, by using evt.preventDefault().
The data property in $.ajax specifies the data to be sent to the server. As for getting this data you can use .serialize(), it will encode the form elements ready for submit them.