Error sending parameter to a PHP server using AJAX (No Jquery)

Asked

Viewed 53 times

0

Hello, I’m trying to pass a simple parameter to a PHP server using AJAX and I’m not getting this parameter in PHP. The error returned is that the index "parameter" of the GET method is not defined. It follows below the codes

ajax function :

function AJAX(){
                var xmlhttp = new XMLHttpRequest();
                xmlhttp.open('POST','./functions/adicionafoto.php', true);
                var data = "parametro=OK"
                xmlhttp.send(data);
                xmlhttp.onreadystatechange=function(){
                if (xmlhttp.readyState == 4){
                    if(xmlhttp.status == 200){
                        console.log(xmlhttp.responseText)

                    }
                }
                };
            }

PHP server code :

<?php
    session_start();

    $parametro = $_GET['parametro'];

    echo $parametro;
?>

Error returned: Undefined index: parameter

Does anyone have any idea why this is happening?

1 answer

0


First thing: you are making a POST type request and trying to receive the GET type.

xmlhttp.open('POST','./functions/adicionafoto.php', true);
$parametro = $_GET['parametro'];

Change to $parametro = $_POST['parametro'];

Second thing: add this header

xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

Your code will look like this:

function AJAX() {
     var xmlhttp = new XMLHttpRequest();
     var data = "parametro=OK"
     xmlhttp.open('POST', './functions/adicionafoto.php');
     xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
     xmlhttp.send(data);
     xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4) {
           if (xmlhttp.status == 200) {
              console.log(xmlhttp.responseText)

           }
        }
     };


  }

  AJAX()

If you want instead of using Xmlhttprequest, you can use Fetchapi. Your code will look like this:

const fetchApi = async () => {

     const options = {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: "parametro=OK"
     }

     try {
        const response = await fetch('./functions/adicionafoto.php', options)
        const result = await response.text()
        console.log(result)
     } catch (err) {
        console.error(err)
     }

  }

fetchApi()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.