0

From a javascript, I'm trying to call a php script which, at its turn, will generate a text file.

To this end, I'm using an ajax script. However, I notice that my text file is never created. I believe that the php is never called.

My javascript :

$.ajax({
type: "POST",
url: "php/test.php",
dataType: "json",
success : function(code_html, statut){
},
error : function(resultat, statut, erreur){
},
complete : function(resultat, statut){
}
});

My php (test.php) :

<?php

    file_put_contents('test2a.txt', 'I am a test');

?>

Any idea what I'm missing here ?

2
  • 2
    does browser console show errors? Commented Nov 25, 2019 at 21:29
  • Make sure that you calling ajax, path in ajax is right. Commented Nov 25, 2019 at 21:40

1 Answer 1

1

Your ajax and php code look good.

Add some debugging lines to help troubleshoot.

When you run this code, click the button to do the post. You should then see some console messages stating either success for failure from the ajax.

I believe this is a working sample of what you are trying to do, you can use whatever version of jQuery that you want.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>

    <button id="btnDoThePost">Do The Post</button>

<!-- Jquery JS file -->
<script type="text/javascript" src="jquery-1.11.3.min.js"></script>

<!-- Custom JS file -->
<script type="text/javascript" src="script.js"></script>

</body>
</html>

script.js

function callTestPHP() {

$.ajax({
    type: "POST",
    url: "php/test.php",
    dataType: "json",
    success : function(code_html, statut){
        console.log("test.php: Sucess!");
        console.log(JSON.stringify(code_html));
    },
    error : function(resultat, statut, erreur){
        console.log("test.php: Error!");
        console.log(JSON.stringify(resultat));

    },
    complete : function(resultat, statut){
        console.log("test.php: Complete!");
        console.log(JSON.stringify(resultat));
    }
    });
}


$(document).ready(function () {

    $("#btnDoThePost").click(function (){
        callTestPHP();
    });

});

The php file should return some JSON for the ajax to parse.

test.php

    // write to file

    file_put_contents('test2a.txt', 'I am a test');

    // return something for ajax to work with

    echo "{ \"data\": \"Success\" }";

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

Comments

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.