I am trying to upload a image using AJAX jquery in a Joomla MVC framework.
Below is the default.php which adds the below javascript script code
$('#icon-submit').on('click',(function(e) {
$.ajax({
url: "index.php?option=com_jsmdownload&task=imageUpload",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
alert(data);
},
error: function(){
}
});
}));
Below is the HTML code which contains a simple file box and a button
<form action="<?php echo JRoute::_('index.php'); ?>" method="POST" name="adminForm" id="adminForm" enctype="multipart/form-data">
<input type="file" id="and_36x36" name="and_36x36">
<input id='icon-submit' type='button' value='Next ->' />
</form>
Below is the PHP code in controller.php for the imageUpload task.
function imageUpload(){
JFactory::getDocument()->setMimeEncoding( 'application/json' );
print_r($_FILES);
JFactory::getApplication()->close();
}
Once I select the file and click on the button the ajax function called and the PHP function also called but the form data is not available inside.
The print_r command always prints an empty array. I don't know what I am doing wrong. I want to get the selected file and upload them into the server and return back to the browser.
I referred multiple posts and cant able to find an answer. Can someone please advice.
UPDATE 1
If I set a independent PHP file as URL then it works. For example
url: "http://localhost/test/indextest.php",
But If I set the Joomla component path with controller it doesn't work.
You have to pass the form to the FormData object, what you have is the button.
in the button click event handler this refers to the button not the form.
Select the form and pass it to the FormData constructor
new FormData($(this).closest('form')[0]),
Related
I use the following code successfully (with different IDs, etc.) to preview a banner image in a div after PHP validates the upload, using AJAX. This works just fine. No issues.
I am having a problem doing the same with a video. The code below works well, except the video doesn't preview. Just echos back the alt tag value. I am passing the uploaded video ID to a hidden input for some back end PHP validation via ajax function. After validation, the video is moved to the folder I want it to move to without a problem. I also echo back an error if the video doesn't meet requirements. This is all good. The video just doesn't show on the page. Any help is appreciated.
<div>Upload Video</div>
<div><input type="file" id="banner-video"></div>
<div id="loading"></div>
<div class="padding-top-1" id="show-video"></div>
<script>
$(document).ready(function() {
$("#banner-video").change(function() {
var data = new FormData();
data.append("file", $("#banner-video")[0].files[0]);
$.ajax({
url: "create-promotions/video-banner-promotions/create-promotion.video.process-banner-video.php",
method: "POST",
data: data,
contentType: false,
processData: false,
cache: false,
beforeSend: function() {
$("#loading").load("../loading.php");
},
success: function(data) {
$('#loading').hide()
$('#show-video').html(data); // ********** This line seems to be the problem
if ($('#show-video').find('img').length) {
bannerVideo = $('#show-video').html(data);
document.getElementById("the-banner-video").value =
bannerVideo
}
}
});
});
});
</script>
<input type="hidden" id="the-banner-video" value="">
Nevermind. After 3 days of working on it, it was just using the wrong tag on my back end php echo. The code works. Feel free to use it if you ever come across it. Let me know if you would like the other pieces.
I am trying to upload data in database.
I using tinymce plugin to textarea editor. When I submit my data, textarea value uploads empty text. Please find below the frontend and backend code.
Frontend Code:
<form id="upload" enctype="multipart/form-data" method="post">
<textarea class="tinymce" name="product_tip" id="product_tip" placeholder="" col="5"></textarea>
<input type="button" name="submit" value="Submit" class="upload-btn"/>
</form>
Backend Code:
<?php
$product_tip=$_POST["product_tip"];
if(empty($product_tip)) {
echo "<div class='alert alert-danger'>Please enter Product tips.</div>";
}
else{
$result=mysqli_query($conn, "INSERT INTO product(tip) VALUES ('$product_tip')")or die("Could not retrieve image: " .mysqli_error($conn));
echo 1;
}
?>
and this my connection code for frontend and backend file.
$(document).ready(function(){
$('.upload-btn').click(function(){
var formdata=new FormData($('#upload')[0]);
$.ajax({
url:'includes/backend_product_upload.php',
method: "POST",
async: false,
cache: false,
contentType: false,
processData: false,
data : formdata,
success:function(answer_from_actionpage){
if(answer_from_actionpage == 1){
$('.error').html("<div class='alert alert-success'>Successfully Product Upload</div>");
//$('.form-control').val("");
}else{
$('.error').html(answer_from_actionpage);
}
}
})
});
});
Add tinyMCE.triggerSave(); in connection file like this-
$('.upload-btn').click(function(){
tinyMCE.triggerSave();
var formdata=new FormData($('#upload')[0]);
$.ajax({
url:'includes/backend_product_upload.php',
method: "POST",
async: false,
cache: false,
contentType: false,
processData: false,
data : formdata,
success:function(answer_from_actionpage){
if(answer_from_actionpage == 1){
$('.error').html("<div class='alert alert-success'>Successfully Product Upload</div>");
//$('.form-control').val("");
}else{
$('.error').html(answer_from_actionpage);
}
}
})
});
By default, TinyMCE will automatically update the underlying <textarea> when the form is submitted via standard HTML form submission. This is built-in behavior in TinyMCE as the overhead of keeping the <textarea> constantly in sync is not needed for most applications.
If you are not relying on a standard HTML form submission event you have a couple of options...
When you start the AJAX form submission process:
TinyMCE has a triggerSave() method that forces the editor to sync with the <textarea> immediately.
https://www.tinymce.com/docs/api/tinymce/root_tinymce/#triggersave
You can call the triggerSave() first thing when your user wants to submit the form and then perform your validation.
TinyMCE Events:
As your response to your own question shows you can certainly rely on various editor events to sync the editor to the <textarea> via the triggerSave() method. There is no technical issue with this just know that you will likely trigger a large number of these events if you rely on something like the change event. If you have large/complex HTML content or many editors on one page constantly syncing with the underlying <textarea> may impact the browser's performance.
Which is better?
If you DON'T need real time validation of the content... just calling triggerSave() at the start of the AJAX submission process is probably easier (no TinyMCE configuration code tied to an event needed) and creates less overhead for the browser.
If you DO need real time validation of the content... using an event like the change event to sync the <textarea> is the better solution. It might look like this:
tinymce.init({
selector: "#myTextarea",
...
setup: function (editor) {
editor.on('change', function () {
tinymce.triggerSave();
});
}
});
I am just wondering how I can append a view within Laravel to my page using AJAX.
So when I didn't use Laravel I would have just done something like this:
$.ajax({
url: "your.html",
success: function (data) { $('body').append(data); },
dataType: 'html'
});
That would have then appended my html file to the current page. I am just wondering what is the cleanest way to do this with a Laravel View?
UPDATE: I forgot to mention that the View in question would be a html form. Nothing resource heavy.
So with the laravel you goes like this:
$.ajax({
url: "get-form",
success: function (data) { $('body').append(data); },
dataType: 'html'
});
Now in your routes.php you define:
Route::get('get-form', function() {
return view('form');
});
And your view file let's say: form.blade.php:
<form action="...">
(...) // here goes form
</form>
This should create an ajax request/response relation on the page. Each time you call ajax request new form will be rendered into body.
Let's assume you have your form hardcoded but hidden in html (could also be included via blade)
<div id="my-hidden-form" style="display:none;">
<form ...>
<!-- form goes here -->
</form>
</div>
<div id="my-forms"></div>
Then you could simply clone your hidden form to create new ones
$( "#my-hidden-form form" ).clone().appendTo( "#my-forms" );
Without knowing further details it's still hard to tell if this matches all your requirements. However, it will dynamically add forms (as you needed) and in addition it will not require an ajax call or mess up your html.
Using blade to include the form this will be even more structured.
I have implemented music to play throughout the website in header.phtml using html5 audio tag and user has the option to click on an icon to mute the music. The action works in the following steps:
1) Icons are wrapped under forms whose code is given below:
<form method="post" id="unmute_form" action="process_unmute.php">
<input type="submit" id="mute" name="mute" value="" style="background: url('music/mute.png')" />
</form>
<form method="post" id="mute_form" action="process_mute.php">
<input type="submit" id="mute" name="mute" value="" style="background: url('music/speaker.png')" />
</form>
2) User clicks on mute icon and form is being submitted via ajax to an external php file to set magento session with the following code:
require_once ("../app/Mage.php");
Mage::app();
Mage::getSingleton('core/session')->setMuted('true');
3) Form submission via ajax using jQuery:
$("form#mute_form").submit(function() {
$.ajax({
url: "musicFolderAtRoot/process_mute.php",
type: "POST",
data: { },
dataType: "json",
success: function(data) { }
});
return false;
});
The same logic i had already applied in a php project and it is working fine but in Magento process_mute.php file is not setting session value.
Any clue how i can call my php file from phtml file, i think my php file is unable to set session because of placing php file in the wrong directory so it is inaccessible for session (tried root/folder and app/design/frontend/base/default/template/page/html/)
OR
I need to create a magento module to have this simple session setting functionality (painful task for this small task)
I desire to upload files asynchronous when the user select a file in a input file, with $.ajax. But the php that recive the call return index undefined.
The jquery code is the next:
$("#urlimatge").change(function(){
var filename = $("#urlimatge").val();
$.ajax({
type: "POST",
url: "utils/uploadtempimg.php",
enctype: 'multipart/form-data',
data: {'urlimatge' : filename },
success: function(response){
alert(response);
}
});
});
and the php that recibe the call:
$image = new gestorimatges();
$target_path = $image->uploadTemp($_FILES['urlimatge']['name'],$_FILES['urlimatge']['tmp_name']);
Thanks
you cannot pass the $_FILE from AJAX to PHP.
I would suggest use a plugin
It will make your life easier :) Here is a video tutorial to help too
You might wanna use tools like uploadify for that.
You can't upload files with AJAX, but you can use an iframe so you don't have to refresh the current page.
Many people go strait to plugins but you can do this yourself pretty easily, and with all the functionality of an AJAX request.
Instead of using an AJAX function, have a form submit to a hidden iframe that has a load event handler attached to it so when the form is submitted, you have a callback function that actually includes the server response (the HTML of the iframe after it loads).
Example:
HTML --
<form action="..." method="post" encrypt="application/x-www-form-urlencoded" target="workFrame" >
<input type="file" name="file" />
<input type="submit" />
</form>
<iframe id="workFrame" src="about:blank" style="display:none;"></iframe>
JS --
$(function () {
$('form').on('submit', function () {
//check if the form submission is valid, if so just let it submit
//otherwise you could call `return false;` to stop the submission
});
$('#workFrame').on('load', function () {
//get the response from the server
var response = $(this).contents().find('body').html();
//you can now access the server response in the `response` variable
//this is the same as the success callback for a jQuery AJAX request
});
});