0

I have an AJAX code;

<script>
function copy_file() {
    $.ajax({
        url: 'copy.php',
        success: function(data) {
        if (data == 'true') {
            alert('The file has been copied');
        }
    }
});        
</script>   

Below, my PHP code;

<?php
function copyFile($test_image, $base_image) {
    copy($test_image, $base_image);          
}
?>

And here, my HTML code;

<label><input type="button" name="button" value="copy files" onclick= copy_file('c:\path1','c:\path1')">

How can pass multiple values (by values, I mean path) from AJAX to PHP?

What am I doing wrong and how can I fix it?

nyedidikeke
  • 6,899
  • 7
  • 44
  • 59
Kevin
  • 217
  • 6
  • 19
  • Why do you want to copy files on AJAX request? – zavg Dec 23 '13 at 19:35
  • http://stackoverflow.com/questions/2320069/jquery-ajax-file-upload – brandonscript Dec 23 '13 at 19:35
  • 1
    There's nothing to AJAX. it's just http requests. The fact that they're done "silently" in the background is irrelevant - it's still just an HTTP request. The **EXACT** same mechanics that apply for a normal form submission apply to ajax calls: You need to pass around relevant information. – Marc B Dec 23 '13 at 19:36
  • I tried with js activeobject to copy files, but it only works on ie and for all browser, I need to have copy button and I want to do with ajax and php. can somebody fix the code? – Kevin Dec 23 '13 at 19:39

1 Answers1

3

You can do this in your ajax file :

<script>

     $('input[type=button]').click(function(){
               $.ajax({
                  type : 'POST',
                  url: 'copy.php',
                  data : {action: 'copy'},
                  success: function(data) {
                  if(data == 'true'){
                  alert('The file has been copied');
                   }
                }
               });

      });
</script>   

Explanation : On the click of the button, an AJAX Request is sent to the php file. I have included the type and data option to the ajax function.

The data contains the variable sent to the PHP Script. In this case, I have named the variable 'action'. The value this variable contains is specified after the colon (In this case, its copy. You can add more).

In your PHP script do this :

<?php

       if(isset($_POST['action'])){
         if($_POST['action'] == 'copy'){
            copy($test_image, $base_image);          
         }
       }
?>

It checks if the variable is received, using the $_POST['action'] If it is received, it then checks if the action is to copy. If it is, then you can use the copy function.

This way, you can add more functionality in your scripts. For example, you can send a variable named action to the PHP script which has value 'delete'. In PHP, you can check this way :

if($_POST['action'] == 'delete'){
   //Delete file
}

NOTE : jQuery library must be included

Shahlin Ibrahim
  • 1,049
  • 1
  • 10
  • 20