2

This question already has an answer here:

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) {
e.preventDefault();
var formData = new FormData($(this).closest('form')[0]));
  $.ajax({
    url: "index.php?option=com_jsmdownload&task=imageUpload",
    type: "POST",
    data:  new FormData(formData),
    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 PHP function is not yet calling and I only see the below output

enter image description here

I dont 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.

One observation is that if I change the URL to a plain PHP file without importing the Joomla MVC then it works fine and I could see the below output.

enter image description here

Only problem is if I link to a component view then it doesn't called. Need some advice to fix this.

marked as duplicate by Valentin Despa Nov 22 '14 at 15:43

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1

You have to add '&tmpl=component' to your URL in the AJAX call to return just the component output, not the whole page.

Change

url: "index.php?option=com_jsmdownload&task=imageUpload",

to

url: "index.php?option=com_jsmdownload&task=imageUpload&tmpl=component",

Try that and see if it works.

  • Sorry unfortunately adding tmpl=component also result the same and doesn't work. One thing I noticed is if I set contentType=true then it calls the function correctly but the form values are not available. Any more suggestions!!! – Malaiselvan Nov 22 '14 at 15:02
  • What about adding '&format=raw' too? – fruppel Nov 22 '14 at 15:41
  • My bad... I forgot to add the hidden task field. After adding the hidden box <input type="hidden" name="task" value="imageUpload" /> in the default.php it started calling fine. Thanks for your help. – Malaiselvan Nov 22 '14 at 15:46

Not the answer you're looking for? Browse other questions tagged or ask your own question.