AJAX with PHP


Loading ....
 

In fairness there’s a lot of different AJAX methods that do pretty much the same thing.  $.load(), $.get(), $.ajax(), getJSON() – the list goes on.

Generally the code-style you use dictates which AJAX method you choose.  At bare-bones level javaScript limits you to $.ajax() or $.xmlHttpRequest(), and the structure of these commands together with the way you’re forced to write your calls can be daunting

However, bolting jQuery into your scripts opens up a whole new range of AJAX methods.

I’ll use a couple of these methods in the following example where I’m using AJAX to send some data to a php script, and have that script update a database with the information I supply from a front-end.  Very simple information in this case – just a users first and last name.

First let’s deal with the PHP ready for the AJAX call.  A typical PHP setup would have a database connector which is added as an ‘include’ to a PHP script.  That’ll look something like this:

connect.php
<?php
echo "OK" ;
try {
   $db = new PDO( 'mysql:host=localhost;dbname=yourDatabaseName;charset=utf8', 'yourAdminLogin', 'yourAdminPassword' );
}

catch(Exception $e) {
   echo $e->getMessage();
   echo "An error has occurred";
}

OK, now to use that we’ll simply insert an include line at the top of our ‘runtime’ script.  This is the script that AJAX will call, and which puts our data into the database.  I’m using a PDO method on my database/scripts to maintain a secure transaction.  If you’re unfamiliar with OOP (Object Orientated Programminh) then I’d strongly recommend you indulge in a tutorial or two!  Basically my bindValue statements are tying the input we receive at $_POST[‘request’] to ‘placeholders’ defined in the parameters.  OK, I’m doing a couple of things to that data before we use it – I’m splitting a 2 value array into it’s separate components.  That will actually be someones firstname and lastname …

putUserInfo.php
<?php error_reporting(E_ALL) ; 
include 'connect.php'; 
$packet = explode(",", str_replace("!" , " " , $_POST['request'])) ; 
$firstName = $packet[0] ; 
$lastName = array_pop($packet) ; 
$stmt = $db->prepare("INSERT INTO userinfo (firstname,lastname) VALUES (:firstName, :lastName)") ; 
$stmt->bindValue(':firstName', $firstName) ; 
$stmt->bindValue(':lastName', $lastName) ; 
$stmt->execute(); ?>

And finally we can write our HTML, jQuery and AJAX which starts the whole thing going.  The HTML is a simple set of input types, buttons and divs where I can put my output.  When a user types his firstname and lastname into the relevant boxes, clicking the ‘send’ button will fire the eventlistener on that ID.

The firstname and lastname variables are pushed into an array outside of the function.  Now strictly speaking that’s really not necessary here, but I’m doing it anyway as I intend to build on this script and make that array available to other functions.

Once the array is formed, the $.post() mechanism calls a script in its first parameter, and in the second it assigns a handle to carry the data.  In the putUserInfo.php script we’re collecting $_POST[‘request’], so we’ll use that in this parameter.  Note the ‘=’ sign following that; this assigns the value in ‘sendArray’ to the call.  So basically the users firstname, a ‘!’ character, and the lastname are send as an array inside this call.

Because this is a database update we don’t really need PHP to tell us anything, other than the fact it worked.  As I can see it works from my console, I can simply add a response function to console log that.  I could do something far more ornate, but that’s not the object of this exercise!

userinfo.html
<div id="container">
<input type="text" id="firstName" name="firstName">First name
<input type="text" id="lastName" name="lastName">Last name
<div id="wholeName"></div>
<button id="btn1">send</button> 

<div id="outputFrame"></div>
</div>

<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> 
<script>

$(function() {

   var sendArray = [] ;

   btn1.addEventListener("click", function() {
      var firstName = $('#firstName').val() ;
      var lastName = $('#lastName').val() ;
      $('#wholeName').html("Your name is " + firstName + " " + lastName) ;
      sendArray.push(firstName, "!" , lastName) ;
      $.post('http://jsonajax/AJAX & PHP/SIMPLE_DATABASE_WORK/putUserInfo.php', 'request=' + sendArray , function(response) {
      console.log("PHP call OK") ;
   }) ;
}) ;

And that’s where the fat lady sings, offers us a cigar and rides off into the sunset with a working database insert function with AJAX!

 


RELATED PRODUCTS
  • For CB Vendors Protect Thank You Pages Downloads
  • Clickbank Ads
     
    Share

    You may also like...

    Leave a Reply

    Your email address will not be published. Required fields are marked *