I have some problem here..
I use upload from on index.php and i use jquery (ajax) to save any information to mysql. I have 3 file index.php, savedata.php, jsSave.js
But when i use $_REQUEST file from savedata.php and result is blank response also in mysql table, i replace $_REQUEST and use $_FILES and have same result.
What i already try and use is code like below...
Index.php
<form class="myform" action="<?php $_SERVER['PHP_SELF'];?>" method="POST" name="myform" id="myform" enctype="multipart/form-data" style="width:350px;">
<li>
<label>Item Picture</label>
<div class="fileUpload btn btn-primary">
<span>Choose Image..</span>
<input type="file" name="cItemPicture" class="cItemPicture" id="cItemPicture"/>
</div>
<input type="hidden" name="cPic" id="cPic"/>
</li>
<li>
<img border="0" src="images/loading_transparent.gif" width="20" height="20" id="imgLoad">
 <button class="button_blue" id="butTblSave" type="submit" style="width: 81px; height: 33px">SAVE</button>
</li>
and for savedata.php file script is
<?php
if($_REQUEST)
{
***$cItemPicture=$_FILES["cItemPicture"]["name"];***
$sql="INSERT INTO tblData(item_image) VALUES ('$cItemPicture')";
$result=mysql_query($sql) or die('Cannot Connect To SQL Server, Please contact your administrator');
move_uploaded_file($_FILES["cItemPicture"]["tmp_name"],
"upload/" . $_FILES["cItemPicture"]["name"]);
}
?>
last file which work as AJAX using jQuery file is jsSave.js
$(document).ready(function() {
$('#imgLoad').hide();
$('#msgConfirm').hide();
$('#tblAvailabilityResult').hide();
});
$(function() {
$("#butTblSave").click(function() {
$.ajax({
type: 'POST',
url: 'saveData.php',
data: $('form').serialize(),
beforeSend: function() {
$("imgLoad").show();
},
complete: function() {
$("imgLoad").hide();
},
cache: false,
success: function () {
$("#cItemPicture").val('');
$('#imgLoad').hide();
$('#butTblSave').attr("disabled", false);
$('#msgConfirm').fadeIn(500).delay(5000).fadeOut(1000);
$("#msgConfirm").html(' Add New Item Success.');
}
});
return false;
}
});
});
Do i miss something? when press SAVE button ajax reponse blank and saved data into mysql item_image also blank, also and no file moved into upload folder.
Any idea for this problem? Many thanks about this.
Thank you
try preventing the default submission of the form.
Because the form is submitting to SELF (index.php)
$("#butTblSave").click(function(event) {
event.preventDefault();
...
Related
I have a simply AJAX call as a part of an image upload form. The page calls a PHP form which is supposed to then process the file upload and return a "successful" comment to the same page.
Currently, the script is working perfectly but when it returns the AJAX success string, it takes you to a new page and shows the AJAX output rather than showing it within the DIV on the same page.
To make it simpler, I've just cut out all of the PHP upload script and changed it to a simple echo output script - so I think it's a problem with the submit form page rather than the page that's called. I have jQuery included in the submission page.
Here's the submit form:
<div id="uploadFormLayer">
<form id="uploadForm" action="../uploadtesties.sparkle" method="post" enctype="multipart/form-data">
<input type="file" name="myFile">
<input type="submit" value="Upload">
<input type="hidden" name="EID" value="<? echo $ElectionID; ?>">
</form>
</div>
<div id="targetLayer"></div>
Here's the AJAX request:
<script type="text/javascript">
$(document).ready(function (e) {
$("#uploadForm").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "uploadtesties.sparkle",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data)
{
$("#targetLayer").html(data);
},
error: function()
{
}
});
}));
});
</script>
The PHP page just says <?php echo "Testing output"; ?> for the moment.
I am trying to generate multiple form that will provide a system to upload multiple files. So far code is
<?php
...
foreach($all_cat as $cat)
{
?>
<form method="post" class="uploadform" enctype="multipart/form-data" action="">
<label for="file-upload" class="custom-file-upload">
<i class="cloud-upload"></i> Add Files
</label>
<input id="file-upload" type="file" name="files[]" multiple />
<input type="submit" value ="uplaod" size="60">
</form>
...
<?php
...
jquery
$(".uploadform").on('submit',(function(e)
{
e.preventDefault();
if($('input[type=file]').val()=="")
{
alert("no file is selected");
return false;
}
else
{
$.ajax({
url: "form_process.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(result)
{
alert(result);
}
})//ajax
}//else
}));//onsubmit
But it seems that form_process.php file is not getting data form jquery. alert producing long mark-up of table, and somewhere in that it says file name can not be empty.
form_process.php
if(isset($_FILES['files']))
{
foreach($_FILES['files']['tmp_name'] as $key3)
{
$exif = exif_imagetype($key3);
echo "file type is ".$exif."<br/>";
}
How do I access those selected files upload and other data of the form? I have been trying for hours, anybody can help me,please ? Thanks in advance
Try appending them instead of using 'this'.
I do not understand, and google does not give me the answer. I want to upload a file and the results show in the div without page relode, but I can not get it!!!!
html:
<form method="post" action="process/pic2.php" enctype="multipart/form-data" id="userpic">
<p>Izvēlies bildi: <input type="file" name="img_to_upload" /><input type="submit" name="upload" value="Augšupielādēt" /></p>
</form>
jquery:
jQuery(function(){
jQuery('#userpic').submit(function(){
jQuery.ajax({
type: 'POST',
enctype: 'multipart/form-data',
url: jQuery('#userpic').attr('action'),
data: jQuery('#userpic').serialize(),
success: function(data){
if(data){
jQuery('#picinfo').html(data);
}else{
jQuery('#uerpic').fadeOut(500);
jQuery('#picinfo').html('<center><img src="img/loader.gif" /></center>');
window.location = 'index.php';
}
}
});
return false;
});
});
and my php:
if(isset($_FILES['img_to_upload']['name']) && !empty($_FILES['img_to_upload']['name'])){
echo 'Done!';
}else{
echo 'Error!';
}
all the time showing the "error" text..
P.S. Sorry for bad English.
Normally, to do a form-submission, and stay on the same page, you'll have to prevent the default form action with Javascript, something like this:
$("#userpic").submit(function(event) {
event.preventDefault();
...
});
But, uploading an image via Ajax is pretty tricky--see:
uploading files with jquery $.ajax and php
PHP/Ajax newbie here...I am trying to save the contents of a textarea into MySQL via Ajax. Although the data IS being saved correctly, Ajax isn't quite working. Basically, the page is "reloaded/refreshed" after the data is saved, unlike Ajax. Can you please tell me what is that I am doing wrong?
index.html:
<form action="save.php" method="post" id="source-form">
<span><input type="submit" value="Save" /></span>
<div>
<textarea id="editor" name="editor" >
</textarea>
</div>
</form>
javascript:
$(document).ready(function() {
$("#source-form").submit(function(){
$.ajax({
url:"save.php",
type:"post",
data:$(this).serialize(),
success: alert('saved');
});
});
save.php
<?php
// connect to the database
include('connect-db.php');
// get form data, making sure it is valid
$submit_date = date('Y-m-d H:i:s');
$content = mysql_real_escape_string(htmlspecialchars($_POST['editor']));
//build query
mysql_query("INSERT source SET submit_date='$submit_date',content='$content'")
or die(mysql_error());
header('Location: index.html');
?>
Any help on this is appreciated. Thank you.
EDIT:
For folks running into the same issue or something similar...here's a great solution from:
http://jquery.malsup.com/form/#getting-started
change your <form action="save.php" method="post" id="source-form">
to <form method="post" id="source-form">
remove the action you already declared your url in the ajax
remove header('Location: index.html'); since your should not redirect since your are using ajax. remember that if you are using ajax you dont need to refresh the page just let it receive a confirmation that the result was successful
Add a return false; to forum submit so that the form submit is cancelled:
$("#source-form").submit(function(){
$.ajax({
url:"save.php",
type:"post",
data:$(this).serialize(),
success: alert('saved');
});
return false;
});
You have to stop the default behavior of the submit button (form posting).Otherwise the form will be submitted again and you will see the page loading again. You use the preventDefault function
$("#source-form").submit(function(e){
e.preventDefault();
$.ajax({
url:"save.php",
type:"post",
data:$(this).serialize(),
success: alert('saved');
});
});
If you're only using the form for a ajax submit, I would suggest removing the form from the HTML completely and using a click event. I've stripped things down to a minimum in the HTML:
HTML
<input id="save-text" type="submit" value="Save" />
<textarea id="editor" name="editor" ></textarea>
JavaScript
$(document).ready(function() {
$("#save-text").click(function(){
$.ajax({
url:"save.php",
type:"post",
data: $("#editor").serialize(),
success: alert('saved');
});
});
I have got this html/php in my index.php
if (isset($_POST['UploadMSub'])) {
$fileP=$_FILES['Upload_f'];
$fileP_name=$fileP['name'];
$fileP_tmp=$fileP['tmp_name'];
$fileP_size=$fileP['size'];
$fileP_error=$fileP['error'];
$fileP_extension=explode('.', $fileP_name);
$fileP_extension=strtolower(end($fileP_extension));
$allowed=array('jpg','png');
if (in_array($fileP_extension, $allowed)) {
if ($fileP_error===0) {
if ($fileP_size<=2097152) {
$fileP_new_name=uniqid().'.'.$fileP_extension;
}
}
}
$_SESSION['fileP']=$fileP;
$_SESSION['fileP_name']=$fileP_name;
$_SESSION['fileP_tmp']=$fileP_tmp;
$_SESSION['fileP_size']=$fileP_size;
$_SESSION['fileP_error']=$fileP_error;
$_SESSION['fileP_extension']=$fileP_extension;
$_SESSION['fileP_new_name']=$fileP_new_name;
}
<form method="post" enctype="multipart/form-data" class='SubmUploadFu'>
<textarea maxlength="400" type="text" class='Text' placeholder="New post"></textarea>
<input type="file" name="Upload_f" style="display:none;" id="Nameupload">
<label for="Nameupload" class='LabelCamerUp'>
<img src="../img/camera.png" class='CamerUp'>
</label>
<input type="submit" class="UploadMSub">
</form>
And this ajax
$(".UploadMSub").click(function() {
var text=$(".Text").val();
var file=$("#Nameupload").val();
$.ajax({
type: "GET",
url: '../connect.php',
data: "Text=" + text+"&&file="+file,
success: function(data)
{
alert(data);
}
});
return false;
});
connect.php
if (isset($_GET['Text'])) {
$Text=htmlspecialchars($_GET['Text'],ENT_QUOTES);
$file=htmlspecialchars($_GET['file'],ENT_QUOTES);
echo $Text." ".$_SESSION['fileP_new_name'];
}
But when i submit form it returns(alerts)
"Undefine index ''fileP_new_name'"
Is there any other way of getting all information about file in my connect.php?
The problem is,
When you hit the submit button, the form doesn't get submitted, which means none of your session variables are set when you hit the submit button. Instead jQuery script runs straight away when you hit the submit button, and that's why you're getting this error,
Undefine index: fileP_new_name
From your question,
Is there any other way of getting all information about file in my connect.php?
So the solution is as follows. You have to change few things in your code, such as:
Add a name attribute in your <textarea> element, like this:
<textarea maxlength="400" name="new_post" class='Text' placeholder="New post"></textarea>
Instead of returning false from your jQuery script, use preventDefault() method to prevent your form from being submitted in the first place, like this:
$(".UploadMSub").click(function(event){
event.preventDefault();
// your code
});
If you're uploading file through AJAX, use FormData object. But keep in mind that old browsers don't support FormData object. FormData support starts from the following desktop browsers versions: IE 10+, Firefox 4.0+, Chrome 7+, Safari 5+, Opera 12+.
Set the following options, processData: false and contentType: false in your AJAX request. Refer the documentation to know what these do.
So your code should be like this:
HTML:
<form method="post" enctype="multipart/form-data" class='SubmUploadFu'>
<textarea maxlength="400" name="new_post" class='Text' placeholder="New post"></textarea>
<input type="file" name="Upload_f" style="display:none;" id="Nameupload">
<label for="Nameupload" class='LabelCamerUp'>
<img src="../img/camera.png" class='CamerUp'>
</label>
<input type="submit" class="UploadMSub">
</form>
jQuery/AJAX:
$(".UploadMSub").click(function(event){
event.preventDefault();
var form_data = new FormData($('form')[0]);
$.ajax({
url: '../connect.php',
type: 'post',
cache: false,
contentType: false,
processData: false,
data: form_data,
success: function(data){
alert(data);
}
});
});
And on connect.php, process your form data like this:
<?php
if(is_uploaded_file($_FILES['Upload_f']['tmp_name']) && isset($_POST['new_post'])){
// both file and text input is submitted
$new_post = $_POST['new_post'];
$fileP=$_FILES['Upload_f'];
$fileP_name=$fileP['name'];
$fileP_tmp=$fileP['tmp_name'];
$fileP_size=$fileP['size'];
$fileP_error=$fileP['error'];
$fileP_extension=explode('.', $fileP_name);
$fileP_extension=strtolower(end($fileP_extension));
$allowed=array('jpg','png');
if (in_array($fileP_extension, $allowed)){
if ($fileP_error===0) {
if ($fileP_size<=2097152){
$fileP_new_name=uniqid().'.'.$fileP_extension;
}
}
}
// your code
//echo $fileP_new_name;
}
?>