0

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 !

18
  • 2
    Your button is a submit button, and you did not prevent the default action - so this should be submitting the form the normal way, canceling any AJAX request you might have started, anyway. Commented Nov 5, 2021 at 9:39
  • 2
    Don't use inline onclick handlers and don't use any tutorials that use them. The proper way to handle that form submission is: $('form.Read_position').on('submit', function (e) { e.preventDefault(); /* more code here */ }); This will stop the regular form submission, which in your case reloads the document (thanks to the form having no action attribute). Commented Nov 5, 2021 at 9:46
  • 1
    Here's the code with the main and some other issues fixed: jsfiddle.net/vz3tmk4r Commented Nov 5, 2021 at 9:50
  • 1
    "even tho it's unrelated for this problem" - and with the level of knowledge & debugging skills you are currently showing here, you would be the right person to determine that ..? If your AJAX code goes into the error handler, then your server must have responded with an error HTTP status code, or a wrong content type - so of course what happens on the server side, is relevant here. You will need to figure out why it actually errors, but your isset statements there will surely never be true. (Because you are sending JSON, in which case PHP will not populate $_POST in the first place.) Commented Nov 5, 2021 at 9:52
  • 1
    "What i mean by unrelated is because my actual problem is just outputing the input value in an alert box once sent." - but you are not trying to output the value you are sending, you are trying to output the response you get from the server. Commented Nov 5, 2021 at 9:58

1 Answer 1

1

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();

?>
Sign up to request clarification or add additional context in comments.

19 Comments

Thank you ! The code is way cleaner like that indeed. I still get the HTML code in the success() alert box and console nonetheless. I can't get my head on why that happens.
Maybe there is some HTML code before the <?php tag in your file? If so, you should move this PHP code to the beginning of the file.
Anyway if the answer has helped you, please remember to mark it as "accepted" and/or upvote it - thanks :-)
There is actually no HTML at all in the get_pos.php file. All the HTML is in the main file (with the JavaScript code above)
Also it's a bit weird because using console.log() on either $('pos_x").val() or $('pos_z").val() actually outputs the numbers. But the result differs.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.