I am writing code to test AJAX image and data upload. However, the Ajax seems to return an error stating that the input is not valid:
Syntax error: unexpected end of input
The script and HTML are as follows
<input type="file" name="vdofile" id="file" />
<input type="text" id="name" />
<button id="send">Send</button>
$("#send").click(function(){
var form = new FormData();
form.append('vdofile',$("#file").prop("files")[0]);
form.append('name', $("#name").val());
$.ajax({
url: 'upload.php',
type: "POST",
data: form,
dataType: 'json',
contentType: false,
processData: false,
success: function(data)
{
alert(data.message);
},
error: function(xhr, status, error)
{
alert('An error occured.. ' + xhr.responseText + '..' + error );
}
});// ajax
}); // function
The test PHP is as follows:
header("Content-Type: application/json");
if(isset($_FILES['vdofile']) && isset($_POST['name']))
{
$result = array(
'message' => 'both data and file received'
);
}
else {
$result = array(
'message' => 'one of parameter missing'
);
}
return json_encode($result);
Your PHP is returning an empty response. return doesn't print anything.
print json_encode($result);
should work better.
Related
i have problem pass data from selected file (image)
i will move the image to localhost directory
here my simple code
function uploadFile(){
event.preventDefault();
var input = document.getElementById("uploadImage");
file = input.files[0];
if(file != undefined){
formData= new FormData();
if(!!file.type.match(/image.*/)){
formData.append("image", file);
$.ajax({
url: "service.php?aksi=A",
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function(data){
alert('data);
}
});
}else{
alert('Not a valid image!');
}
}else{
alert('Input something!');
}
}
here my simple html code
<input type="file" required="" id="uploadImage" name="gambar" >
<button id="gantiphoto" name="submit" onclick="uploadFile()" class="btn btn-default">Upload </button>
and call it to specific php function
if ($_POST["aksi"]=="A"){
$dir = "asset/";
move_uploaded_file($_FILES["image"]["tmp_name"], $dir. $_FILES["image"]["name"]);
}
elseif ($_POST["aksi"]=="B"){
}
i try
$.ajax({
url: "service.php?aksi=A",
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function(data){
alert('data);
}
});
and
$.ajax({
url: "service.php",
type: "POST",
data: "aksi=A"+formData,
processData: false,
contentType: false,
success: function(data){
alert('data);
}
});
but the response still
Notice: Undefined index: image in C:\xampp\htdocs\rutela\service.php on line 166
or
Notice: Undefined index: aksi in C:\xampp\htdocs\rutela\service.php on line 7
i still dont understand how to pass this image file,. im success with text but cant solve this image pass data
im appreciate ur answer, im just newbie in ajax
You Can Add One More formData Filed
formData.append("aksi", "A");
Also Change Url to This
service.php
After This You Can Check Like
if($_POST['aksi'] == "A"){
$dir = "asset/";
move_uploaded_file($_FILES["image"]["tmp_name"], $dir. $_FILES["image"]["name"]);
}
else if($_POST['aksi'] == "B")
{
}
There are a couple things I might change to make this work:
<script>
function submitForm()
{
// Set error state a true
var valid = false;
// Init
var data1 = new FormData();
// Loop files
$.each($('input[type="file"]')[0].files, function(i, file) {
// If the file is good
if(!!file.type.match(/image.*/)) {
// Update status to valid
valid = true;
// Add file
data1.append(i, file);
}
});
// Do the ajax
if(!valid) {
$.ajax({
url: "service.php?aksi=A",
type: "POST",
data: data1,
enctype: 'multipart/form-data',
processData: false,
contentType: false,
success: function(response) {
$('#response').html(response);
}
});
}
else {
alert('Incorrect file type');
}
}
</script>
<div id="response"></div>
<input type="file" required="" id="uploadImage" name="gambar" >
<button id="gantiphoto" name="submit" onclick="submitForm()" class="btn btn-default">Upload</button>
In your PHP you should first try a test to make sure but I would switch to $_GET here not $_POST:
// ****** START TEST ******//
// If you do a test, you can see what is being sent so it will help you
// narrow down where it's going wrong
echo '<pre>'.print_r([
$_POST,
$_GET,
$_FILES
], 1).'</pre>';
// ****** START ACTUAL CODE ******//
// Stop if this is not set
if(empty($_GET["aksi"]))
die('aksi is a required parameter.');
// Switch to GET here
switch($_GET["aksi"]) {
case('A'):
if(empty($_FILES))
die('Invalid image.');
$dir = "asset/";
// I haven't checked, but I think these keys are numeric now
// The test above should tell you what they are exactly
move_uploaded_file($_FILES[0]["tmp_name"], $dir. $_FILES[0]["name"]);
break;
case('B'):
// do stuff
}
I can successfully upload a document in mysql blob (msword or pdf). Now I need help in downloading it.
Here is My download button code.
<form id="specificationdownload">
<input type="hidden" name="cusid" id="cusid" value = "<?php echo $row['id_stk']?>">
<button class="btn btn-success" name="downloadspec" type="submit">Download </button>
</form>
Here is my Ajax code which handles the download button form
//Specification download
$("form#specificationdownload").on("submit",function(e){
e.preventDefault();
jQuery.ajax({
url: "../data/stock.php?action=stock-specification-download",
type: "POST",
data: new FormData(this),
processData: false,
contentType: false,
success: function(data, textStatus, jqXHR) {
console.log(2);
var filter = "<?php echo $id_stc ?>";
var tab_content_to_change = "#stock-sub-list";
jQuery(tab_content_to_change).load('/tasks/stock/stock-list.php?filter='+filter);
},
error: function(jqXHR, textStatus, errorThrown){
//Display error message to user
alert("An error occured when saving the data");
}
});
});
Here is my action
$CustomerID = $_POST['cusid'];
if(isset( $CustomerID ))
{
//Query
$prepare_query = "SELECT specificationsheet_name_stk,specificationsheet_type_stk,specificationsheet_size_stk, specificationsheet_stk FROM stock_stk
WHERE id_stk ='$CustomerID';";
$result = mysqli_query($mysqli_scs, $prepare_query);
$row = mysqli_fetch_array ($result);
//die(var_dump($row));
header("Content-length:" .$row['specificationsheet_size_stk']);
header("Content-type:" .$row['specificationsheet_type_stk']);
header("Content-Disposition: attachment; filename=".$row['specificationsheet_name_stk']);
return $row['specificationsheet_stk'];
exit;
}
The problem is when I click "Download" button, the file does not get downloaded. If I var_Dump the $row, It dump the array with right keys so object is there, but does not print.
Anybody know What I'm doing wrong.
Thank you.
I am using Ajax to post my data, while using inspect elemet, I can see the post data from all other fields, but text area field comes empty, so the data fails to be saved to the database.
function addblog() {
save_method = 'add';
url = "<?php echo site_url('index.php/blog/post_new_blog')?>";
$.ajax({
url: url,
type: "POST",
data: $('#addblog').serialize(),
dataType: "json",
success: function (data) {
alert('Saved');
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error adding / update data');
}
});
}
HTML:
<div id="editor-one" class="editor-wrapper"></div>
<textarea id="descr" class="text" name="desc" style="display:none;"></textarea>
PHP:
public function post_new_blog()
{
$data = array(
'blog_title' => $this->input->post('title', true),
'blog_content' => $this->input->post('desc', true),
'blog_tags' => $this->input->post('tags', true),
);
$insert = $this->main_model->save_new_posts($data);
echo json_encode(array("status" => TRUE));
}
You are sending data as follows:
data: $('#addblog').serialize(),
does your
<textarea id="descr" class="text" name="desc" style="display:none;"></textarea>
inside html element with id addblog?
Meanwhile, i didn't understand why you set display to none for textarea?
I'm sending formData through jQuery.ajax(), however the PHP function that is processing all this can't properly retrieve and recognize the DATA being sent. I've went through many questions on stackoverflow and also tried this in many different ways all to no avail and finally gave up.
This is all done in WORDPRESS.
I can't use serialize because I'm also sending files, but I left them out below for the sake of simplicity.
This is the simplified version of the form:
<form id="newForm" method="post" enctype='multipart/form-data'>
<div>
<label>Title</label>
<input name="title" type="text" value=""/>
</div>
<div>
<label>Content</label>
<input name="content" type="text" value=""/>
</div>
<button type="submit" id="submit_button">SUBMIT</button>
</form>
This is the jQuery:
jQuery(document).ready(function(){
$('#newForm').submit(function(e){
e.preventDefault();
var new_data = new FormData($(this)[0]);
$.ajax({
url:ajaxurl,
type: "POST",
data: {
'action': 'upload_function',
new_data //I've tried new_data: new_data
},
cache:false,
processData:false,
dataType: 'json', //tried not sending it as json dataType, still didn't work
success:function(response){
console.log(response);
if(response.success == 1){
alert("Post inserted");
}else{
alert("Post not inserted");
}
},
error:function(){
alert("Ajax request hasn't passed");
}
});
});
});
This is the PHP that handles the post insert(it's getting called properly, I've checked by inserting static values in post title and content), I left out the nonce and other stuff for the sake of simplicity:
function upload_function(){
$json_result=array();
$json_input=$_POST['new_data'];
$post_vars=json_decode($json_input,true);
$submit_post_data = array (
'post_title' => $post_vars['title'],
'post_content' => $post_vars['content'],
'post_status' => 'draft'
);
$post_id = wp_insert_post($submit_post_data);
if($post_id){
$json_result['success']=1;
}else{
$json_result['success']=0;
}
wp_send_json($json_result);
exit();
}
add_action('wp_ajax_upload_function','upload_function');
you need to serialize the form data and then pass it to the php code. Do this to your var new_data assignment.
var new_data = $(this).serialize()
EDIT 1: As you stated you have files you need use FormData object to pass the files to sever in ajax. refer the code below.
var $element = $(this);
var formdata = new FormData();
var totalFiles = $element.files.length;
if (totalFiles > 0) {
for (var i = 0; i < totalFiles; i++) {
var file = $element.files[i];
formdata.append("FileUpload", file);
}
$.ajax({
type: "POST",
url: Url,
data: formdata,
contentType: false,
processData: false,
success: function (result) {
// make the server return a array of file names that has been saved.
//Post your other form elements data a this point with the filename array.
},
error: function (error) {
console.log("File Upload Failure");
}
});
}
I am using jQuery ajax to upload files. When I clicked upload button,it fails and the error section of ajax is showing Uncaught TypeError: Cannot read property 'length' of undefined. I have checked the code and found that alerting the jqXHR shows success in the first ajax call,but the ajax call in submitForm() is not working.The controller stops before the $.each(event,data) and it shows the above error in the console.Please help me.
My code is below:
$(document).ready(function()
{
//for checking whether the file queue contain files or not
var files;
// Add events
$('input[type=file]').on('change', prepareUpload);
// Grab the files
function prepareUpload(event)
{
files = event.target.files;
alert(files);
}
$("#file-form").on('submit',uploadFiles);
function uploadFiles(event)
{
event.stopPropagation();
event.preventDefault();
// Create a formdata object and add the files
var data = new FormData();
$.each(files, function(key, value)
{
data.append(key, value);
//alert(key+' '+ value);
});
$.ajax({
url: 'module/portal/filesharing/upload.php?files',
type: 'POST',
data: data,
cache: false,
dataType: 'json',
processData: false,
contentType: false,
success: function(data, textStatus, jqXHR)
{
if(typeof data.error === 'undefined')
{
// Success so call function to process the form
submitForm(event, data);
}
else
{
console.log('ERRORS: ' + data.error);
}
}
});
function submitForm(event, data)
{
// Create a jQuery object
$form = $(event.target);
// Serialize the form data
var formData = $form.serialize();//controller stops here
// sterilise the file names
$.each(data.files, function(key, value)
{
formData = formData + '&filenames[]=' + value;
});
$.ajax({
url: 'update.php',
type: 'POST',
data: formData,
cache: false,
dataType: 'json',
success: function(data, textStatus, jqXHR)
{
if(typeof data.error === 'undefined')
{
// Success so call function to process the form
console.log('SUCCESS: ' + data.success);
}
else
{
// Handle errors here
console.log('ERRORS: ' + data.error);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
// Handle errors here
console.log('ERRORS: ' + textStatus);
},
complete: function()
{
// STOP LOADING SPINNER
}
});
}
}
});
</script>
Html:
<form id='file-form' action="" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="filename" ><br>
<input type="submit" id='upload' value="Upload file">
</form>
My update.php:
$data = array();
if(isset($_GET['files']))
{
$error = false;
$files = array();
$uploaddir = 'module/portal/filesharing/upload/';
foreach($_FILES as $file)
{
if(move_uploaded_file($file['tmp_name'], $uploaddir .basename($file['name'])))
{
$files[] = $uploaddir .$file['name'];
}
else
{
$error = true;
}
}
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
}
else
{
$data = array('success' => 'Form was submitted', 'formData' => $_POST);
}
echo json_encode($data);
If you want it works on cross-browser, i recommend you use iframe like this http://www.ajaxf1.com/tutorial/ajax-file-upload-tutorial.html
Or there is some jquery modules using flash for upload they are also good option for older version of internet explorer
Maybe your problem is this one, please check this out
how to get the uploaded image path in php and ajax?