0

I want to update a DB field. I can achieve it through the below code yet this requires the page to be refreshed and I am unable to display a message about the action outcome.

I tried using some JQ scripts without success (its so cryptic to me, however, it is on my learning plan just not there yet).

Would you please help me achieve this using ajax / jquery?

index.php

include ("functions.php");

if (isset($_GET['user_id'])) {
    $user_id = $_GET['user_id'];
    update_time($user_id);
}    

?>
<html>
    <head>
        <title>Update Time</title>
    </head>
    <body>
        <div id="msg"></div>
        <a id="update_link" href="index.php?user_id=user_id">Update Time</a>
    </body>
</html>

functions.php

<?php 
    function user_exist(){
        //run an SQL query to check if the user exist
        if (exist)
            return true;
        else
            return false;
    }

    function update_time($user_id){
        if(user_exist())
            //display a message in #msg that the time was updated
            //update the database
        else
            //display a message in #msg that the user does not exist
    }

?>

Script

$("a#update_link").click( function() {

    $.post( $(this).attr("href"),
            function(data) {
              if (data == "Time Updated") {
                  window.location = "index.php";
              }
              $("div#msg").html(data);
            });

    $(this).click( function() {
       return false;    
    });

});
NEWWPDEV
  • 15
  • 4

2 Answers2

0

In order to prevent the page from reloading, you can either change the href attribute to something like:

<a id="update_link" href="#" data-link="index.php?user_id=user_id">Update Time</a>

and update your JavaScript post URL:

$.post( $(this).data("link"),

or, alternatively, stop the default event in your click function like this:

$("a#update_link").click( function(event) { 
  event.preventDefault();
Cody Brumfield
  • 487
  • 4
  • 10
0

HTML (index.php)

In order to use jQuery, you have to first include the script file in your code.

<html>
    <head>
        <title>Update Time</title>
        <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
        <script src="function.js"></script>
    </head>
    <body>
        <div id="msg"></div>
        <a id="update_link" href="index.php?user_id=user_id">Update Time</a>
    </body>
</html>

JS (function.js)

Next, you want to attach a 'click' event handler to your #update_link element. When you attach an event handler to your link, you want to prevent it from doing its default behavior of redirecting to another page by using e.preventDefault().

// shorter syntax for document.ready
$(function () {
    // attach a click event handler
    $('#update_link').click(function(e) {
        // prevent the click from redirecting
        e.preventDefault();
        // make an AJAX request
        $.post($(this).attr('href'), function (res) { 
            // handle the response (*) by storing the message into the DIV#message
            $('#msg').html(res);
        });
    });
});

PHP

Now, you are making an AJAX request to the same URL (index.php). It's usually better have a separate script to handle AJAX request -- but we'll work with your current setup. This means your page needs to be able to handle two different kinds of requests: those that are AJAX requests and those that aren't.

When it's an AJAX request, we only want to output a HTML message. When it is not, we want to output the HTML page.

(index.php)

So, first let's modify your page again.

<?php
include 'functions.php';

// check if the request was made via AJAX
if (is_ajax() && isset($_GET['user_id'])) {
    // update and print (not return) a message
    update_time($_GET['user_id']);
    // stop the script from outputting the rest
    exit;
}
?>

(functions.php)

Next, let's create a new function (that we just used above) for convenience to detect whether we are receiving an AJAX request.

function is_ajax() {
    return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';
}

Lastly, ensure that you print (or echo) your message. That will be the AJAX response (*) that will be sent back to your JavaScript.

function update_time($user_id){
    if (user_exist()) {
        //update the database
        //print a message that the time was updated
    } else {
        //print a message that the user does not exist
    }
}
Community
  • 1
  • 1
Mikey
  • 6,728
  • 4
  • 22
  • 45