Prabu R
Prabu R

Reputation: 65

How to store the value of a text box in a database?

What I want to achieve: In a HTML window I click a button, then a popup window opens containing a text box and a submit button. There I enter a text into the text box, and after I click the submit button the text should be stored using SQl in a database.

I have code (see below)to get a text box value, and call another script to store the value in a database.

My AJAX code

$(document).ready(function() {
$("#sub").click(function() {
    $.ajax({
        type: "POST",
        url: "jqueryphp.php",
        data: {
            val: $("#val").val()
        },
        success: function(result) {
            $("div").html(result);
        }
    });
});
});​

HTML form code

<input type="text" name="val[text]" id="val"/><br>
<input type="button" name="sub"  value="submit" id="sub"/>

How can I put these pieces together?

Upvotes: 0

Views: 2556

Answers (1)

Beryllium
Beryllium

Reputation: 12998

You can use a HTML form like this:

<html>

<head>
  <script type="text/javascript"
    src="http://code.jquery.com/jquery-1.10.2.js"> </script>
  <script type="text/javascript"
    src="addEntryFormAjax.js"> </script>
</head>

<body>
  <form id="form">
    <input type="text" id="blogText" name="blogText" size="40" />
    <input type="submit" id="submit" value="submit"/>
  </form>

  <div id="result">
    None
  </div>
</body>

The HTML form uses JavaScript to attach a submit handler (addEntryFormAjax.js):

$(document).ready(function() {
    $("#form").submit(function() {
      doAjax();

      // Prevent normal form submit
      return false;
    });
});

function doAjax() {
    $("#result").html("<span>Calling ...</span>");

    $.ajax({
        type: "POST",

        url: "addEntryAjaxPdo.php",

        dataType: "html",

        data: {
          blogText: $("#blogText").val()
        },

        success: function(result) {
          $("#result").html(result);
        }
    });
}

If the submit button is pressed, the submit handler uses an AJAX call to the PHP script addEntryAjaxPdo.php which inserts data into the database:

<div>

<?php

// Sleep 3s, simulate a long running request
sleep(3);

$host = "localhost";
$db = "sandbox";
$user = "dev";
$pass = "dev";

$conn = new PDO("mysql:host=$host;dbname=$db", $user, $pass);

$stmt =
  $conn->prepare(
    "insert into blog (blogText, blogTimestamp) values (:blogText, now())");
$stmt->bindParam(':blogText', $_REQUEST['blogText']);
$stmt->execute();

$sql = "select last_insert_id()";
$query = $conn->query($sql);
$row = $query->fetch(PDO::FETCH_ASSOC);
echo "Inserted <em>" . $_REQUEST['blogText'] . "</em> into blog, id is " 
  . $row['last_insert_id()'];

?>

</div>

The state/result of the AJAX call is shown in the HTML page in the div element.

Upvotes: 1

Related Questions