Skip to content Skip to sidebar Skip to footer

Retrieving Data From Database And Displaying It By Using Ajax

Okay people, what I am trying actually trying to achieve is, to create a chat box something similar to fb without refreshing the page. I have two tables in my database(phpmyadmin)

Solution 1:

Working with ajax, at the beginning, can be very frustrating. You should start with more simple task, simply to understand what you're working with. Start with something like this, a simple request that send two numbers to the server and then alert the sum

ajax_request.php

<?php$num1 = isset( $_GET[ "num1" ] ) ? $_GET[ "num1" ]: 0;
$num2 = isset( $_GET[ "num2" ] ) ? $_GET[ "num2" ]: 0;
echo$num1 + $num2;

index.html

<html><head><scriptsrc="jquery-1.11.3.min.js"></script><script>
        $(document).ready(function () {
            $( "#calculate" ).click(function(e) {
                e.preventDefault();
                $.ajax({
                    url: 'ajax_request.php',
                    data: $( "#form" ).serialize(),
                    success: function( data ) {
                        alert( data );
                    },
                    error: function() {
                        alert( "Something went wrong" );
                    }
                });
            });
        });
        </script></head><body><formid="form">
            Num1: <inputtype="text"name="num1" /><br />
            Num2: <inputtype="text"name="num2" /><br /><inputtype="submit"id="calculate" /></form></body></html>

Open index.html (download the jQuery library), fill the two numbers and click the button. You can test the "Something went wrong", simply put a wrong url (ajax_requestx.php instead of ajax_request.php). From here, you can study "ajax" and "jQuery" to understand better how this work.

The concept is this: you stop the form to be sent (e.preventDefault()) and instead send the form in "asyncronous" way, making javascript send the request to the server without changing the page; in the "success" function you can analyze the string sent back from the server and do something with it. All done by javascript

Post a Comment for "Retrieving Data From Database And Displaying It By Using Ajax"