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 })
Related
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.
The code is working fine but the problem is that when I add this code to Magento it the Javascript doesn't work.
Let me explain a little bit about code. There is a simple form that has only one input field which is intended to enter phone numbers. There is another file called form.php that has all the PHP code. Whenever someone enters a phone number in the input field the PHP saves that number in the CSV file which is created in the backed. I don't want to redirect the form to another page, I just wanted a small message to appear in the same page without page reloading or redirecting.
For that, I added a jQuery code and it was working fine but the code was created to add it on Magento but when I add this code to Magento then the only the Javascript code doesn't work. Does anyone have a solution for this?
$(function() {
$("#myform").on("submit", function(e) {
e.preventDefault();
$.ajax({
url: $(this).attr("action"),
type: 'POST',
data: $(this).serialize(),
beforeSend: function() {
$("#message").html("sending...");
},
success: function(data) {
$("#message").hide();
$("#response").html(data);
}
});
});
});
<form id="myform" action="https://www.tawakkalfabric.com/form.php" method="post">
<div class="block-content">
<div class="form-subscribe-header">
<label for="newsletter">Sign Up for Our Newsletter:</label>
</div>
<div class="input-box">
<input type="tel" name="name" placeholder="Sign Up for Our WHATSAPP" />
</div>
<div class="actions">
<button type="submit" class="button"><span><span>Subscribe</span></span></button>
</div>
<div id="message"></div>
<div id="response"></div>
</div>
</form>
The code below is in form.php:
<?php
$email = $_POST['email'];
$name = $_POST['name'];
$data = $name.",".$email;
$file = "sample.csv";
file_put_contents($file, $data . PHP_EOL, FILE_APPEND);
print "<h1 align=center>Thank you for submitting your email address!</h1>";
?>
<html>
<head>
<title>ThankYou Page</title>
</head>
<body>
<h1>GO BACK</h1>
</body>
try following code
<script>
$(document).on("submit", "#myform", function(e) {
e.preventDefault();
$.ajax({
url: $(this).attr("action"),
type: 'POST',
data: $(this).serialize(),
beforeSend: function() {
$("#message").html("sending...");
},
success: function(data) {
$("#message").hide();
$("#response").html(data);
}
});
});
</script>
Magento (similar to WordPress) doesn't automatically allow for the $ alias, so you will need to include the code with the jQuery dependencies and then either create the alias or change the $ to jQuery.
See https://magento.stackexchange.com/questions/97184/how-to-use-jquery-library-in-magento-2
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.
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;
}
I'm new to the AJAX and PHP. I'm currently facing a problem with calling an jQuery confirm box function and insert the data into the database. When i clicked submit button, the ajax should called the confirm box function in jquery then when user clicked "YES" only the data will be inserted into the database. (The data contain of text filed and image file upload). But when i clicked the submit button, it straight away lead me to the bannerItem.php which is wrong.
Here is the AJAX code that i use to call the confirm box function and run the php code:
//File and text upload with formDATA function
$("form#form").confirm(function(){
var formData = new FormData($(this)[0]);
confirm: function(){
$.ajax({
url:'bannerItem.php',
type: 'POST',
data: formData,
async: false,
success: function (data) {
if(!alert('Banner Had Successfully Updated.')){location.reload();}
},
cache: false,
contentType: false,
processData: false
});
return false;
}
});
Here is the bannerItem.php code:
<?php
include 'dbConnection.php';
global $dbLink;
$target_file = basename($_FILES['uploaded_file']['name']);
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
//Check image file type
//Gather all required data
$item_id = $dbLink->real_escape_string($_POST['banner_id']);
$name = $dbLink->real_escape_string($_POST['bannerName']);
$data = $dbLink->real_escape_string(file_get_contents($_FILES['uploaded_file']['tmp_name']));
if(!isset($mydata) || $mystring == null){
//Create the SQL query
$query = "UPDATE banner_item SET banner_name='$name', banner_created=NOW() WHERE banner_item_id = '$item_id' ";
//$query = "INSERT INTO banner_item (banner_item_id, banner_name,banner_data,banner_created) VALUES ('{$item_id}','{$name}','{$data}', NOW())";
}
else if($name==''){
//Create the SQL query
$query = "UPDATE banner_item SET banner_data='$data', banner_created=NOW() WHERE banner_item_id = '$item_id' ";
//$query = "INSERT INTO banner_item (banner_item_id, banner_name,banner_data,banner_created) VALUES ('{$item_id}','{$name}','{$data}', NOW())";
}
else{
//Create the SQL query
$query = "UPDATE banner_item SET banner_name='$name', banner_data='$data', banner_created=NOW() WHERE banner_item_id = '$item_id' ";
//$query = "INSERT INTO banner_item (banner_item_id, banner_name,banner_data,banner_created) VALUES ('{$item_id}','{$name}','{$data}', NOW())";
}
// Close the mysql connection
$dbLink->close();
?>
Here is the code that i used to submit the form:
<!--Banner Item No 1 Start-->
<div class="box box-primary1" id="no1" style="display:none;">
<div class="box-header">
<h3 class="box-title">Edit Banner Image No.1 <small>编辑器</small></h3>
</div>
<div class="box-body">
<form id="form" action="bannerItem.php" method="POST" enctype="multipart/form-data">
<div class="box-body">
<input type="hidden" name="banner_id" value="1"></input>
<div class="form-group" >
<label for="bannerName">Banner Name 旗帜名称</label>
<input type="text" class="form-control" name="bannerName" id="bannerName" placeholder="Please Enter Name" onChange="checkDisabled(testing);">
</div>
<div class="form-group">
<label for="exampleInputFile">File input</label>
<input type="file" id="uploaded_file" name="uploaded_file" onChange="checkDisabled(testing);"><br>
<p class="help-block">Your picture size not more than 2MB. (Only JPEG/JPG/PNG is allowed)</p>
</div>
<div class="checkbox">
<button id="testing" type="submit" class="btn btn-primary" disabled>Update</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 -->
<!--Banner Item No 1 End-->
I'm not sure which part i did wrong on the ajax code. Please point out my mistake so that i can change, Thanks and good day ahead :)