I submit the form when trigger submit. How ever I cannot create user record. I show you the code.
<form method="POST" id="form_1" action="../api.php" enctype="multipart/form-data" novalidate="novalidate">
<input type="text" name="name" id="name" value="Amy" readonly="readonly">
<input id="fileBox" class="fileUpload" type="file" name="img" accept="image/*" required>
<input type="hidden" name="isSubmit" value="1"/>
</form>
<a id="btnSubmit" href="javascript:void(0)">Submit</a>
In js file:
$('#form_1').submit(function(){
var formData = new FormData((this)[0]);
$.ajax({
type: "POST",
url: "../../api.php",
data: { action: "isSubmit", formData: formData},
processData:false,
contentType:false,
success: function(data){
$("#thankyou").show();
}
})
return false;
});
$("#btnSubmit").click(function(){
var name = $("#name").val();
$.ajax({
type: "POST",
url: "../../api.php",
data: { action: "checkInputData", name: name}
})
.done(function(data){
data = $.parseJSON(data);
if ( data.status == 0 ){
$('#form_1').trigger('submit');
}
api.php :
if( $action == "isSubmit"){
$name= isset($_POST["name"])?$_POST["name"]:null;
createUser($conn, $name);
}
I found the the flow of the submit is not correct.
The flow of the above code is when I trigger submit then fall into success show thankyou div, but didn't create user record.
however if I removed the "return false" in ajax, the flow will becomes : trigger submit then fall into success show thankyou div then redirected to api.php then finished. In this case I can create the user record.
My target result should be I trigger submit then fall into success show thankyou div and create user record. How can I do this? And what's the differnce between having and without the "return false".
Related
I have 2 separate form that are working fine, but my subscribe button is calling add comment form. So when button from second form is clicked my add_comment.js is also called. On my website I have only buttons for subscribtion and for adding comments on one specific page. I'd like to make my add_comment called when form or button with specific id is clicked or submitted and every other button to call news.js which is working fine. I searched for answer but none was good for me
First Form
<form name ="add_comment" id="add_comment" class="comment-form">
//some inputs name, email..
<button type="submit" name="submit" id="buttonKomentar">Submit</button>
</form>
Second Form
<form action="" method="post" novalidate>
<input type="text" class="form-control" placeholder="Your Email">
<button class="btn btn-block btn-default" id="buttonSub">Subscribe</button>
</form>
News.js
$("button").click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "dodaj_za_news.php",
data: {
email: $("#email").val(),
},
success: function(result) {
$('#news').html(result);
},
error: function(result) {
$('#news').html(result);
}
});
});
add_comment.js
$(document).ready(function(){
$("#buttonKomentar").on("click", function(e){
$.ajax({
type: 'post',
url: 'add_comment.php',
data: $('form').serialize(),
success: function (data) {
$('#potvrda').html(data); }
});
});
});
First form doesn't have closing tag. If it is the same in your code, then the second form is treated as a part of parent form.
im getting undefined from print_r($_POST), it's posting on the same php page.
Array ( [file] => undefined )
Edited - added part where it calls the upload_banner function
HTML
<form enctype="multipart/form-data" id="banner_form" class="form-horizontal" role="form" action="">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input id="file" name="file" type="file" class="filestyle" accept="image/jpeg,image/gif,image/png">
</form>
JS
$('#submit_btn').click(function(e){
e.preventDefault();
var date = document.getElementById('datepicker').value;
var title = document.getElementById('title').value;
var content = document.getElementsByClassName('note-editable')[0];
if(date == "" || title == "") {
alert("Please fill in the required fields");
return false;
}
else {
var cfm = confirm("Confirm Submit Changes?");
if(cfm === true)
{
var editarea = content.innerHTML;
$.post ("functions/add_upcoming.php",{date: date,title: title,sm_content: editarea},
function(data) {
});
upload_banner();
}
else
{
return false;
}
}
});
function upload_banner() {
var form_data = new FormData($('#banner_form')[0]);
form_data.append('file', $('input[type=file]')[0].files[0]);
$.ajax({
url: "upcomingevents.php?p=73",
contentType: false,
processData: false,
dataType: 'json',
data: form_data,
type: 'post',
success: function(data) { },
contentType: false,
processData: false
});
}
json as datatype cause im returning arrays from php side, did not post additional code cause im already getting issue at the file upload part
PHP
if(isset($_POST['file'])) {
print_r($_POST);
exit();
}
am i doing anything wrong here?
The FormData is set up incorrectly, should be :
var form_data = new FormData( );
form_data.append('file', $('input[type=file]')[0].files[0]);
Are you sure the url refered by the ajax is correct?
Why is there query param (?p=73) as you're doing post and not get.
Finaly, try to print the response through
success: function(data) { alert(JSON.stringify(data))},
You're function isn't even being called considering you don't have the submit button for the handler to run.
It should be like:
<form enctype="multipart/form-data" id="banner_form" class="form-horizontal" role="form" action="">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input id="file" name="file" type="file" class="filestyle" accept="image/jpeg,image/gif,image/png">
<input type="submit" id="submit_btn"/>
</form>
Also you have a syntax error in your JS, there is no need for the second set of }); to close the click handler.
JSFiddle:
https://jsfiddle.net/sggf82am/2/
I have a form having some data
<form id="abc" method="POST" action="abc.html">
<input type="hidden" id="a" name="a" />
<input type="hidden" id="b" name="b" value="save"/>
</form>
and in js file i am submitting this form
document.getElementById("abc").submit();
What i want to do is if it throws any exception then an alert popup should open. Can anyone help?
Both previous answers are wrong. They check that object form exists but don't handle server-side errors.
You could use jQuery Form Plugin:
$('#myForm')
.ajaxForm({
url : 'myscript.php', // or whatever
dataType : 'json',
success : function (response) {
alert("The server says: " + response);
}
})
;
or simple ajax :
$('#form').submit(function(){
$.ajax({
url: $('#form').attr('action'),
type: 'POST',
data : $('#form').serialize(),
success: function(){
console.log('form submitted.');
}
});
return false;
});
You could find more details in answers to this question - How do I capture response of form.submit
I want To submit multiple form using Jquery (ALready done) but the problem is .. every time after submit i want the form is remove from list form Here's My JSP code
<form action="searchTweet" method="post">
<textarea name="searchTxt"></textarea>
<input type="submit" name="post" value="Search"/>
</form>
<%
if(session.getAttribute("twitModel")!=null)
{
List<TwitterModel> twit=(List<TwitterModel>)session.getAttribute("twitModel");
int count=0;
for(TwitterModel tweet:twit)
{
count=count+1;
%>
<p>
#<%=tweet.getScreenName()%> : <%=tweet.getTweet() %>
<form id="form2" method="post">
<input type="hidden" name="screenName" value="<%= tweet.getScreenName() %>">
<input type="hidden" name="tweet" value="<%= tweet.getTweet() %>">
<input type="submit" class="update_form" value="Save"> <!-- changed -->
</form>
</p> <% } } %>
My Jquery for multiple submit form
<script>
// this is the class of the submit button
$(".update_form").click(function() { // changed
$.ajax({
type: "GET",
url: "saveSearch",
data: $(this).parent().serialize(), // changed
success: function(data)
{
$(this).parents('p').remove();
}
});
return false; // avoid to execute the actual submit of the form.
});
Any idea what i'm doing wrong??
Thank's
Regards
Danz
I guess your this has changed to global window variable inside the success function, try this for once:
$(".update_form").click(function() { // changed
var me = this;
$.ajax({
type: "GET",
url: "saveSearch",
data: $(this).parent().serialize(), // changed
success: function(data)
{
$(me).parents('p').remove();
}
});
return false; // avoid to execute the actual submit of the form.
});
read up on closures
this inside the success handler refers to the ajax object, not the clicked button. In this case you can use a closure variable to fix the issue.
Also not the use of .closest() instead of .parents()
$(".update_form").click(function () { // changed
var $this = $(this);
$.ajax({
type: "GET",
url: "saveSearch",
data: $(this).parent().serialize(), // changed
success: function (data) {
$this.closest('p').remove();
}
});
return false; // avoid to execute the actual submit of the form.
});
I created two forms on my website, but when i submit it redirects automatically, i want to prevent this.
I have a javascript code here that does exactly what i need, but it works in all forms on my website, i just need this code working in a specific form, because i have two forms, one called login, and other one called cart, and when i click on login button, it doesnt redirect, because of the script, it works for both forms, and i just want this script working in a specific form, in this case, cart.
I hope you understand, i dont speak english very well.
My Javascript code:
<script type="text/javascript">
$(document).ready( function () {
$('form').submit( function () {
var formdata = $(this).serialize();
$.ajax({
type: "POST",
url: "carrinho.php",
data: formdata,
});
return false;
});
}); </script>
My html code:
<form name="comprar" method="post" action="carrinho.php">
<input name="id_txt" type="hidden" value="<?php echo $id; ?>" />
<input name="nome" type="hidden" value="<?php echo $nome; ?>" />
<input name="preco" type="hidden" value="<?php echo $preco; ?>" />
<input name="quantidade" type="hidden" value="1" />
<input name="Comprar" type="submit" class="Adicionar" value="" />
</form>
Carrinho means cart, im building a ecommerce store.
Try:
$(document).ready( function () {
$("form[name='comprar']").submit( function () {
var formdata = $(this).serialize();
$.ajax({
type: "POST",
url: "carrinho.php",
data: formdata
});
return false;
});
});
Use $("form[name='comprar']") to access particular form. Change form name according to your requirement.
Use an attribute selector to select only the desired form. Also note that extra , is going to cause problems in IE < 9.
$("form[name='comprar']").submit( function () {
var formdata = $(this).serialize();
$.ajax({
type: "POST",
url: "carrinho.php",
data: formdata, //remove this comma
});
return false;
});