insert image into database with ajax using formData - javascript

I'm having some difficulties with uploading an image from an html form. the form should be able to send the image name with other data to php page.
I used formData instead of serialized function, since it can't handle files data.
$(document).on('click', '#btn_add', function(){
var formData = new FormData($(this)[0]);
$.ajax({
url:"includes/widgets/insert.php",
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false
success: function (data) {
alert(data);
},
});
return false;
});
html form
<form id="insert_post" action="includes/widgets/insert.php" method="post" enctype="multipart/form-data" >
<div class="row">
<div class="medium-6 columns">
<label>First name
<input type="text" name="first_name" id="first_name" contenteditable>
</label>
</div>
<div class="medium-6 columns">
<label>Last name
<input type="text" name="last_name" id="last_name" contenteditable>
</label>
</div>
<div class="medium-12 columns">
<label>Last name
<input type="file" name="file" id="image" multiple contenteditable>
</label>
</div>
</div>
<button type="button" name="btn_add" id="btn_add" class="button btn btn-xs btn-success" >Submit</button>
</form>
php page
<?php
$connect = mysqli_connect("localhost", "root", "", "myaddboard");
echo $_POST['first_name'];
echo $_POST['last_name'];
echo $image = $_FILES['file']['name'];
echo $image_tmp = $_FILES['file']['tmp_name'];
/*
if(empty($image)){
echo 'error';
}
move_uploaded_file($image_tmp,"img/$image");
//$sql = "INSERT INTO posts(post_content, post_author) VALUES('".$_POST["first_name"]."', '".$_POST["last_name"]."')";
if(mysqli_query($connect, $sql))
{
echo 'Data Inserted';
} else {
echo 'error';
}
*/
?>
The php form is just to test if the ajax send the data correctly.
When I click on the button I always get errors that the php variables is not defined
The errors i get each time I submit the form
undefined index: frist_name in c:xampp\htdocs\unv\includes\widgets\insert.php on line 4
undefined index: last_name in c:xampp\htdocs\unv\includes\widgets\insert.php on line 5
undefined index: file in c:xampp\htdocs\unv\includes\widgets\insert.php on line 8
undefined index: file in c:xampp\htdocs\unv\includes\widgets\insert.php on line 9
what should I do to make the ajax send the data to the php page ?

