Welcome to collectivesolver - Programming & Software Q&A. A website you can trust. All programs tested and works. Contact: aviboots(AT)netvision.net.il
Hostgator 1 Penny

BlueHost Web Hosting

Ecommerce Software - Best Ecommerce Platform Made for You - Free Trial

Ecommerce Software - Best Ecommerce Platform Made for You - Free Trial

getflywheel wordpress hosting


Distribute your Resume to 500+ Job Boards & Recruiters


7,765 questions

10,845 answers

573 users

How to use ajax to update MySQL and web page without refresh with PHP, jQuery and JavaScript

1 Answer

0 votes
<!-- index.php -->

<form id="form-create-topic" method="post" onsubmit="return doCreateTopicAjax();">

   <input id="input-new-topic" type="text" name="new-topic" />
   <input type="submit" id="create" value="Create" />

</form>
// create-topic.js

function doCreateTopicAjax()
{
    if (document.getElementById('input-new-topic').value == "")
    {
        return false;
    }

    data = "new-topic=" + document.getElementById("input-new-topic").value;

    $.ajax({
        url : "create-topic.php",
        type: "POST",
        contentType: 'application/x-www-form-urlencoded',
        data : encodeURI(data),
        success: function(data, status, xhr)
        {
            document.getElementById("menu-id").innerHTML = 
                         document.getElementById("menu-id").innerHTML + 
                         document.getElementById("input-new-topic").value;
        },
        error: function (jqXHR, status, err)
        {
            alert('there was an error ' + err + ' with status ' + status);
        }
    });
}
// create-topic.php

if (isset($_POST['new-topic']) && !empty($_POST['new-topic']))
{  
    try 
    {
         $inserted = $con->prepare("INSERT INTO topics(topic, IP, add_date)
                VALUES(:topic, :ip, NOW())");

          $inserted->execute(array(
                    "topic" => $_POST['new-topic'],
                    "ip" => $_SERVER['REMOTE_ADDR']
                ));
    }
    catch (PDOException $e) 
    {
            die($e->getMessage());
    }
}

 




answered Jul 14, 2015 by avibootz
edited Jul 14, 2015 by avibootz
...