Daññ Daññ - 4 months ago 7
Ajax Question

Send variable From PHP to AJAX

I have a php page called posts.php, this page just

select all
from a database table named
posts
and display them. Down the page I have a textarea named
post
. When I press the submit button the AJAX script will send the text from textarea to a page called
insert.php
. This
insert.php
gets the submited text and insert it into
posts
table. How can I do this and how can I upload the
posts.php
when I have inserted a post into
posts
table.

Example:
User 123 writes a message in the textarea. He presses submit button. AJAX sends the post to
insert.php
.
Insert.php
inserts the post into
posts
tabel.
Posts.php
shows the message.

Answer

You can do it very easily! Here's a very simple example.

func.js

$(document).on("click", ".submitBtn", function() {
    var textareaVal = $(".textarea").val();
    $.ajax({
        type: "POST",
        url: "insert.php",
        dataType: "text",
        data: { postVar: textareaVal },
        success: function(data) {
            $(".resultDiv").load("posts.php");
        }
    });
});

insert.php

// You have to pay attention to AJAX can only invite your file!
if (!empty($_SERVER["HTTP_X_REQUESTED_WITH"]) && strtolower($_SERVER["HTTP_X_REQUESTED_WITH"]) == "xmlhttprequest") {
    if (isset($_POST["postVar"])) {
        $var = sanitize($_POST["postVar"]); // You need sanitize the data!
        // Insert into your table...
    }
}

In your posts.php, SELECT datas from your table, but only select the data, without „HTML container”! Your JS file load this datas on your resultDiv box.