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.
Related
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
I am trying to pass some basic data using JavaScript and PHP.
The PHP is not receiving any data.
I have the following JavaScript code:
var formData = new FormData();
formData.append("action", "save-game");
formData.append("title", title);
formData.append("players", players);
formData.append("noTables", noTables);
formData.append("maxPPT", maxPPT);
formData.append("rounds", roundChart);
$.ajax({
url: "/static/apps/games.php",
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function(response){
if (response.success) {
alert("Saved Game Setup");
} else {
alert("Failed to save game setup, "+response.reason);
console.log(response.reason);
}
}
})
And I have stripped the PHP down to the bare minimum but it is still not receiving the data
header("Content-Type: application/json");
$action = $_POST["action"];
echo json_encode(array(
'success' => false,
'reason' => $action,
));
The $action variable in PHP is returning null
try to build data like here
var buildData = function( _action, _title, _players, _noTables, _maxPPT, _rounds){
var data = {};
data.action = _action;
data.title = _title;
data.players = _players;
data.noTables = _noTables;
data.maxPPT = _maxPPT;
data.rounds = _rounds;
return JSON.stringify(data);
}
var _json = buildData("save-game", title, players, noTables, maxPPT, roundChart);
So I am having some issues using jQuery to POST data to a php script. I am passing the image data from a canvas to php that will in turn save the image to the server. I am wanting this to stay as a string when sending to make it easy when the php gets it. I have tried send in json as well and no success with that. The issue is I am not getting anything in return. I have no errors in the console and php isn't leaving any errors for me either to find. I also am for the time being writing the info passed to a txt file as well to verify that data is being passed and it as well is empty. What am I doing wrong? Also I have verified the DataURL var has info in it using an alert and it contains a nice string.
var dataURL = Grabcanvas.toDataURL();
$.ajax({
url: 'upload.php',
method: 'POST',
dataType : 'text',
data: {Image:dataURL},
success : function(data) {
console.log("sucessfull sending:");
console.log(data);
},
error : function() {
console.log('failed');
}
The php code
$writeDir = "dir/text/";
$upload_dir = "dir/image/";
$img = $_REQUEST['Image'];
$myfile = fopen($writeDir."newfile.txt", "w") or die("Unable to open file!");
$txt = $img . "\n";
fwrite($myfile, $txt);
fclose($myfile);
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = $upload_dir . mktime() . ".png";
file_put_contents($file, $data);
In your ajax call you have the key as Image {Image:dataURL} but in your php script your trying to access image $_REQUEST['image'], the key is case sensitive. change the one in ajax to image
you may try this
var dataURL = Grabcanvas.toDataURL();
var data = new FormData(); // added this line
data.append('Image', dataURL); // I have added this line
$.ajax({
url: 'upload.php',
method: 'POST',
dataType : 'text',
data: data, //I have changed this
success : function(data) {
console.log("sucessfull sending:");
console.log(data);
},
error : function() {
console.log('failed');
}
In PHP code change the following
$img = $_REQUEST['Image']; //you have used image, mind it it is case sensitive
This fixed it. Apparently I was explained to by a user here that toDataURL() is used for native javascript DOM but not jQuery DOM which I am using jQuery. So after code was rewritten to reflect this it now works correctly and sends without failing
`$.ajax({
url: 'upload.php',
type: 'POST',
dataType : 'text',
data: {Image: $('#name of canvas')[0].toDataURL()}, //CHANGED
cache: false,
contentType: false,
processData: false,
success: function(data) {
console.log("sucessful send:");
console.log(data);
},
error: function(d) {
console.log('error');
console.log(d);
console.log(d.responseText);
}`
I am trying to send form data with attachment to php via ajax.
My code is :
var company_name = $('#companyname').val();
var company_type = $('#companytype').val();
var industry_sector = $('#industrysector').val();
var email = $('#email').val();
var mobile = $('#mobile').val();
var logo = $("#logo").prop("files")[0];
var company_description = $('#company_description').val();
var password = $('#password').val();
var rePassword = $('#rePassword').val();
var data = {
company_name: company_name,
company_type: company_type,
industry_sector: industry_sector,
email: email,
mobile: mobile,
logo: logo,
company_description: company_description,
password: password
}
$.ajax({
type: "POST",
async: false,
data: {companyregister: data},
url: "ajax/loginvia.php",
processData: false, // tell jQuery not to process the data
contentType: false,
beforeSend:function(){
},
i am getting empty data to php controller. i tried in many ways, im unable to resolve the issue.
With simple ajax it is some complex to perform you can use ajaxForm for this. It is easy to implement. Here is plugin url : http://jquery.malsup.com/form/
It is so easy to implement have a look at this.
<script>
// wait for the DOM to be loaded
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#myForm').ajaxForm(function() {
alert("Thank you for your comment!");
});
});
</script>
$.ajax({
url: "ajax_php_file.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
$('#loading').hide();
$("#message").html(data);
}
});
$sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "upload/".$_FILES['file']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
I am extremely bad at AJAX (actually, I just started to learn it).
So, I write whois service on PHP and I want to make it to output the result via AJAX-request.
All I have at the moment is:
my PHP code:
$domain = $_POST['domain'];
$whois = new Whois();
header("content-type:application/json");
$res = $whois->getWhois($domain); // Calls the Whois-query function;
echo json_encode($res);
my JS code:
$('#submit').on('click', function() {
e.preventDefault();
var domain = $('#value').val();
});
$.ajax({
url: 'ajax/whois.php',
type: "post",
data: {'domain': domain, 'action': 'whois'},
dataType: "json",
success: function(json) {
$('#whoisResult').html('<h2>Whois Query result for ' + domain + '</h2>');
$('#whoisContent').html(json.html);
},
error: function(xhr, status) {
$('#whoisResult').html('<h2>Sorry, an error occured. Try again later, please!</h2>')
}
});
As HTML I have an input: <input type="text" id="value"> and the submit button.
I searched for the script examples and tried to make something similar, but it does not work at all...
P.S. Guess you won't hit this question a negative rating :)
P.P.S: As requested, this is my response from PHP:
{"domain":"exp.cm","whois":"[Domain]\nDomain: exp.cm\nStatus: active\nChanged: 2014-02-25T12:22:00.957819+02:00\n\n[Holder]\nType: Legal person\nName: Name, Surname\nEmail: email#example.com\nPhone: Phone here\nAddress: Address goes here\nSome other info\n\nUpdated: 2014-03-18T18:12:35.717462+00:00\n"}
In this case you don't need the JSON datatype, just return html.
Additionally, you'll want the ajax request to be inside the click event. In your click event, you also forgot to pass the e parameter.
$domain = $_POST['domain'];
$whois = new Whois();
header("content-type:text/html");
$res = $whois->getWhois($domain); // Calls the Whois-query function;
echo $res;
js:
$('#submit').on('click', function(e) {
e.preventDefault();
var domain = $('#value').val();
$.ajax({
url: 'ajax/whois.php',
type: "post",
data: {'domain': domain, 'action': 'whois'},
//dataType: "json",
success: function(html) {
$('#whoisResult').html('<h2>Whois Query result for ' + domain + '</h2>');
$('#whoisContent').html(html);
},
error: function(xhr, status) {
$('#whoisResult').html('<h2>Sorry, an error occured. Try again later, please!</h2>')
}
});
});