0

Hi there am a beginner in php and ajax, was trying to create a simple admin page which only submit a message and the message get stored in a mysql database. (via ajax ) however it seems that the no data is being parse through when I hit the submit button(I coded it so that when the submit button is pressed, the message would be send without the page refreshing).

Could someone check to see where my error could be? thank you

admin.php

<!DOCTYPE html>
<html>
<head> <!--inseart script here -->
    <script type= "text/javascript" src="js/jquery.js"></script> 
</head>

<body>
    Message: <input type="text" name="message" id= "message_form"><br>      


    <input type="submit" id= "submit_form" onclick = "submit_msg()">


    <script type= "text/javascript" src="js/func_submit_msg.js">     </script> 
</body>

</html>

I have created a separate function file called func_submit_msg.js

//this is a function file to submit message to database

$(document).ready(function submit_msg(){
alert('worked');
$.ajax({
    type: "POST",
    url: "submit_data.php"
    data: { message: message_form},
})
}

a connect.php file is created to connect to mysql database

<?php

        $host = "localhost";
        $user = "root";
        $pass = ""; // phpMyAdmin mysql password is blank ? i believe

        $database_name = "test"; //
        $table_name = "test_table_1";  //table that will be accessing

        //connect to mysql database
        $db = new mysqli($host, $user, $pass, $database_name); 

        //check connection? 
        if ($db -> connect_error) {
            die("error mysql database not connected: " . $db -> connect_error);
        }
        else {
            echo "connected successfully" ; 
        }

?>      

a submit_data.php file is created to submit to database

<?php
include "connect.php";

$insert_data=$db-> query ("INSERT INTO test_table_1(message) VALUES ('$message_form')");


if ($db->query($insert_data === TRUE) ){
    echo "New record created successfully";
} else {
    echo "Error: " . $insert_data . "<br>" . $cdb->error;
}

$db->close();

?>

error checking code to check whether database was inserted correctly doesn't even echo out whether it is successful or not.

Updated

submit_data.php as per @ Maximus2012 suggestion

<?php
include "connect.php";

$insert_data=$db->query("INSERT INTO test_table_1(message) VALUES ($_POST['message_form'])");


if ($insert_data === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $insert_data . "<br>" . $cdb->error;
}

$db->close();

?>

No error display but there isn't any data being recorded in the database still.

21
  • Try $_POST['message_form'] in place of $message_form in the insert query in submit.php. This may not be entirely secure though. Commented Apr 6, 2015 at 19:35
  • Also, in your code, you are calling the query function twice while you need to do that only once in submit.php. $insert_data=$db-> query (" should be $insert_data=$db->query(" (remove extra spaces) Commented Apr 6, 2015 at 19:38
  • @Maximus2012 what do you mean by calling it twice? i thought i had to do it as one of them is to insert a table the other is doing an error checking? Commented Apr 6, 2015 at 19:48
  • if ($db->query($insert_data === TRUE) ){ should be if ($insert_data === TRUE){ . You don't need to call the query function twice like this. Commented Apr 6, 2015 at 19:50
  • 1
    WARNING: When using mysqli you should be using parameterized queries and bind_param to add user data to your query. DO NOT use string interpolation to accomplish this because you will create severe SQL injection bugs. NEVER put $_POST data directly into a query. Commented Apr 6, 2015 at 19:58

1 Answer 1

1

You should start by adding your success callback to your Ajax: (if you havent already)

$(document).ready(function(){

  $('#submit_form').on('click', function(e){
    e.preventDefault();
    message_form = $('#message_form').val();

    $.ajax({
        type: "POST",
        url: "submit_data.php",
        data: {message: message_form},
            success: function(data) {
              $('#result').html(data);
            },
            error:function(err){
               //handle your error
               alert('did not work');
            }
    });
  });
}); 
  • Here we use .on() as the preferred method of attaching an event handler function
  • We then use .val() to get the value of the message input field and store it in a variable to be used for POSTing to the submit_data.php script
  • e.preventDefault() is used so that the default event is cancelled when click the submit button


In your html, add an element that the result can be returned to: (#result)

<html>
<head> 
    <script type= "text/javascript" src="js/jquery.js"></script>
    <script type= "text/javascript" src="js/func_submit_msg.js"></script>
</head>
<body>
    <form action="" method="POST">
    Message: <input type="text" name="message" id="message_form"><br>      

    <input type="submit" id="submit_form">
    </form>
    <div id="result"></div>

</body>
</html>
  • Here we wrap your input in a form with the method and action properties to ensure that the name attributes are able to be used in POST requests


In your PHP (submit_data.php) you need to assign a value to $message_form before using it:

<?php
include "connect.php";

$message_form = $_POST['message'];

$insert_data=$db->query("INSERT INTO test_table_1(message) VALUES ('$message_form')");


if ($insert_data === TRUE ){
    echo "New record created successfully";
} else {
    echo "Error: " . $insert_data . "<br>" . $cdb->error;
  }

$db->close();
?>

If all goes well, you should get some kind of result from this.

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

5 Comments

Nope it doesn't work, and it seems that the <div> id=result doesn't display anything .whether it was successful or not
I believe the submit_data.php file is working fine now as it can create blank entry when run by itself, so it seems that the ajax function that is parsing data to the submit_data.php doesn't seem to work as it should
I have changed the Ajax and HTML. Try it this way, without the onclick="..." and with the inputs wrapped in a <form> to make sure your data gets posted
M.doye sorry it works now, the ajax file that i had was different. thanks a lot . by the way what does this mean in your ajax file function(e){ e.preventDefault(); why did you put e inside it? i saw this in a few examples when i googled but never understood
thanks for your help would like to also ask why did you not use onclick ? and wrap it around as a form?

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.