This won't work because of how your selector is created.
$(document).on('click', '#btn_add', function(){
var formData = new FormData($(this)[0]);
In the above scenario, $(this)[0] is getting you the raw HTML interpretation of the button.
What you actually want is to change your button to a submit type, capture the form submit event, and then process your request.
button type="submit" <-- change
$(document).on('submit', '#insert_post', function(e){
e.preventDefault(); //stop default form submission
//do the rest of your stuff here
});
Now $(this)[0] is actually the form and not the button.

Related

Jquery Form Submission with Image

Please refer question: Jquery Image Upload in Form with Plugin goes Null
I am trying to submit a form using JQuery Ajax and trying to retrieve in a PHP file and save. for the particular form there are two file inputs.
Image
Note
when I debug using var_dump($_FILES), I was able to see only Note's array but not Image's. for image upload I am using a plugin called FancyUpload, that is what probably causing the issue. below is the form
<form id="form" action="add.php" method="post" autocomplete="off" enctype="multipart/form-data">
<div>
<input aria-label="cxname" id="cxname" name="cxname" class="form-control" placeholder="Name" type="text">
</div>
<div>
<select name="sales" id="sales" class="SlectBox form-control">
<option value='0'>Sales</option>
<?php echo sales(); ?>
</select>
</div>
<div>
<input class="custom-file-input" placeholder="choose note" name="note" id="note" type="file">
<label class="custom-file-label">Choose Note</label>
</div>
<div>
<input class="custom-file-input" placeholder="Choose Image" name="image" id="image" type="file" multiple>
</div>
<div>
<button id="submit" class="btn btn-primary btn-size">Add</button>
</div>
</form>
Jquery Below along with its fancy uploader classes
<!-- JQuery min js -->
<script src="assets/plugins/jquery/jquery.min.js"></script>
<script src="assets/plugins/jquery-ui/ui/widget.js"></script>
<script src="assets/plugins/fancyuploder/jquery.ui.widget.js"></script>
<script src="assets/plugins/fancyuploder/jquery.fileupload.js"></script>
<script src="assets/plugins/fancyuploder/jquery.iframe-transport.js"></script>
<script src="assets/plugins/fancyuploder/jquery.fancy-fileupload.js"></script>
<script>
$(document).ready(function(e){
var image = $('#image').FancyFileUpload({
maxfilesize : 1000000,
params : {
action : 'form'
},
autoUpload: false
});
$("#form").on('submit', function(e){
e.preventDefault();
var fd = new FormData();
fd.append('pimage', $(image)[0].files[0]);
fd.append('deliveryNote', $("#note")[0].files[0]);
fd.append('cxname', $('input[name=cxname]').val());
fd.append('sales', $('select[name=sales]').val());
$.ajax({
type: 'POST',
url: 'add.php',
data: fd,
dataType: 'json',
processData:false,
contentType: false,
cache: false,
async: false,
success: function(response){
$('.statusMsg').html('');
if(response.status == 1){
$('#form')[0].reset();
$('.statusMsg').html('<p class="alert alert-success">'+response.message+'</p>');
alert('received');
}else{
$('.statusMsg').html(alert(response.message));
}
$('#form').css("opacity","");
$(".submit").removeAttr("disabled");
}
});
});
});
Retreiving PHP
upload_dir = 'uploads/';
pdf_dir = 'doc/';
if (isset($_POST['cxname']) || isset($_POST['deliveryNote']) || isset($_POST['pimage']) || isset($_POST['sales'])) //even tried with ($_FILES['pimage'])
{
$cxname=$_POST['cxname'];
$sales=$_POST['sales'];
var_dump($_FILES);
//MOVE IMAGE -> Comes Empty
if(!empty($_FILES['pimage']['tmp_name']))
{
$temp = $_FILES['pimage']['tmp_name'];
$name = $_FILES['pimage']['name'];
$result = move_uploaded_file($temp,$upload_dir.$name);
$response['status'] = 1;
$response['message'] = 'IMAGE HAS BEEN SAVED';
}
else{
$name = '';
$response['status'] = 0;
$response['message'] = 'IMAGE CAME EMPTY!';
}
//SAVE NOTE
$_pdfDN = $_FILES['deliveryNote']['name'];
$Tempfile = $_FILES['deliveryNote']['tmp_name'];
$_pdfResult = move_uploaded_file($Tempfile,$pdf_dir.$_pdfDN);
}
If I do without image upload plugin, it works fine. Please advice.

how can page reload disabled when data get using ajax success function in javascript codeigniter php?

I have a registration form and want to check if registered user will try to register again to show a alert window already registered using ajax function.
i have used codeigniter framework.
my function is working properly but when alert popup and press ok page is reloaded. i want to disable
my form code:
<form class="modal-content" name="form2" action="<?= $this->config->base_url();?>home/register_user" method="post" onSubmit="return ValidateRegister()">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">Create your account</h4>
</div>
<div class="page-content vertical-align-middle" style="display:block;">
<div class="form-group has-error">
<label class="control-label" for="inputTokenfieldError-tokenfield"> <?php echo validation_errors(); ?></label>
</div>
<div class="form-group form-material floating">
<input type="text" class="form-control " id="inputName" name="username" value="<?php echo set_value('username'); ?>" autocomplete="off">
<label class="floating-label">Username</label>
</div>
<div class="form-group form-material floating">
<input type="email" class="form-control " id="my_email" name="email" value="<?php echo set_value('email'); ?>" autocomplete="off">
<label class="floating-label">Email</label>
</div>
<div class="form-group form-material floating">
<input type="password" class="form-control " id="inputPassword" name="password" autocomplete="off">
<label class="floating-label">Password</label>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-block">Join Now - It's Free</button>
</div>
</form>
my javascript function:
function checkRegistrations()
{
var email = $('#my_email').val();
$.ajax({
url: "<?= base_url() ?>home/checkRegistration",
async: false,
type: "POST",
data: "email="+email,
dataType: "html",
success: function(data) {
// alert(data);
if(data==1)
{
//event.preventDefault();
alert('Email already registered');
return false;
window.location.reload(false);
}
else{
return true;
}
}
})
}
Just add an id to the submit button, say #submitbutton.
and use the .prop() method of jQuery to set the disabled attribute of the button.
$("#submitbutton").prop("disabled", true);
IMP: This will only work if you are keeping the same page on ajax success, But if you are reloading the page then you need to check it on php side whether this form has been submitted in this current $_SESSION.
So inside your php ajax handler, you can do the check as follows.
session_start();
if(!empty($_POST) && empty($_SESSION['post'])) {
$_SESSION['post'] = true;
... do your code
unset($_SESSION['post']);
}else{
// send the json encoded error message
}
And on the html form just add a hidden input with the name post and set value to 1 or something whatever you deem fit, so once the form is submitted, the post key will be set inside the $_SESSION SuperGlobal Array, and if the same form is submitted twice by the same user then php wont accept it.
You are returning true/false from inside an annon. function i.e. success handler. But parent function is not returning true/false.
Modify your code like this :
function checkRegistrations()
{
var email = $('#my_email').val();
var isValid = true;
$.ajax({
url: "<?= base_url() ?>home/checkRegistration",
async: false,
type: "POST",
data: "email="+email,
dataType: "html",
success: function(data) {
if(data==1)
{
alert('Email already registered');
isValid = false;
}
}
});
return isValid;
}

Unable to call Ajax function from php in server

I am having a problem to call the ajax function from the php after I clicked submit button to submit the form. Everything is working fine on Localhost, but when I transfer all of the php to FTP server, all the function can't work already.
In Localhost, I'm able to submit the file upload to filesystem which I name it "uploads" folder and then insert the data of the form into database with query. But when I try on the FTP server, where I also create a uploads folder to store the uploaded file, it can't work.
Anything I did wrong in my code or any configuration I need to set? Please point me out.
Here is my php code where I use to submit form :
schoolform.php
<!--Banner Item No 1 Start-->
<div class="box box-primary1" id="no1" style="display:block;">
<div class="box-header">
<h3 class="box-title">Upload New Form Here <small>Only PDF</small></h3>
</div>
<div class="box-body">
<form class="form" id="form" action="" method="POST" enctype="multipart/form-data">
<div class="box-body">
<div class="form-group" >
<label for="formName">Form Name</label>
<input type="text" class="form-control" name="formName" id="formName" placeholder="Please Enter Name" onChange="checkDisabled(testing);">
</div>
<div class="form-group" >
<label for="formDescription">Form Description</label>
<input type="text" class="form-control" name="formDescription" id="formDescription" placeholder="Please Enter Description" onChange="checkDisabled(testing);">
</div>
<div class="form-group">
<label for="exampleInputFile">File input</label>
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input type="file" id="uploaded_file" name="uploaded_file" onChange="checkDisabled(testing);"><br>
<p class="help-block">You file must not more than 1MB. (Only PDF allowed)</p>
</div>
<div class="checkbox">
<button id="testing" type="submit" class="btn btn-primary" disabled>Add</button>
</div>
</div><!-- /.box-body -->
</form> <!-- Date range -->
<!-- /.form group -->
<!-- Date and time range -->
<!-- /.form group -->
<!-- Date and time range -->
<!-- /.form group -->
</div><!-- /.box-body -->
</div><!-- /.box -->
Here is where I used to call the ajax function to insert the data:
//File and text upload with formDATA function
$("#form").submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url:'schoolFormItem.php',
type: 'POST',
data: formData,
async: false,
beforeSend: function(){
if(confirm('Are you sure?'))
return true;
else
return false;
},
cache: false,
contentType: false,
processData: false
}).done(function () {
//do something if you want when the post is successfully
if(!alert('Form Had Successfully Inserted.')){document.getelementbyclassname('form').reset()}
});
return false;
});
Here is my query function to insert data into database and also filesystem :
<?php
include 'dbConnection.php';
global $dbLink;
$path = "uploads/";
$valid_formats = array("PDF", "pdf");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['uploaded_file']['name'];
$size = $_FILES['uploaded_file']['size'];
$fName = $dbLink->real_escape_string($_POST['formName']);
$fDescription = $dbLink->real_escape_string($_POST['formDescription']);
if(strlen($name))
{
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024))
{
$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
$tmp = $_FILES['uploaded_file']['tmp_name'];
if(move_uploaded_file($tmp,$path.$actual_image_name))
{
//mysqli_query ($db,"INSERT INTO image VALUES('','hello','$actual_image_name')");
//mysqli_query($db,"UPDATE users SET profile_image='$actual_image_name' WHERE uid='$session_id'");
$query = "INSERT INTO schoolform_item (schoolform_name,schoolform_description,schoolform_data,schoolform_created) VALUES ('{$fName}','{$fDescription}','{$actual_image_name}', NOW())";
$result = $dbLink->query($query);
}
else
echo "failed";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format..";
}
else
echo "Please select image..!";
exit;
}
?>
Did I miss any step or is any code is wrong? Because everything is working when I try on localhost with xammp. And it all become malfunction when put on the server.
Please guide me through this.
The reason your confirm box never appears is actually because you have an error in jquery.confirm.js on line 147: Uncaught ReferenceError: dataOptions is not defined I see your using jquery.confirm.js version 2.3.1.
In the official version the file ends like this:
/**
* Globally definable rules
*/
$.confirm.options = {
text: "Are you sure?",
title: "",
confirmButton: "Yes",
cancelButton: "Cancel",
post: false,
confirmButtonClass: "btn-primary"
}
})(jQuery);
In your copy, the file ends like this:
/**
* Globally definable rules
*/
var settings = $.extend({}, $.confirm.options = {
confirm: $.noop,
cancel: function (o) {},
button: null,
text: "Are you sure?",
title: "Warning!",
confirmButton: "Yes",
cancelButton: "Cancel",
post: true,
confirmButtonClass: "btn-primary",
cancelButtonClass: "btn-default"
}, dataOptions, options);
})(jQuery);
I would replace that bit of code iwth the original bit, or, better yet, grab a new copy of the file from the jquery.confirm site
try $.post() instead of $.ajax({}) and see. may be it's the cause, $.post is simplified. for more info http://api.jquery.com/jQuery.post/
also try changing:
var formData = new FormData($(this)[0]);
to:
var formData = jQuery('#myform').serialize();
try this code too:
$("#form").submit(function(){if(confirm('Are you sure?')) {$.post('schoolFormItem',{data:$('#form').serialize()}, function(){$('#form #resetbtn').trigger('click');alert('success')})} else {alert('not posted');return false;}});
at the top, have:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
and wrap the code in:
jQuery(function(){ //our code goes here })

Getting value from contenteditable div

Up to this point, I've been using a textarea as the main input for a form. I've changed it to use a contenteditable div because I wanted to allow some formatting.
Previously, when I had the textarea, the form submitted fine with Ajax and PHP. Now that I've changed it to use a contenteditable div, it doesn't work anymore and I can't tell why.
HTML:
<form>
<div name="post_field" class="new-post post-field" placeholder="Make a comment..." contenteditable="true"></div>
<input name="user_id" type="hidden" <?php echo 'value="' . $user_info[0] . '"' ?>>
<input name="display_name" type="hidden" <?php echo 'value="' . $user_info[2] . '"' ?>>
<ul class="btn-toggle format-post">
<button onclick="bold()"><i class="fa-icon-bold"></i></button>
<button onclick="italic()"><i class="fa-icon-italic"></i></button>
</ul>
<div class="post-buttons btn-toggle">
<button class="btn-new pull-right" type="submit">Submit</button>
</div>
</form>
JQuery Ajax:
$(document).ready(function() {
$(document).on("submit", "form", function(event) {
event.preventDefault();
$.ajax({
url: 'php/post.php',
type: 'POST',
dataType: 'json',
data: $(this).serialize(),
success: function(data) {
alert(data.message);
}
});
});
});
PHP (post.php): Just your typical checks and echo a message back. This is just a snippet of the code.
<?php
$user_id = $_POST["user_id"];
$display_name = $_POST["display_name"];
$post_content = $_POST["post_field"];
$array = array('message' => $post_content);
echo json_encode($array);
?>
For some reason, it's not sending back the post content anymore ever since I added the contenteditable div.
Please help!
The contents of the div are not serialized. You would have to add them on your own.
var data = $(this).serialize();
data += "post_field=" + encodeURIComponent($("[name=post_field]").html());

Multiple forms in while loop with ajax

I have a product page whos products are created dynamically from mysql along with "add to cart" buttons and quantity inputs on each item. These items are submitted via AJAX. I'm able to submit the correct product but the success message returned from ajax uses a hidden div which hides the add to cart button then displays text that your item in now in the cart. It hides ALL of the cart button and shows the hidden div containing the success message in every form. Any help to solve this is appreciated!
My PHP/HTML
//inside while loop
?>
<div class="form">
<form action="cart_action.php" method="post" name="form" id="form_<?php echo $item_no; ?>">
<input type="hidden" class="text" name="order_code" value="<?php echo $item_no; ?>" id="order_code<?php echo $item_no; ?>" />
<input type="hidden" class="text" name="minorder" value="<?php echo $min; ?>" id="min_<?php echo $item_no; ?>" />
<br><br><div style="float:left; padding:5px;"><b>Qty</b>: <input class="text" type="text" name="quantity" value="<?php echo $min; ?>" size="3" id="quan_<?php echo $item_no; ?>" ?></div>
<div id="status"></div>
<input type="image" src="images/add_to_cart.png" class="psubmit" alt="submit" name="submit" id="submit_<?php echo $item_no; ?>" />
</div><div class="added"><b><div style="color: rgb(85, 176, 90);"><br /><b>Added to Cart </b>(View Cart)</div></b></div>
</form>
<?php
} //end loop
JAVASCRIPT:
$(document).ready(function() {
$('form').submit(function(){
// Catching the DOM element which trigger the event
var $form = $(this);
var orderCode = $form.find('input[name=order_code]');
var quantity = $form.find('input[name=quantity]');
var minOrder = $form.find('input[name=minorder]');
if (quantity.val() == '') {
quantity.addClass('hightlight');
$form.find("#status").html('<font color="red">Please Enter A Quantity!</font>');
return false;
} else quantity.removeClass('hightlight');
if (quantity.val() % minOrder.val()) {
quantity.addClass('hightlight');
$form.find("#status").html('<font color="red">Invalid Multiple!</font>');
return false;
} else quantity.removeClass('hightlight');
//organize the data properly
var data = 'order_code=' + orderCode.val() + '&quantity=' + quantity.val();
//disabled all the text fields
//$('.text').attr('disabled','true');
//show the loading sign
$('.loading').show();
//start the ajax
$.ajax({
//this is the php file that processes the data and send mail
url: "cart_action.php",
//GET method is used
type: "GET",
//pass the data
data: data,
//Do not cache the page
cache: false,
//success
success: function (html) {
//if process.php returned 1/true (send mail success)
if (html==1) {
//hide the form
$('.form').fadeOut('slow');
//show the success message
$('.added').fadeIn('slow');
//if process.php returned 0/false (send mail failed)
} else
//hide the form
$('.form').fadeOut('slow');
//show the success message
$('.added').fadeIn('slow');
}
});
//cancel the submit button default behaviours
return false;
e.preventDefault();
});
});
In your success handler, change the selectors to start from $form:
$form.fadeOut('slow');
$form.children('.added').fadeIn('slow');

Categories