Steve Price
Steve Price

Reputation: 600

Understanding AJAX and callbacks

I've searched around the internet, and SO and I haven't managed to find the answer to what I thought would be a simple question. I've only just started getting involved with AJAX and js, so please excuse me if it appears to be a really dumb question!

How do i return html, and a variable in the AJAX callback.

Say I want to execute a database query to update a sort order. I send the sort order from my form to update.php using AJAX. I then send some html back like

<div class="alert alert-info">
    <strong>Sort Order Updated</strong>
</div>

I display the success message in my div, and then I want to use something like

document.getElementById('sortOrderInput')['sortorder'].value = "returnedvariable";

to update the value in the form field. (NOTE: "returnedvariable" is only to illustrate where I want the value that was in $_POST['sortorder'] to go)

If I console.log(data) i currently see html content, and I can't for the life of me figure out how I should also return a variable. Do I do it as some form of array containing both data types and then reference it in

.done(function(data) {

For clarity, I'm adding my entire script here

$(document).ready(function() {
        var original_content = '';
        $('.sortOrder').submit(function(e){
            e.preventDefault();
            $.ajax({
                url: 'sort_order_update_ajax.php',
                type: 'POST',
                data: $(this).serialize(),
                dataType: 'html'
            })
           .done(function(data) {
               console.log(data);
               var elem = $('.sort-update');
               var original_content_qty = elem.html();
               elem.fadeOut('slow', function() {
                   elem.html(data).fadeIn('slow', function() {
                       elem.delay(1200).fadeOut('slow', function() {
                           elem.html(original_content_qty).fadeIn('slow');
                           //document.getElementById('sortOrderInput')['sortorder'].value = ?????;
                       });
                   });
               });
           })
           .fail(function(){
               alert('Ajax Submit Failed ...'); 
           });
       });
   });

sort_order_update_ajax.php file contains

<?php require('includes/application_top.php');

if( $_POST ){
    $sort_order = $_POST['sortorder'];

    $sort_order = (int)$sort_order;
    if (is_int($sort_order)) { 
        $sql = "UPDATE " . TABLE_PRODUCTS . " SET sort_order = '" . $sort_order . "' WHERE products_id ='" . $_POST['products_id']. "'";
        $db->Execute($sql);
    }
?>
<div class="alert alert-info">
    <strong>Sort Order Updated</strong>
</div>

<?php 
}
require(DIR_WS_INCLUDES . 'application_bottom.php'); 
?>

Upvotes: 1

Views: 119

Answers (3)

floverdevel
floverdevel

Reputation: 150

based on the information you given us, i would answer something like this :

serverside (assuming PHP)

<?PHP
$data = array(
    'sortOrder' => $_POST['sortorder'],
    'asHtml' => '<div class="alert alert-info"><strong>Sort Order Updated</strong></div>',
);
header('Content-Type: application/json');
echo json_encode($data);

client side (assuming javascript)

.done(function(data) {
  // show your confirmation div like before
  document.getElementById('confirmation').value = data.asHtml;
  document.getElementById('sortOrderInput')['sortorder'].value = data.sortOrder;
});

Upvotes: 2

Abhi
Abhi

Reputation: 1671

there are multiple ways to do this, but most easy and obvious in my opinion would be: From your service (server api) you can return an object like this:

{
  sortOrder: <sort order value>,
  message: "Sort Order Updated"
}

Then, you can use these variables as response.sortOrder and response.message.

Hope this helps! Please write in comments if you have questions, rather than down voting. :)

Upvotes: 1

Joshua Miles
Joshua Miles

Reputation: 81

If I understand your question correctly, you are trying to return a variable from an ajax call to the parent scope (presumably the global scope) to inject it into the DOM.

The reason this is not easy to figure out is that it's impossible (at least in the common version of the language). The ajax call cannot return the data because it processes the http request asynchronously. You will need to either move your DOM injection code inside the .done callback, or (preferably) wrap the DOM injection code in another function called from your .done callback.

Upvotes: 0

Related Questions