0

The code posts two variables to a MySQL table. The code seems to work perfectly - the only thing that doesn't work is the echo statements. What would cause this?

I'm testing the file locally using MAMP, and the PHP version is up to date. I can't think of anything else that might be causing the problem. The SQL "insert" statements are working perfectly, and every other aspect of the code seems to go off without a hitch.

HTML

    <body>
    <div>
        First Name: <input type="text" id="fname" name="fname" />
        <button id="submitMe" onclick="postData()">Click Here</button>
    </div>
</body>

JS

            function postData(){
            //HTML variable
            var fname = document.getElementById("fname").value;
            //Javascript Variable
            var sname = "Second Name";


            var http = new XMLHttpRequest();
            var url = "index.php";
            var params = "fname="+fname+"&sname="+sname;
            http.open("POST", url, true);

            http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            http.onreadystatechange = function() {
                if(http.readyState == 4 && http.status == 200){
                    //alert(http.responseText);
                    alert("Request recieved");
                }
            }
            http.send(params);

        }

PHP

<?php

if(!empty($_POST)){
$fname = $_POST['fname'];
$sname = $_POST['sname'];

$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "tutorials";

$conn = new mysqli($servername, $username, $password, $dbname);
if($conn->connect_error){
    die("Connection failed".$conn->connect_error);
}

$sql = "insert into tutorials_tbl(firstname, lastname) values('".$fname."', '".$sname."')";

if($conn->query($sql) === TRUE){
    echo "New Record created successfully";
}else{
    echo "Error: ".$sql."<br/>".$conn->error;
}

$conn->close();
}
?>
Shadow
  • 33,525
  • 10
  • 51
  • 64
  • 1
    where are you expecting this to output at? in your dev tools/network panel? – Napoli Mar 13 '18 at 06:42
  • Where do you expect the `echo`-ed strings to show? They are the body of the response but you send the request to the server using AJAX and you don't do anything with the response. – axiac Mar 13 '18 at 06:47
  • I was expecting them to show in-browser via html, as they do if I add an Echo statement above the IF statement. Does this make sense? – John Alledras Mar 13 '18 at 06:50
  • The PHP code is exposed to SQL injection. Better use [prepared statements(https://stackoverflow.com/a/60496/4265352). – axiac Mar 13 '18 at 06:53
  • You can check the response of the AJAX request in the webdeveloper tools console. – axiac Mar 13 '18 at 06:54
  • Thanks Axiac for bringing this to my attention! Much appreciated – John Alledras Mar 13 '18 at 06:57

3 Answers3

0

To echo the PHP statements into your main document, you need to get it via your AJAX script.

HTML

Add this where you want the output to be.

<span id="output"></span>

JS

if (http.readyState == 4 && http.status == 200){
    alert("Request recieved");
    document.getElementById("output").innerHTML = this.responseText;
}

this.ResponseText is getting the output of your PHP document.

XantiuM
  • 132
  • 1
  • 16
  • 1
    `InnerHTML` is not a property of a DOM [`Element`](https://developer.mozilla.org/en-US/docs/Web/API/Element). It doesn't do what you think it does. The one you are looking for is [`innerHTML`](https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML). – axiac Mar 13 '18 at 07:02
  • Thank you, XantiuM and Axiac. This worked...but oddly, the entire html is now re-executing. I get a new "submit" form beneath the old one. Any idea why? – John Alledras Mar 13 '18 at 13:44
0

What would cause this? (...) I can't think of anything else that might be causing the problem.

It is important to understand the difference between server-side and client-side execution when doing web programming.

Refer to this excellent question (and answers): What is the difference between client-side and server-side programming?.

Both HTML and javascript are client-side languages*. They run in the browser, which is the client.

PHP, however, is server-side (it runs on the "server").

In your case, even though you have everything running locally with MAMP, there is still both a client and server. They just happen to be on the same machine. The server is Apache, and it runs PHP code through the php executable.

Wikipedia says (emphasis mine):

MAMP is an acronym of macOS, the operating system; Apache, the web server; MySQL, the database management system; and PHP, Perl, or Python, all programming languages used for web development.

Now, in your example, you have a simple HTML document, with an input field of type "text" and a submit button. Normally, both the input field and the submit button would be part of a <form> element, but in your code, there is no <form>. Instead, you use some javascript to perform the "submit" to the server.

Can you see it? You have the browser run some javascript code, which makes a request to the server. The server processes the request, returns some text but this is never parsed by the javascript who requested.

In your code, I believe you can just uncomment this line:

//alert(http.responseText);

and it'll show a popup alert with the message from your echo statement.


(*) there can be exceptions, none of which are relevant here.

Marc.2377
  • 7,807
  • 7
  • 51
  • 95
-3

Yes, The insert query is not perfect. Pls remove double quotes and use only single quotes.