jQuery Ajax

Not sure how to use jQuery and Ajax but I'm thinking something like this:

    $.ajax({
    	url: "getCustomerData.php?c=customerID", 
    	dataType: 'json',
    	success: function(result){
		$("#customerName").val(The customer name returned by Ajax);
		$("#customerAddress").val(The customer address returned by Ajax);
		$("#customerCity").val(The customer city returned by Ajax);
                etc;
                etc;
    	}
    });

Open in new window


I'm hoping, at the end of the day, that I can send the customerID on listbox changes.  So, when the user selects a customer from the listbox various fields will reflect the proper info.

Thoughts?
Sheldon LivingstonConsultantAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Brian TaoSenior Business Solutions ConsultantCommented:
Yes, you're thinking in the right direction.
On your html/javascript page, put the $.ajax() call inside a $("#your_select_element_id").change() declaration, so that it is triggered on listbox changes.
(for detail on how to use jquery ajax, please visit https://api.jquery.com/jQuery.ajax/)
In your PHP script, use json_encode() function to send the response.
(link is here - http://php.net/manual/en/function.json-encode.php)
Prakash SamariyaIT ProfessionalCommented:
You need to change below line to take the value of customerID
      url: "getCustomerData.php?c="+$("#customerID"),

You can return value in JSON object, so in ajax success event function you can simply use that one like
      success: function(result){
               $("#customerName").val(result.data.Name); //and so on for rest of the property/members
               //result.data.Name can used like result.Name based on how you return JSON object to it.
Julian HansenCommented:
You also should use a POST with AJAX so you need to add the property

type: "POST"

Open in new window


Try this test code to see how to get it working
HTML
    <form action="getCustomerData.php" method="post" class="form">
      <div class="form-group">
        <label for="customerID">Customer ID :</label><input type="text" id="customerID" name="customerID" class="form-control"/>
      </div>
      <div class="details" style="display: none">
        <div class="form-group">
          <label for="customerName">Customer Name :</label><input type="text" id="customerName" name="customerName" class="form-control"/>
        </div>
        <div class="form-group">
          <label for="customerAddress">Customer Address :</label><input type="text" id="customerAddress" name="customerAddress" class="form-control"/>
        </div>
        <div class="form-group">
          <label for="customerCity">Customer City :</label><input type="text" id="customerCity" name="customerCity" class="form-control"/>
        </div>
      </div>
      <button class="btn btn-default">Load Customer</button>
    </form>
<script src="http://code.jquery.com/jquery.js"></script>
<script src="js/bootstrap.js"></script>
<script>
$(function() {
  // BIND TO THE FORM SUBMIT
  $('form').submit(function() {
  
    // CREATE THE AJAX CALL
    $.ajax({
    // POST URL: NOT NECESSARY TO INCLUDE URL PARAMETERS
      url: "getCustomerData.php", 
    
    // USE jQuery .serialize() TO GET POST DATA
      data: $(this).serialize(),
    
    // TELL AJAX WE ARE EXPECTING JSON RETURN
      dataType: 'json',
    
    // POST THE DATA
      type: "POST"  
    })
  // NOTHING WRONG WITH success: STANDARD IS TENDING
  // TOWARD USING DEFERRED OPERATIONS
  // res PARAMETER IS DECODED JSON RETURN
  .done(function(res) {
  
      // CHECK IF REQUEST WAS SUCCESSFUL
      if (res.status == 'Ok') {
        // POPULATE THE RESULT FIELDS FROM THE res STRUCTURE
        $("#customerName").val(res.customerName);
        $("#customerAddress").val(res.customerAddress);
        $("#customerCity").val(res.customerCity);
    
        // SHOW THE POPULATED FIELDS
        $('.details').show('slow');
      }
      else {
        // OTHERWISE SHOW ERROR
        alert(res.error);
      }
    });
    
    // PREVENT DEFAULT SUBMIT BEHAVIOUR
    return false;
  });
});
</script>

Open in new window

PHP
<?php
// RETRIEVE AND SANITIZE THE CUSTOMERID
$customerid = isset($_POST['customerID']) ? (int)$_POST['customerID'] : '';

// CREATE A RESULT STRUCTRE
$result = new stdClass;

// CHECK CUSTOMER REQUEST IS VALID
if (!empty($customerid) && $customerid >= 1) {
  // SET THE STATUS AND CUSTOMER FIELDS
  $result->status = 'Ok';
  $result->customerName = 'Customer Name';
  $result->customerAddress = 'Address';
  $result->customerCity = 'City';
}
// CUSTOMER REQUEST INVALID
else {
  // SET ERROR STATUS AND FAIL MESSAGE
  $result->status = 'Fail';
  $result->error = 'Customer not found';
}

// RETURN JSON ENCODED RESULT
echo json_encode($result);

Open in new window


Working sample here

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Sheldon LivingstonConsultantAuthor Commented:
Thank you!  Exactly what I was looking for.
Julian HansenCommented:
You are welcome.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
AJAX

From novice to tech pro — start learning today.