I'm having trouble using PHP and JavaScript.
Goal: When the event listener for an HTML button in a .js file is called, the .php script should be executed, without reloading the page.
Expected results: When the button is clicked, the PHP script will be executed. In my case, the file from the URL will be downloaded to the server.
Actual Result: I don't know how to call a PHP script from a JavaScript file.
I tried using AJAX but nothing worked. And I don't know where to put the JQuery library reference.
I also tried using a form and putting an input in it (type="submit"), but when the PHP function is called, it refreshes the page and everything on the page that says client side disappears.
HTML button:
<button type="button" class="button" id="btnsubmit">Submit</button> <img class="image" id="someimage">
JavaScript event listener (I have assigned the button and image to variables):
btnsubmit.addEventListener("click", () => { someimage.src = "directory/downloadedimg.png"; });
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 generally when a button is clicked I want to do the following:
I tried @Abhishek's answer and found that the problem is now in my php file. It always gives me an internal server error. Do you find any errors in this code, uploading image from $path (which is 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); ?>
P粉5474204742024-02-18 09:55:32
No other libraries required, you can use vanillaJs to accomplish this.
Your misunderstanding comes from: "How to call php with Js and get the return value"
Starting here, you have an example: https://www.w3schools.com/php/php_ajax_php.asp
Once you are able to call the PHP script, you are 70% of your goal
P粉7878203962024-02-18 00:14:54
You can perform the following operations.
sssccc
$("#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 conduct the business operations you want to do.