I am trying to build off a question I asked yesterday.
I am able to pass the file over to PHP using the ajax method. But I need to be able to change the file name to the booking number. For some reason, the booking was not being passed over to the PHP script. So I attempted the following:
$('#uploadBtn').on('click', function()
{
var form_data = new FormData();
form_data.append("file", document.getElementById('pdfFile').files[0]);
var booking = $('#bookingNum').val();
var partner = $('#partnerCode').val();
$.post('process/fileUpload.php', {booking:booking, partner:partner}, function(data)
{
// Wasn't sure if I needed anything here
console.log(data);
});
$.ajax({
url: 'process/fileUpload.php',
method:"POST",
data: form_data,
contentType: false,
cache: false,
processData: false,
success: function(data){console.log(data);},
error: function(jqHHR, textStatus, errorThrown){console.log('fail: ' + errorThrown);}
});
});
As you will notice above, I had to use the $.post method to send the booking and partner over to the php script.
I then used $.ajax to send the form_data over to the same script.
(I could not achieve this in one motion from yesterday's question I asked. So this is my second attempt to complete this. If there is a way to send all of the info in one motion, please refer to the question I linked above.)
So over in the PHP script, I am able to get all of the items I needed with a couple of functions:
<?php
// from the $.post method
if(isset($_POST['booking']))
{
$booking = $_POST['booking'];
$partner = $_POST['partner'];
getInfo($booking);
}
// from the $.ajax method
if($_FILES['file'])
{
$file = var_dump($_FILES['file']);
getFile($file);
}
function getInfo($booking)
{
return $booking;
}
function getFile($file)
{
return $file;
}
?>
I know it's not pretty, but I am able to get the booking (I don't need the partner right now), and I am also able to get the file information.
What I need to do is rename the file to the booking, and then finally upload it to the necessary directory.
I wasn't sure if I had to combine the functions, but I did try to no avail.
With that said, I am able to get the booking and file info within the PHP script. Now how would I go about renaming the file to the booking?
As you used form_data.append() to add the file data to the formdata. did it not occur to you to also use that to add the booking and partner values to it as well?
$('#uploadBtn').on('click', function()
{
var form_data = new FormData();
form_data.append("file", document.getElementById('pdfFile').files[0]);
form_data.append('booking', $('#bookingNum').val());
form_data.append('partner', $('#partnerCode').val());
$.post('process/fileUpload.php', form_data, function(data)
{
console.log(data);
});
});
To fix your ajax request (especially the illegal invocation), use the following javascript code
$('#uploadBtn').on('click', function()
{
var form_data = new FormData();
form_data.append("file", document.getElementById('pdfFile').files[0]);
form_data.append('booking', $('#bookingNum').val());
form_data.append('partner', $('#partnerCode').val());
$.ajax({
type: "POST",
url: 'process/fileUpload.php',
data: form_data,
processData: false,
contentType: false,
success: function(data) { console.log(data); }
});
});
Notice the use of processData: false and contentType: false
Related
I'm trying to add a file upload option to my page.
And I use Ajax for this purpose that sends the file to the server (where it is saved)
And should get back the file name
Everything works well except that when I print what comes back instead of just getting the array I send from the server I also get extra information.
Does anyone know where this supplement comes from? and how I can get rid of it?
here is my ajax:
$("#upload_file").change(function(input){
console.log(" in upload_file");
var file_data = $('#upload_file').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
type: 'POST',
url: '<?php echo base_url(); ?>organizer/save_event_file',
// dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
beforeSend: function(){
$('#progress_spinner').show();
$('body').addClass('disable_body');
},
success: function(response,status){
console.log(response);
},
complete: function(){
$('#progress_spinner').hide();
$('body').removeClass('disable_body');
}
}).fail(function (xhr, status, error) {
alert("error");
});//fail;
});
this is my server function:
enter code here
public function save_event_file(){ // to add check and prommision
$filePath = $_FILES['file']['tmp_name'];
$type=$_FILES['file']['type'];
//adding to the name with the current date in the end
$date = new DateTime();
$name = substr($_FILES['file']['name'],0,strpos($_FILES['file']['name'],'.')). '__' .$date>format('d.m.y').substr($_FILES['file']['name'],strpos($_FILES['file']['name'],'.'));
$data = array('file' => curl_file_create($filePath, $type, $name));
$response = $this->organizer_model->save_file($data); // save the file with the new name
$result = array('alertcode'=>1,'response'=>$response,'name'=>$name);
echo json_encode($result);
}
this is what I expect to be the response:
{"alertcode":1,"response":true,"name":"old db function__21.03.21.txt"}
this is the real response (The other part is the " {"alertcode":1}" in the beginning):
{"alertcode":1}{"alertcode":1,"response":true,"name":"old db function__21.03.21.txt"}
I have no problem cutting this information and then making a parse as follows:
var ans = JSON.parse(response.substring(response.indexOf('{"alertcode',10),response.length));
But I want to understand where this is coming from - in case this addition changes - and then it will cut the string badly.
I am passing a file to a php file via ajax and i am returning only 1 $ variable using die($var) in the php file after a sucsessfull run...
the problem i am now facing is passing more than 1 variable back to the ajax sucess function . i have tried using json encode but it has failed to work. im thinking maybe to do with the ajax being form data.
im hoping there is a simple way top pass multiple varibles back to the sucess function.
Any help is greatly appreciated
var form_data = new FormData(); // Creating object of FormData class
form_data.append("image", file , newimagesrc) // Appending parameter named file with properties of file_field to form_data
form_data.append("oldimagesrc", oldimagesrc) // to re-write over with new image
form_data.append("email", email)
form_data.append("imagext", fileNameSub)
$.ajax({
url: "UploadProfileImage.php",
type: "POST",
data: form_data,
processData: false,
contentType: false,
success: function(newimagesrc){
//how do i pass back from php these variables
var out1=out1;
var out2=out2;
alert(out1 , out2);
//help appreciated
var newimagesrc = newimagesrc;
//alert(newimagesrc); alert recieved message
imagename=input.files[0].name;
$('#imageupdate').css('color','green');
$('#imageupdate').text(newimagesrc);
var refreshimage = "Profileimagerefresh.php?avatar="+newimagesrc+"&email="+email;
$('#imagerefresh').load(refreshimage);
}//success 1 messagereturn1
});//ajax1
PHP FILE ('UploadProfileImage.php')
if(file_exists($oldimagelocation) && is_readable($oldimagelocation)){
$new=$rnd.$accountname.".".$extension;
if ($stat->execute(array("$new","$email"))){
unlink($oldimagelocation);
die($oldimagesrc); //HERE I PASS 1 $ BACK - I NEED TO RETURN MORE
exit();
}
else{
die("Failed replace image with image and rename");
exit();
}
}
Using JSON encode is the best choice. I would recommend something like this:
if (file_exists($oldimagelocation) && is_readable($oldimagelocation)) {
$new = $rnd.$accountname.".".$extension;
if ($stat->execute([$new, $email])) {
unlink($oldimagelocation);
echo json_encode([
'out1' => $oldimagelocation,
'out2' => $oldimagesrc,
], JSON_FORCE_OBJECT);
} else {
die("Failed replace image with image and rename");
}
}
Then in JS just parse the response as JSON
$.ajax({
url: "UploadProfileImage.php",
type: "POST",
data: form_data,
processData: false,
contentType: false,
success: function(newimagesrc){
let jsonObj = JSON.parse(newimagesrc);
console.log(jsonObj.out1);
}
});
I have encountered a similar issue recently and solved this using JSON.
With PHP you can put the variables into an array and then use json_encode: and then return that onto the webpage.
Now, using your jQuery, you can use $.parseJSON which then makes it an array in jQuery.
Here's an example:
PHP:
die(json_encode(array('Hello', 'world!')));
jQuery:
$.ajax({
type: 'POST',
url: 'test.php',
}).done(function(result){
var array = $.parseJSON(result);
alert(array[0]);
});
I have read a lot of Q&As on here and can't seem to figure out what I am doing wrong...
Here is AJAX
var color = $('#fontcolor').val();
var size = $('#fontsize').val();
var text = $('#imagetext').val();
var fileToUpload = $('#fileToUpload').val();
var placement = $('#placement').val();
$.ajax({
type: "POST",
url: 'upload.php',
data: {color:color, size:size, text:text, fileToUpload:fileToUpload},
success: function(data)
{
window.alert(data);
},
cache: false,
contentType: false,
processData: false,
error: function()
{
window.alert('error');
}
});
And then php, I am just trying to simply see my data from now, but it shows empty...
<?php
$fontSize = $_POST['size'];
echo $fontSize;
echo "Test";
?>
I know that data is coming from form, I have tested variables after data is received, but just can't get it to post... I was using FormData object originally, but decided to simplify for troubleshooting purposes... Still nothing, seems very straightforward, but have been on this for a few days now...
So it seems I might not be able to pass the image alongside the other parameters, though perhaps there is a way I cannot find. Instead, I will pass image to upload.php, then in response return the image path. Then I will have it trigger success function that passes other parameters to another function that modifies the image accordingly. Works for me.
I am trying to upload a file using jQuery's $.ajax function but didn't get any output.
Somebody please help me to solve this.
I don't know if this script is correct.
My script is:
$.ajax({
url:'newsup.php',
data: "",
type: 'POST',
contentType:'multipart/form-data',
dataType: 'json',
catche: 'false',
success:function(data6)
{
$("#disp").removeClass().addClass((data6.error=== false)? 'success':'error').html(data6.msg).fadeIn('fast');
//dele();
if($("#disp").hasClass('success'))
{
alert("success");
setTimeout("$('#disp').fadeOut('slow')",3000);
}
},
error:function(XMLHttpRequest,textStatus,errorThrown)
{
$("#disp").removeClass().addClass('error').html("There was an <strong>"+errorThrown+"</strong> error due to <strong>"+textStatus+" condition").fadeIn('fast');
}
});
Also I need help getting data from file uploading field using jQuery.
Please use plugin for this.In my opinion this plugin is better solution for this.You don't need to remember all options etc.Just replace your 'ajax' to 'ajaxForm'.
Please read examples ,below
http://jquery.malsup.com/form/#ajaxForm
This is how I've done it. Use the FormData object.
Note: The odd syntax of the for statement is just setting "f" to the array[i] instance.
$("#submit").click(function () {
var formData = new FormData();
for (var i = 0, f; f = fileArray[i]; i++) {
formData.append("opmlFile", f);
}
$.ajax({
url: "/Documents/SaveFiles/" + #Model,
type: "POST",
data: formData,
cache: false,
contentType: false,
processData: false
})
.error(function (xhr, status, error) {
$.notify(error, true);
})
.success(function (data, status, xhr) {
$.notify("Success");
});
});
Unfortunately I don't recall which article I got this from, but it was someone else on Stack Overflow.
AJAX doesnt support file uploading. There are plugins like ajaxfileupload which basically creates a hidden form and uploads your file dynamically.
take a look here and read Oli's answer
I'm using this and it's working fine:
$('#btnUploadFile').on('click', function () {
var data = new FormData();
var files = $("#fileUpload").get(0).files;
// Add the uploaded file content to the form data collection
if (files.length > 0) {
data.append("upload", files[0]);
}
// Make Ajax request with the contentType = false, and procesDate = false
var ajaxRequest = $.ajax({
type: "POST",
url: "/api/documents",
contentType: false,
processData: false,
data: data,
error: function (xhr, status, error) {
console.log(xhr);
console.log(status);
console.log(error);
console.log(data);
}
});
ajaxRequest.done(function (xhr, textStatus) {
$("#response").attr('class', "alert alert-success");
$("#response").html("File uploaded successfully");
});
});
You can use either of the two plugins Jquery File Upload Plugins 1 or Jquery File Upload Plugins 2 and there's no errors on this script.
Hope it helps
Thanks,
Rashid
Ajax supports File upload using FormData Object, Also supports in all major browser except IE8/9
See below
https://developer.mozilla.org/en-US/docs/Web/API/FormData
Another option would be to base64 encode the file contents and send it as a string, decoding it at the back-end.
Simply use submit event on form to send the files and prevent default form action
$('#form').submit(function(e) { return false; });
and get the file on the server side via
$_FILES['inputName'];
Everything was going great in my previous help request thread. I was on the correct track to get around a CSRF, but needed to be pointed in the right direction. I received great help and even an alternate script used to log into Google's Android Market. Both my script and the one I altered to match my form is get hung up at the same point. Apparently cURL cannot process JS, is there any way to work around the form being submitted with submitForm() without changing the form?
Here is the code for the SubmitForm function
function submitForm(formObj, formMode) {
if (!formObj)
return false;
if (formObj.tagName != "FORM") {
if (!formObj.form)
return false;
formObj = formObj.form;
}
if (formObj.mode)
formObj.mode.value = formMode;
formObj.submit();
}
Here is the code for the submit button -
<a class="VertMenuItems" href="javascript: document.authform.submit();">Submit</a>
Here is a link to my last question in case more background information is needed.
PHP service...
<?php
// PHP service file
// Get all data coming in via GET or POST
$vars = $_GET + $_POST;
// Do something with the data coming in
?>
Javascript elsewhere...
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
function sendData(data)
{
var response;
$.ajax({
url: 'phpservice.php',
data: data,
type: 'POST',
dataType: 'json',
async: false,
success: function(response_from_service)
{
response = response_from_service;
},
error: function()
{
}
});
return response;
};
function getData(data)
{
var response;
$.ajax({
url: 'phpservice.php',
data: data,
type: 'GET',
dataType: 'json',
async: false,
success: function(response_from_service)
{
response = response_from_service;
},
error: function()
{
}
});
return response;
};
});
</script>