0

I am calling a PHP script from JavaScript. Whenever my function is called, I want to set tag=image. How can I do that?

function httpGetAsync(theUrl, callback) {
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function() { 
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
            callback(xmlHttp.responseText);
        }
    }
    xmlHttp.open("POST", theUrl, true); 
    xmlHttp.send(null);
}

httpGetAsync('storeImage.php');

The file storeImage.php looks like

<?php
$img = $_POST['tag'];
 $folderPath = "C:/xampp/htdocs/";

    $image_parts = explode(";base64,", $img);
    $image_type_aux = explode("image/", $image_parts[0]);
    $image_type = $image_type_aux[1];

    $image_base64 = base64_decode($image_parts[1]);
    $fileName = 't' . '.jpeg';

    $file = $folderPath . $fileName;
    file_put_contents($file, $image_base64);

    print_r($fileName);
    $command = escapeshellcmd("python C:/xampp/htdocs/generate_graph.py");
    $output = shell_exec($command);
    echo $output;
?>
  • Well, you have `xmlHttp.open("GET"` and then `$_POST['tag'];` so first you need to decide whether you want to be making a POST request or a GET request and then use the same term on both sides. – Patrick Q Nov 22 '19 at 13:04
  • i have updated my question.Now how can i do that? – Shafat Ahmed Nov 23 '19 at 09:18
  • Possible duplicate of [POST from XMLHttp with parameters](https://stackoverflow.com/questions/7071544/post-from-xmlhttp-with-parameters) – Patrick Q Nov 25 '19 at 14:34
  • Also https://stackoverflow.com/questions/9713058/send-post-data-using-xmlhttprequest – Patrick Q Nov 25 '19 at 14:35

1 Answers1

0

There are conflicts,

  1. In your xmlHttpRequest you are triggering a GET Request. But, In your storeImage.php, You are accessing POST data.

  2. The httpGetAsync functions get 2 parameters (theUrl, callback), But when you call the function, You only pass the url.

Correct Example Code

function httpGetAsync(theUrl){
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function() { 
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
          alert(xmlHttp.responseText);
        }
    xmlHttp.open("GET", theUrl + "getData=hello", true); 
    xmlHttp.send();
}
<?php

  echo $_GET['getData'];

?>

Please Take a tour https://www.w3schools.com/php/php_ajax_php.asp

BadPiggie
  • 3,374
  • 1
  • 7
  • 23