Schedule A Consultation

    Fields marked * are mandatory

      CA INQUIRY

      Asynchronous Comments with PHP, jQuery, and JSON

      This entry was posted on Thursday December 3, 2020

      Right now, going to take a gander at how we make a straightforward however powerful methods for catching and showing guest remarks utilizing a mix of jQuery, PHP and JSON. In the open gathering that is the blogosphere, the capacity to catch and show guest remarks on your websites can offer you moment input and thoughts from the individuals that issue most – those that read your blog.

       

      Outline

      We’ve a few errands that should be cultivated so as to finish this model; when the page on which the remarks are shown is at first stacked, we have to show the entirety of the current remarks. Moreover, when another remark is made, we’ll have to show this on the page after the current remarks, just as sending the new remark to the server for capacity with the current remarks.

       

      Tools Required

      We’ll be utilizing jQuery (variant 1.3.1), clearly, on the grounds that it rocks, and we’ll be utilizing JSON on the grounds that it’s a light-weight and productive arrangement for shipping information across systems. We’ll additionally be utilizing somewhat straightforward PHP to cooperate with a MySQL database. You’ll have to approach an establishment of MySQL server and ought to set up another database considered remarks that contains a table, likewise called remarks, which has a name section and a remark segment.

       

      Let Start – The Stored Comments

      How about we make a beginning by making the PHP document that peruses the remarks from the database and returns them to the page; along these lines, when we come to code the page, the information will as of now be accessible for us to utilize. In another record in your content manager include the accompanying code:

      <?php

        //db connection detils

        $host = “localhost”;

        $user = “root”;

        $password = “cilected”;

        $database = “comments”;

        //make connection

        $server = mysql_connect($host, $user, $password);

        $connection = mysql_select_db($database, $server);

        //query the database

        $query = mysql_query(“SELECT * FROM comments”);

          //loop through and return results

        for ($x = 0, $numrows = mysql_num_rows($query); $x < $numrows; $x++) {

          $row = mysql_fetch_assoc($query);

          $comments[$x] = array(“name” => $row[“name”], “comment” => $row[“comment”]);      

        }

        //echo JSON to page

        $response = $_GET[“jsoncallback”] . “(” . json_encode($comments) . “)”;

        echo $response;  

      ?>

      Save this  comments.php. We should quickly stroll through what we do with this code. We store the entrance qualifications for our server in the initial four factors and following this, we associate with the database. We at that point inquiry the database and select the entirety of the information from it.

       

      For Loop

      In the following area of code we utilize a for circle to push through each line of information. On every emphasis of the circle we add another thing to a cluster ($comments). The exhibit is a multidimensional partner cluster and every thing will have two sub things which are given the keys name and remark, coordinating the segments in our table. The estimation of every thing will be the information from each individual field in the present line.

      JSON Encode

      At long last we package up the finished JSON object in a GET ask for and afterward utilize the local PHP json_encode capacity to change over our cluster into an appropriately arranged JSON object. We’ll be utilizing a JSONP callback in the JavaScript, which is the reason we have to utilize a get reaction and furthermore why we wrap the JSON encoded exhibit in sections. To explain the structure of the information that we’re returning, in the event that we were working it out physically we would accomplish something like this:

      ([

        {name:”a name”, comment:”a comment”},

        {name:”a name”, comment:”a comment”},

        { etc }

      ])

       

      This comprises of a straightforward exhibit, where every thing in the cluster is an article. These internal items each have two properties – creator and remark, where the estimations of these properties are the information extricated from the content document. Settling the internal articles in a cluster makes it incredibly simple for us process the information with jQuery.

      Displaying the Stored Comments

      Since we have an item to work with, we can make the HTML page that will show the comments. In another document in your word processor include the accompanying increase:

      <!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01//EN” “http://www.w3.org/TR/html4/strict.dtd“>

      <html>

        <head>

          <link rel=”stylesheet” href=”comments.css”>

          <meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″>

          <title>Asynchronous Comments</title>

        </head>

        <body>

          <div id=”content”>

            <h2>Some Content</h2>

            <p>Lorem ipsum dolor…</p>

          </div>

          <div id=”comments”>

            <h2>Reader Comments</h2>

          </div>

          <div id=”leaveComment”>

            <h2>Leave a Comment</h2>

            <div class=”row”><label>Your Name:</label><input type=”text”></div>

            <div class=”row”><label>Comment:</label><textarea cols=”10″ rows=”5″></textarea></div>

            <button id=”add”>Add</button>

          </div>

          <script src=”jquery-1.3.1.min.js”></script>

        </body>

      </html>

       

      Save this record as comments.html. The vast majority of the increase is unimportant and is utilized to give the model some substance. On the page we have some spurious substance, a compartment which the current remarks can be rendered into and some fundamental structure components used to leave another remark. In the leader of the page we connect to a template and toward the finish of the body we connect to the jQuery library.

      CSS

      The template utilized right now trivial and is utilized basically to introduce the model flawlessly. It comprises of the accompanying CSS:

       

      body { font-family:verdana; font-size:11px; color:#ffffff; }

      #content {

        width:400px; height:195px; border:3px solid #000000; margin:0 auto 10px;

        font-size:13px; background-color:#575454;

      }

      #content p { padding:0 10px; }

      #comments {

        width:400px; border:3px solid #000000; margin:0 auto 10px;

        padding-top:5px; background-color:#575454;

      }

      .comment {

        background-color:#d4d7d6; border:1px solid #000000;

        padding:5px 0 5px 5px; color:#000000;

      }

      #leaveComment {

        width:400px; border:3px solid #000000; margin:0 auto;

        overflow:hidden; position:relative; background-color:#575454;

      }

      h2 { text-align:center; margin:5px 0 10px; }

      .row { padding-left:5px; margin-bottom:5px; clear:both; overflow:hidden; }

      .row label {

        width:100px; text-align:right; margin-right:5px; display:block;

        float:left; font-weight:bold; padding-top:5px;

      }

      .row input, .row textarea, .row div {

        width:280px; display:block; float:left;

      }

      #add {

        position:absolute; bottom:5px; left:60px; font-weight:bold;

        font-size:10px;

      }

      Save this as comments.css in a similar registry as the HTML page. I won’t spread precisely what this code does as it’s really minor and is utilized only for show purposes. It should make the page be shown as follows:

      Javascript

      Presently we can include the JavaScript that will demand the JSON object from the server, process it and show the remarks. Legitimately after the connection to jQuery include the accompanying content square:

       

      <script>

        $(function() {

          //retrieve comments to display on page

          $.getJSON(“comments.php?jsoncallback=?”, function(data) {

            //loop through all items in the JSON array

            for (var x = 0; x < data.length; x++) {

              //create a container for each comment

              var div = $(“<div>”).addClass(“row”).appendTo(“#comments”);

              //add author name and comment to container              

              $(“<label>”).text(data[x].name).appendTo(div);           

              $(“<div>”).addClass(“comment”).text(data[x].comment).appendTo(div);

            }

          });         

        });           

      </script>

       

      Again this code is genuinely trifling; when the page has stacked, we utilize the getJSON technique to demand the JSON object from the PHP record, determining the way to the document as the main contention. We include the JSONP callback – ?jsoncallback=? – as far as possible of the URL and afterward indicate a mysterious callback work as the subsequent contention, which will be executed if and when the solicitation returns effectively.

      Inside our callback we have a basic for circle which is utilized to circle through every thing in the JSON cluster. For every thing we make a holder div which is given a class of line and is then added to the principle remarks compartment div. 

      We at that point indicate a mark and set the content of the name to the estimation of the name property of the article in the present cluster thing. After the name has been annexed to the present holder div, we make another div which is utilized to hold the estimation of the remark property. The remark is then attached to the present holder div. 

      Presently when we run the page, we should find that the remarks from the database are shown inside the predetermined holder div

       

      Adding New Comments Asynchronously

      For the last piece of this instructional exercise we can perceive that it is so natural to consequently embed another remark after the current remarks, while simultaneously sending the new remark to the server to be added to the database with the goal that it tends to be shown naturally when the page is next stacked. Include the accompanying new code legitimately after the getJSON technique:

      //add click handler for button

      $(“#add”).click(function() {

        //define ajax config object

        var ajaxOpts = {

          type: “post”,

          url: “addComment.php”,

          data: “&author=” + $(“#leaveComment”).find(“input”).val() + “&comment=” + $(“#leaveComment”).find(“textarea”).val(),

          success: function(data) {      

            //create a container for the new comment

            var div = $(“<div>”).addClass(“row”).appendTo(“#comments”);        

            //add author name and comment to container

            $(“<label>”).text($(“#leaveComment”).find(“input”).val()).appendTo(div);

            $(“<div>”).addClass(“comment”).text($(“#leaveComment”).find(“textarea”).val()).appendTo(div);

          }

        };

        $.ajax(ajaxOpts);

      });

      Once more, this is straight-forward code – what we’re doing is very unpredictable, however jQuery abstracts away all the trouble and cross-program dubiousness, leaving us to compose only a couple of lines of code. We previously set a tick handler for the include remark button. This will execute the unknown capacity indicated as a contention to the snap technique at whatever point the catch is clicked. 

      Inside this capacity we initially make another exacting item which is utilized to design the new AJAX demand. We determine the kind of solicitation, the URL of the asset we’re mentioning, a few information and a triumph callback work. Inside our prosperity work everything we do is get the substance of the information and textarea and add them to the remarks div similarly that we did with the first remark information got when the page loads.

      Database Connection

      We’ll require one more PHP file so as to compose the new comment to the database:

      <?php

        //db connection detils

        $host = “localhost”;

        $user = “root”;

        $password = “your_password_here”;

        $database = “comments”;

        //make connection

        $server = mysql_connect($host, $user, $password);

        $connection = mysql_select_db($database, $server);

        //get POST data

        $name = mysql_real_escape_string($_POST[“author”]);

        $comment = mysql_real_escape_string($_POST[“comment”]);

        //add new comment to database

        mysql_query(“INSERT INTO comments VALUES(‘ $name ‘,’ $comment ‘)”);

      ?>

      Save this file as addComment.php. We indicate our association data again and interface with the database. We at that point get the information sent by our JavaScript from the $_POST superglobal factors and afterward utilize the mysql_query capacity to embed the new information into the table. Notice that we utilize the mysql_real_escape_string capacity to forestall any abuse of our database; in spite of the fact that it’s impossible that any damage could emerge out of an assailant accessing this specific database, it’s constantly astute to clean any information before it is included.