samedi 25 avril 2015

How to respond correctly to an AJAX call in PHP?


I am trying to update form fields using ajax and php.

My AJax call is like this :

var productId = 'productId=' + id;

$.ajax({
  url: './includes/process_edit_products.php',
  method: 'post',
  data: productId
}).success(function(response) {
  // Populate the form fields with the data returned from server
  $('#userForm')
    .find('[name="product_id"]').val(response.product_id).end()
    .find('[name="product_name"]').val(response.product_name).end()
    .find('[name="product_price"]').val(response.product_price).end()
    .find('[name="product_des"]').val(response.product_des).end();

  // Show the dialog
  bootbox
    .dialog({
      title: 'Edit Products',
      message: $('#userForm'),
      show: false // We will show it manually later
    })
    .on('shown.bs.modal', function() {
      $('#userForm')
        .show() // Show the login form
        .formValidation('resetForm'); // Reset form
    })
    .on('hide.bs.modal', function(e) {
      $('#userForm').hide().appendTo('body');
    })
    .modal('show');
});

PHP processing script is like this:

if ((isset($_POST['productId'])) && (is_numeric($_POST['productId'])) ) { // Form submission.
    $productId = (int)$_POST['productId'];
    //echo $productId;

        // fetch the selected product to edit
    $query = " SELECT product_id, product_name, price, product_des
                         FROM  product
                         WHERE product_id = ? LIMIT 1";

    $stmt = $mysqli->prepare($query);

    if ($stmt) {
        // Bind "$imageId" to parameter.
        $stmt->bind_param('i', $productId);  
        // Execute the prepared query.
        $stmt->execute();    
        $stmt->store_result();
        // count rows
        $numrows = $stmt->num_rows;

        if ($numrows == 1) {
            // get variables from result.
            $stmt->bind_result($product_id, $product_name, $price, $product_des);   
            // Fetch all the records:
            $stmt->fetch();     

            echo $product_id;
            echo $product_name;
            echo $price;
            echo $product_des;

            // Close the statement:
            $stmt->close();
            unset($stmt);
        }
    }
}

My problem is I am not sure how to get php processing data back and populate the form fields with existing data.

Can anybody tell what do I need to do in my php.


Aucun commentaire:

Enregistrer un commentaire