Home > Software engineering >  Ajax request outputing HTML Code instead of form value
Ajax request outputing HTML Code instead of form value

Time:11-05

As the title says, i have been having a problem with Ajax for 2 days now and can't seem to find why. I looked it up but didn't find a suiting solution.

Here is the code i am using :

<!DOCTYPE html>
    <html>
    <head>
        <title>Test_unity</title>
    </head>
    <style type="text/css">
    
    .Read_position {
        max-width: 100%;
        display: flex;
        flex-direction: column;
        align-items : center;
        padding: 10px;
        box-shadow: 0px 0px 20px #2c3e50;
        margin: 10%;
    }
    
    .DivForm {
        display: flex;
        flex-direction: column;
        justify-content: center;
    }
    
    .text-align{
        text-align: center;
    }
    
    </style>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
    <script type="text/javascript">
    
  
        jQuery(document).ready(function(){
          console.log("jQuery est prêt !");
        });
    
    
        function ajax_request(){
            console.log("RequeteAjax pos_unity");

            let tmp_x = $('#pos_x').val();
            let tmp_z = $('#pos_z').val();
            console.log(tmp_x   " "   tmp_z)

            $.ajax({            
                url :"get_pos.php",
                type :"POST",
                data : JSON.stringify({
                  pos_x : tmp_x,
                  pos_z : tmp_z 
                }),
                contentType: "application/json",
                dataType: "json",
                success : function(text,state){
                    console.log("operation reussi : " text);
                    alert("tmp : " text);
                },
                error : function(result, state, error){
                    //alert("resultat : " result " / statut " state " / erreur : " error);
                    alert("error : \n"   result.responseText);
                },
                complete : function(result, state){
                  alert("complete : " result " / statut " state);
                  console.log(tmp_x   "/"   tmp_z)
                }
            })
        }
    </script>
    <body>
    <?php
    echo('
      <form class="Read_position" method="post" name="main_form" action=""> 
        <p class="text-align"><b>Envoyer une position a Unity : </b></p>
        <div class="DivForm">
          <label for="pos_x">Position X : </label><input type="number" id="pos_x" name="pos_x">
        </div>
        <div class="DivForm">
          <label for="pos_z">Position Z : </label><input type="number" id="pos_z" name="pos_z">
        </div>
        <button type="submit" name="entree"style="margin-top:10px;" onclick="ajax_request()">send positions</button>
      </form>
      <br>
    ');
    ?>
    </body>
    </html>

What i am trying to do with that Ajax request is to get the form value entered by user and display it (for now) in an alert box.

Here's the code from get_pos.php as it has been asked :

<?php

$pos_x = 0;
$pos_z = 0;
$file = "positions_unity.txt";
$error_msg = "ERROR" ;

if( isset($_POST["pos_x"]) && isset($_POST["pos_z"]) ) {
    $data = $_POST["pos_x"] "/" $_POST["pos_z"];
    file_put_contents($file, $data);
    exit();
} else if(file_get_contents($file) === "" ) {
    file_put_contents($file, $error_msg);
    echo(file_get_contents($file));
    exit();
} else {
    echo(file_get_contents($file));
    exit();
}

?>

Here is what is displayed instead by the error function :

error :
<!DOCTYPE html>
<html>
<head>
    <title>Test_unity</title>
</head>
<style type="text/css">

.Read_position {
    max-width: 100%;
    display: flex;
    flex-direction: column;
    align-items : center;
    padding: 10px;
    box-shadow: 0px 0px 20px #2c3e50;
    margin: 10%;
}

.DivForm {
    display: flex;
    flex-direction: column;
    justify-content: center;
}
...

Expected output would be whatever the user types in.

If you have any idea please let me know.

Thank you in advance !

CodePudding user response:

There are a number of issues occurring here:

  1. Not handling the default form submission properly and prevent it in order to launch the AJAX code
  2. Sending JSON in the AJAX request but not configuring PHP to expect JSON
  3. Sending plain text in the PHP response, but configuring jQuery to expect JSON.
  4. In the case where the user submits some data, your code will store them in the file, but not output them again. Currently it's only programmed to output the file contents when no POST values were submitted.

This should sort out all those issues:

HTML:

<button type="submit" name="entree"style="margin-top:10px;">send positions</button>

(just removed the old-fashioned inline onlick)

Javascript:

jQuery(document).ready(function() {
  $('form.Read_position').on('submit', function(e) { //better event handler
    e.preventDefault(); //prevent default postback
    console.log($('#pos_x').val()   " "   $('#pos_z').val())
    
    //send normal form data, no JSON in either direction
    $.ajax({
      url: "get_pos.php",
      type: "POST",
      data: {
        pos_x: $('#pos_x').val(),
        pos_z: $('#pos_z').val()
      },
      success: function(text) {
        console.log("operation reussi : "   text);
        alert("tmp : "   text);
      },
      error: function(result, state, error) {
        alert("error : \n"   result.responseText);
      },
      complete: function(result, state) {
        alert("complete : "   result   " / statut "   state);
        console.log(tmp_x   "/"   tmp_z)
      }
    })
  });
});

PHP:

<?php
$file = "positions_unity.txt";
$error_msg = "ERROR" ;

if( isset($_POST["pos_x"]) && isset($_POST["pos_z"]) ) {
    $data = $_POST["pos_x"] "/" $_POST["pos_z"];
    file_put_contents($file, $data);
} 
else if(file_get_contents($file) === "" ) {
    file_put_contents($file, $error_msg);
}

//always echo the data. HTML-encode it to protect against XSS
echo(file_get_contents(htmlspecialchars($file)));
exit();

?>

CodePudding user response:

Here this example get ajax request in php:

$postRequest    = file_get_contents("php://input");
$receiveRequest = json_decode(stripslashes(isset($_REQUEST['data']) ? $_REQUEST['data'] : $postRequest));

$pos_x=$receiveRequest['pos_x'];
  • Related