Submit a form with a file without refresh - javascript

Hello guys i don't know to submit a form without page refresh.
This is my code:
My form:
<form method="POST" id="post123" action="" enctype="multipart/form-data">
<input class="form-control input-lg" name="book_name" id="inputLarge" type="text">
<input class="form-control" name="book_price" type="number">
<textarea class="form-control" id="exampleTextarea2"
name="book_description" maxlength="100" rows="7"></textarea>
<textarea class="form-control" name="book_content" id="exampleTextarea4" maxlength="200" rows="7"></textarea>
<input type="file" name="file" id="imgInp44" >
<button type="submit" name='action' id="sendbutton21" value="post1" class="btn btn-primary">
Submit
</button>
</form>
Javascript:
$("#sendbutton21").click(function() {
var url = "http://localhost:5000/magazin_insert"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#post123").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
How i can modify my code to submit along with text a file towards the mysql db?

Your first issue is in this line:
<button type="submit" name="action" ... />
You have two possibilities:
change type="submit" to type="button"
use event.preventDefault() in your $("#sendbutton21").click(function() {
After, your ajax call can be changed in order to include the file:
var form = document.getElementById('post123');
var formData = new FormData(form);
$.ajax({
url: url,
data: formData,
type: 'POST',
processData: false,
success: function(data) {
alert(data);
}
});
$("#sendbutton21").click(function() {
var url = "http://localhost:5000/magazin_insert"; // the script where you handle the form input.
// for testing...
url = 'https://api.github.com/repositories';
var form = document.getElementById('post123');
var formData = new FormData(form);
$.ajax({
url: url,
data: formData,
type: 'GET',
processData: false,
success: function (data) {
console.log(data[0].id);
}
});
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<form method="POST" id="post123" action="" enctype="multipart/form-data">
<input class="form-control input-lg" name="book_name" id="inputLarge" type="text">
<input class="form-control" name="book_price" type="number">
<textarea class="form-control" id="exampleTextarea2"
name="book_description" maxlength="100" rows="7"></textarea>
<textarea class="form-control" name="book_content" id="exampleTextarea4" maxlength="200" rows="7"></textarea>
<input type="file" name="file" id="imgInp44" >
<button type="button" name='action' id="sendbutton21" value="post1" class="btn btn-primary">
Submit
</button>
</form>

Try https://jquery-form.github.io/form/ plugin to easily send form via ajax sample code:
$('#post123').ajaxForm(function() {
// SUCCESS CALLBACK
});

To submit a form without refresh, use event.preventDefault().
$("#sendbutton21").click(function(event) {
event.preventDefault();
var url = "http://localhost:5000/magazin_insert"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#post123").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});

Instead of
$("#sendbutton21").click(function() {
use
$("#post123").submit(function() {

Related

Upload PDF using ajax and form keeps failing

I have this code that keeps failing do do its job. I'm trying to pass file data ass well as ID to the php side, but it keeps failing. I don't know what I'm doing wrong. Please help.
$(document).ready(function() {
$('#form_upload').submit(function(event) {
event.preventDefault();
$.ajax({
url: 'updateFile.php',
type: 'post',
contentType:false,
cache: false,
processData:false,
data: {docID: document.getElementById('txt_docID').value, formUpload: new FormData($('#form_upload'))},
success: function(data){
alert(data);
}
});
return false;
});
});
<div id="divItemSelector" >
<form id = 'form_upload' class 'uploadform' action="updateFile.php" method="post" enctype="multipart/form-data">
<input type="file" name="fileUpload" id="fileUpload" >
<input id='txt_docID' type="text" name="txt_docID" style="visibility:hidden">
<input type="button" value="Close" name="btn_close" onclick = "hideDiv()" style="float: right;">
<input type="submit" value="Upload PDF" name="submit" style="float: right;">
</form>
and on php side im trying to use
$_POST['docID']
and
$_FILES["fileUpload"]["name"]
to get to my data.
in your code type: 'post' should be method: 'post'

How to sent uploaded image details(name,size, temp_name,error) for upload using JavaScript

I am submiting form using JavaScript. Now I want to store/move image into folder using javaScript.
HTML Code -
<form id="exampleForm" method="post" action="" enctype="multipart/form-data" >
<input type="file" name="imagename" id="imagename" />
<input type="button" name="save_exit" id="save_exit" onclick="submitForm('add_question_sql.php')" value="Save & Exit" />
</form>
JavaSript Code-
function submitForm(action)
{
document.getElementById('exampleForm').action = action;
document.getElementById('exampleForm').submit();// submiting form
}
So how to sent image details (name, size, temp_name,error) to action page for move uploading process.
Try this
<form id="exampleForm" method="post" enctype="multipart/form-data" >
<input type="file" name="imagename" id="imagename" />
<button>Submit</button>
</form>
Ajax:
$("form#exampleForm").submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url:'add_question_sql.php',
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});

Submitting two jQuery ajax form with two submit buttons

Here I just want to use two submit button in a single page, but its not sending any data through post?
<form name="form_post" id="form-post" method="post">
<label>
<span>Title *</span>
<input type="text" name="post_name" id="post-name" placeholder="Post title...." required>
</label>
<label>
<span>Body *</span>
<input type="text" name="post_body" id="post-body" placeholder="Post body...." required>
</label>
<input type="submit" id="submit_post" value="Submit Post">
</form>
Here is another form:
<form id="form_comment" method="post">
<!-- need to supply post id with hidden fild -->
<input type="hidden" name="postid" value="<?php echo $post_id ?>">
<label>
<span>Name *</span>
<input type="text" name="comment_name" id="comment-name" placeholder="Your name here...." required>
</label>
<label>
<span>Your comment *</span>
<textarea name="comment" id="comment" cols="30" rows="10" placeholder="Type your comment here...." required></textarea>
</label>
<input type="submit" id="submit_comment" value="Submit Comment">
</form>
this my script but not working? where I'm sending my request. I want to active such scrpts fro particuler submit, is there any way?
$(#form_post).submit(function(){
var form = $(form);
var submit = $('#submit_post');
form.on('submit', function(e) {
// prevent default action
e.preventDefault();
// send ajax request
$.ajax({
url: 'ajax_post.php',
type: 'POST',
cache: false,
data: form.serialize(), //form serizlize data
beforeSend: function(){
// change submit button value text and disabled it
submit.val('Submitting...').attr('disabled', 'disabled');
},
success: function(data){
// Append with fadeIn see http://stackoverflow.com/a/978731
var item = $(data).hide().fadeIn(500);
$('.wrap').append(item);
// reset form and button
form.trigger('reset');
submit.val('Submit Post').removeAttr('disabled');
},
error: function(e){
alert(e);
}
});
});
});
$(#form_comment).submit(function(){
var form = $(form);
var submit = $('#submit_comment');
form.on('submit', function(e) {
// prevent default action
e.preventDefault();
// send ajax request
$.ajax({
url: 'ajax_comment.php',
type: 'POST',
cache: false,
data: form.serialize(), //form serizlize data
beforeSend: function(){
// change submit button value text and disabled it
submit.val('Submitting...').attr('disabled', 'disabled');
},
success: function(data){
// Append with fadeIn see http://stackoverflow.com/a/978731
var item = $(data).hide().fadeIn(500);
$('.comment-block').append(item);
// reset form and button
form.trigger('reset');
submit.val('Submit Comment').removeAttr('disabled');
},
error: function(e){
alert(e);
}
});
});
});
you miss some "
it should be $("#form_comment") and $("#form_post") ...
This works for me:
$('#form_post').on('submit', function(event){
event.preventDefault();
$.ajax({
...
...
...
});
});
$('#form_comment').on('submit', function(event){
event.preventDefault();
$.ajax({
...
...
...
});
});
Use submit events like this,
$('body').on('submit', '#form_comment', function(){
e.preventDefault();
$.ajax({
...
...
...
});
});
$('body').on('submit', '#form_post', function(){
e.preventDefault();
$.ajax({
...
...
...
});
});

clear form data after submit jquery

How do I clear a form data once the submit succeed in jquery?
$(document).ready(function () {
$('#submit').click(function () {
$.ajax({
type: "POST",
url: 'final.php',
data: "user=" + $('#user').val() + "&comment=" + $('#comment').val(),
success: function (data) {
$('#status').html(data);
}
});
});
});
HTML... I need to clear the form data once the form is submitted....Any help would be appreciated.
<input type="text" name="user" id="user">
<input type="text" name="comment" id="comment">
<input name="submit" type="submit" id="submit">
<div id="status">
$('#formId').trigger('reset');
$('form').find('input[type=text]').val('') should do
Call this in the success callback of your Ajax

Repopulating div with new form/content using jQuery/AJAX

Are there any jQuery/AJAX functions that when a form (or anything for that matter) is displayed, upon pressing a button the div containing the original form is replaced by a new form? Essentially, a multi-part form without having to reload the page.
Can I use something like this?
$('form#myForm').submit(function(event) {
event.preventDefault();
$.ajax({
type: '',
url: '',
data: $(this).serialize(),
success: function(response) {
$('#divName').html(response);
//somehow repopulate div with a second form?
}
})
return false;
});
I've used this before for adding items to a list, but I've never used it to totally repopulate it with different content. How can I direct it to the second form?
edit - I got it to work, but only when I write '#form2' for the replacement. I alerted the response and I get {"formToShow":"show2"}. I tried doing response.formToShow but it's undefined.
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
</head>
<div id="divName">
<form method="POST" action = "#" id="form1">
<input type="textbox" name="textbox1" value="1"/>
<input type="submit" name="submit1"/>
</form>
<form method="POST" action = "#" id="form2" style="display: none">
<input type="textbox" name="textbox2" value="2"/>
<input type="submit" name="submit2"/>
</form>
</div>
<script>
$('form#form1').submit(function(event) {
event.preventDefault();
$.ajax({
type: 'JSON',
url: 'receiving.php',
data: $(this).serialize(),
success: function(response) {
$('#form1').hide(); //hides
//$('#form2').show(); //this will show
$(response.formToShow).show(); //this does not display form 2
}
})
return false;
});
</script>
Here is receiving.php. When I view this page {"formToShow":"show2"} is displayed
<?php
echo json_encode(array("formToShow" => "#form2"));
?>
Check the JQuery Load Function
This is personal preference, but I'd never send HTML through the response and display it like that, what I'd do is:
Send a JSON array back from the server, such as { formToShow: "#form1" }
Then you can simply do this:
success: function(response) {
$('form').hide();
$(response.formToShow).show();
}
Obviously, using this method, you'd also have to have the second form in your markup like this:
<form method="POST" action = "#" id="form2" style="display: none">
<input type="textbox" name="textbox2"/>
<input type="submit" name="submit2"/>
</form>
You'd also have to change (to pickup the array):
$.ajax({
type: 'JSON'
try this
$('form#myForm').submit(function(event) {
event.preventDefault();
$.ajax({
type: '',
url: '',
data: $(this).serialize(),
success: function(response) {
$('#divName').html(response);
$('#form1').hide();
$('#form2').show();
}
})
return false;
});
<form method="POST" action = "#" id="form1">
<input type="textbox" name="textbox1"/>
<input type="submit" name="submit1"/>
</form>
<form method="POST" action = "#" id="form2" style="dispay:none;">
<input type="textbox" name="textbox2"/>
<input type="submit" name="submit2"/>
</form>

Categories