Home > Software engineering >  Why is my PHP script not being executed when calling it by AJAX JQuery?
Why is my PHP script not being executed when calling it by AJAX JQuery?

Time:04-20

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.

CodePudding user response:

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

  • Related