-2

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.

u_mulder
  • 54,101
  • 5
  • 48
  • 64
Daññ
  • 5
  • 2
  • What I understand from your question is that you've a page with text input field and submit button and you need when user write down some value in the input field and press submit, the value should be placed in your posts table and also appear below your form. Am I right ? – Mou Aug 10 '16 at 19:33
  • You need to implement two ajax requests: one for inserting data (insert.php) and second for polling. More information on polling is [here](http://stackoverflow.com/questions/6835835/jquery-simple-pollingexample) – Ivnhal Aug 10 '16 at 20:05
  • There are 2 ways to achieve this. a) Create an AJAX call which can reload the posts on the page. After AJAX call for insert, call the post refresh AJAX call. b) Refresh the page when you call insert.php – Yash Dayal Aug 10 '16 at 20:13
  • Welcome to Stack Overflow. Please read the following article on how to ask a question on this site: http://stackoverflow.com/help/how-to-ask – Robert Columbia Aug 10 '16 at 20:28

2 Answers2

0

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.

0

I'm not certain why you would need to do this via ajax, but:

$( "#myForm" ).submit(function( event ) {
 $.ajax({
         type: 'post',
         url: '../insert.php' ,
         data: { value1: document.getElementById('textarea').value },
         success: function () {
           alert("yay!");
         }
 });
});
Bobert123
  • 103
  • 8