I have a problem with PHP and JavaScript.
Goal: A .php script should be executed when the event listener of the HTML button in the .js file is called without reloading the page.
Expected result: When the button is clicked, the PHP script gets executed. In my case, a file from a URL will be downloaded to the server.
Actual result: I don't know how to call the PHP script from the JavaScript file.
I tried using AJAX, but nothing really worked out. Also I didn't know where exactly to put the library reference for JQuery.
I also tried to use a form, and inside of it an input (type="submit"), but when this calls the PHP function, it refreshes the page and everything on the page which was displaying client side is gone.
The HTML button:
<button type="button" class="button" id="btnsubmit">Submit</button>
<img class="image" id="someimage">
The JavaScript event listener (I have the button and image already assigned to a var):
btnsubmit.addEventListener("click", () => {
someimage.src = "directory/downloadedimg.png";
});
The PHP script:
<?php
$path = 'https://somewebsite.com/imagetodownload.png';
$dir = 'directory/downloadedimg.png';
$content = file_get_contents($path);
$fp = fopen($dir, "w");
fwrite($fp, $content);
fclose($fp);
?>
So in general, I want to do as follows when the button gets clicked:
I tried the answer of @Abhishek and figured the problem now lies in my php file. It always gives me an internal server error. Do you spot any error in this code to upload the image from the $path (it's a URL) to my server (serverdirectorypath is $image_url):
<?php
$params = $_POST['data'];
$path = $params['path'];
$image_url = $params['image-url'];
$content = file_get_contents($path);
$fp = fopen($image_url, "w");
fwrite($fp, $content);
fclose($fp);
?>
You can do following things.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
$("#button-id").on('click',function(){
var data = {"image-url" : "directory/downloadedimg.png","path" : "https://somewebsite.com/imagetodownload.png"};
$.ajax({
type: 'POST',
url: "{hostname}/test.php",
data: data,
dataType: "json",
success: function(resultData) { alert("success"); }
});
});
$params = $_POST['data'];
$path = $params['path'];
$image_url = $params['image-url'];
and do the business operation, you want to do in this.
No need another library, you can do this with vanillaJs.
Your misunderstanding come from : "how to call php with Js and get returned value"
Start here you have an exemple: https://www.w3schools.com/php/php_ajax_php.asp
Once you will be able to call your PHP script you will have done 70% of your target