0

I want to execute a PHP script on a button click, which downloads an image from a URL to my server, through AJAX JQuery.

Here is the AJAX code in the .html file:

In the head section:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

In the body section:

<button type="button" id="btntest">Test PHP</button>

<script>
    $("#btntest").on('click',function(){
        alert("start");
        var data = {"image-url" : "/serverfolder/Image.png","path" : "https://example.com/Image.png"};
        $.ajax({
          type: 'POST',
          url: "test.php",
          data: data,
          success: function(resultData) { alert("success"); }
       });
    });
</script>

The code in the test.php file:

<?php
$params = $_POST['data'];
$path = $params['path'];
$image_url = $params['image-url'];
    
$data = file_get_contents($path);
$new = $image_url;
file_put_contents($new, fopen($data, 'r'));
?>

The problem: I don't get the "success" alert, instead I get an Internal server error for the test.php file. If test.php file only looks like this:

<?php
$params = $_POST['data'];
$path = $params['path'];
$image_url = $params['image-url'];
?>

The success alert appears, but that doesn't help me, because I want to download the file from the $path to the server directory $image_url. Any help appreciated on how to get this to work.

3
  • Display all PHP errors level to get the error message. Commented Apr 15, 2022 at 13:17
  • A 500/Internal Server error is a generic error message and covers pretty much every single thing that can go wrong with a PHP script. Check your server error logs to find out the exact error message. Commented Apr 15, 2022 at 13:20
  • Shouldn't the assignment to $params be more like $params = json_decode($_POST['data']) ? Commented Apr 15, 2022 at 13:27

1 Answer 1

1

you can send data in ajax like that

data:{data:data}

that is ok or you can send data like

data:{image_url : "/serverfolder/Image.png",path : "https://example.com/Image.png"}

in this shape you dont need to decode in php file and use like it

$path = $_POST['path']; 
$image_url = $_POST['image_url'];

THAT'S IT

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.