Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

267
Visualizações
Run PHP script when button is clicked without refreshing page

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:

  1. Download the image from the URL to my server using PHP
  2. Display the image from the server (not from the URL, I know it's possible, but for my use I need it to be from the server) in an HTML image using JavaScript

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);
?>
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can do following things.

  1. Add jquery in head/bottom section of your page like
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  1. Use jquery AJAX and call your php script like below
        $("#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"); }
           });
        });
  1. In your php script ex- test.php, use code like below to get post params.
    $params = $_POST['data'];
    $path = $params['path'];
    $image_url = $params['image-url'];

and do the business operation, you want to do in this.

about 4 years ago · Juan Pablo Isaza Relatório

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda