0

I am really in doubt how to get started on this code. In my DIV tag "talraekke" I want to receive the last 10 records from my database. That means everytime I put in a number in my form field, the div tag should be updated with the latest number, without I have to update the page. Could anybody help me on the way?

Best Regards Julie

PS: Please look away from the outdated php/sql statements :-) This is just a test session for me.

HTML

    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
        <script src="js/my_script.js" type="text/javascript"></script>
        <link rel="stylesheet" type="text/css" href="css\placing.css">
        <title>Numbers</title>
    </head>

    <body>
        <div class="topbar">
            <p>Topbar</p>
        </div>


        <div class="talraekke">
            ****Recieve from DB******
        </div>

        <div class="content">
            <p>Enter The Number</p>
            <form id="myForm" action="userInfo.php" method="post">
                <input type="value" name="numbervalue">
                <button id="sub">Save</button>
            </form>
            <span id="result"></span>
        </div>  
    </body>
    </html>

JS:

// Insert function for number
function clearInput() {
    $("#myForm :input").each( function() {
         $(this).val('');
    });
}

    $(document).ready(function(){
         $("#sub").click( function(e) { // note the 'e'
       e.preventDefault(); // remove default action(submitting the form)
       $.post( $("#myForm").attr("action"), 
         $("#myForm :input").serializeArray(), 
         function(info){ $("#result").html(info); 
       });
       clearInput();
    });
    })

// Receive data from database

PHP:

<?php

include('connection.php');


// Insert To Database
$strSQL = "INSERT INTO numbertable(numbers) VALUES('" . $_POST["numbervalue"] . "')";


        if(mysql_query("INSERT INTO numbertable VALUES('numbers')"))
            echo "Insert Succesfull";
        else
            echo "Failed";


// The SQL statement is executed 
    mysql_query($strSQL) or die (mysql_error());

// Close the database connection
    mysql_close();

?>
4
  • To state the obvious, you are just inserting values in the Datbase in PHP and not returning any response content to the POST request. Also your database structure is unclear. Are your numbers at least inserted into the database as expected so far? Commented Dec 8, 2015 at 19:16
  • Thanks a lot for your answer. In my database I only have 1 column which is named numbers. When I save my number it is saved fine in the database, but it is the returning of the I really dont know how to do. Hope it is a bit more clear now? Best Regards Commented Dec 8, 2015 at 19:20
  • Can you post here the returned response from your query please Commented Dec 8, 2015 at 19:21
  • Im sorry, but I am not quite sure what you mean? :-/ Commented Dec 8, 2015 at 19:31

2 Answers 2

2

Honestly, you may want to look into a framework like Backbone.js which could make this a lot easier. First off, you should remove the SQL injection vulnerability by either escaping the form input or wrapping it in a function to return the numerical value. Also, I don't think an input type of "value" is valid; you can use "text" or "number" but keep in mind the later will not prevent the security hole since client-side input can not be trusted.

If you want to do this by hand, simply return the data from your controller in something like a JSON object which you could then use on the client-side. You shouldn't need to prevent a form submission if there isn't any submit button (and you aren't calling the submit method). If you would like an example using jQuery to populate a DIV with the results of a jQuery post() there is an example of it right here:

http://api.jquery.com/jquery.post/

CTRL+F: Post a form using Ajax and put results in a div

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

Comments

0

What you are looking for is

$res = mysql_query( 'SELECT * FROM numbertable' );
$values = mysql_fetch_array( $res );
echo json_encode( $values );

just before the //close the database connection part of your php. And adding die(); just before the ?> probably can't hurt to ensure there is no further output.

Some changes in your javascript to get you started:

$("#sub").click( function(e) { 
    e.preventDefault(); // remove default action(submitting the form)
    $.post( $("#myForm").attr("action"), 
        $("#myForm :input").serializeArray(), 
        function(info){ 
            info = JSON.parse(info);
            $("#result").html(info);
            console.log(info);
        }) // end of the POST request success hander
   ); // end of the $.post function call
}); // end of the .click function call

You now have a Javascript Object of the returned values. You can see it in the Developer console. Go from there.

But please note that the mysql extension for php is deprecated. Better use mysqli or pdo_mysql. Also please take note of the answer by Eric Wilk. Security is a serious issue and frameworks can make your life a lot easier in that and other regards.

Another tip for development: In most browsers developer tools you have a network tab where you can inspect the header and response information of all the HTTP requests that are going on. It can be immensely helpful to figure out what is going on.

Oh and one more thing I forgot...

The echos informing about the success or failure of the database insert will likely make the response of your php invalid json. You can remove them for now, or better, start constructing a response object and make no other outputs throughout the script. Think something like this:

$response = array();
/* ...some code in between... */
    $response["insert"] => array("success" => true, "msg" => "Insert Succesfull");
else
    $response["insert"] => array("success" => false, "msg" => "Failed");
/* ... */
$values = mysql_fetch_array( $res );
$response["values"] => $values;
echo json_encode( $response );

1 Comment

Thanks a lot for all your answer. I will spend my night looking at it. I really apriciate it. Best Regards Julie

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.