tatty27
tatty27

Reputation: 1554

Display different parts of JQuery Ajax response in separate DIVs

I have a script that allows the user to grade an image and then dynamically adds another form to the page to grade the next. When the image grade is entered it is entered into a database and displayed on the page above the newly created form in a list with the ID responds.

All of this works great but I would also be able to show a running count of how many images have been audited at the top of the page in a DIV with the ID results.

The JQuery

$("#FormSubmit").click(function (e) {
        e.preventDefault();
        if($("#grade").val()!='1')
        {
            if($("#positioning_reason").val() == '' &&
                                  $("#exposure_reason").val() == '' &&
                                  $("#equipment_reason").val() == '' &&
                                  $("#patient_reason").val() == '')
                            { 
               alert("Please select why the image was not perfect");
               return false;
            }
        }
        jQuery.ajax({
        type: "POST",
        url: "response.php",
        dataType:"text",
        data: $('#test_form').serialize(),
        success:function(response){
            $("#responds").append(response);
            $('#test_form')[0].reset();
            $("#test_form").get(0).scrollIntoView();
            $("#results").display $numRows in this div          
        },
        error:function (xhr, ajaxOptions, thrownError){
            alert(thrownError);
        }
    });

});

response.php

//include db configuration file
include 'includes/db_connect.php';

if(isset($_POST['grade'])) 
    {
    $grade = $_POST['grade'];
    $positioning = $_POST['positioning_reason'];
    $exposure = $_POST['exposure_reason'];
    $patient = $_POST['patient_reason'];
    $equipment = $_POST['equipment_reason'];
    $user_id = $_POST['user_id'];
    $audit_id = $_POST['audit_id'];

    $sql= "INSERT INTO image(auditID, imageGrade,positioning_reasonID,exposure_reasonID,patient_reasonID,equipment_reasonID,auditDate,userID) VALUES('$audit_id', $grade,'$positioning','$exposure','$patient','$equipment',NOW(),$user_id)";
    $result = mysqli_query($mysqli,$sql) or die(mysqli_error($mysqli));

    if($result)
    {
        $sql = "SELECT * FROM image WHERE auditID = '$audit_id'";
        $result = mysqli_query($mysqli,$sql) or die(mysqli_error($mysqli));
          $numRows = mysqli_num_rows($result);
          $my_id = mysqli_insert_id($mysqli);
          $output_array = array(
              'my_id' => $my_id,
              'grade' => $grade,
              'numRows' => $numRows
          );

    }else{

        header('HTTP/1.1 500 Looks like mysql error, could not insert record!');
        exit();
    }

}
elseif(isset($_POST["recordToDelete"]) && strlen($_POST["recordToDelete"])>0 && is_numeric($_POST["recordToDelete"]))
{   
    $idToDelete = $_POST["recordToDelete"]; 

    $sql = "DELETE FROM image WHERE imageID = $idToDelete";
    $result = $result = mysqli_query($mysqli,$sql) or die(mysqli_error($mysqli));
    if(!$result)
    {     
        header('HTTP/1.1 500 Could not delete record!');
        exit();
    }
}
else
{
    header('HTTP/1.1 500 Error occurred, Could not process request!');
    exit();
}
echo json_encode($output_array);

I would like to display the value $numRows in a div called 'results' (at present it i being displayed with all of the other results for testing purposes). I have tried getting the $numRow value from a different php page using a separate page load function further down the page but it was very slow and the result were not always correct because of timings

Upvotes: 1

Views: 2432

Answers (1)

Jack Cole
Jack Cole

Reputation: 1804

Using JSON would be a better option, as others in the comments have pointed out.

if($result)
    {
        $sql = "SELECT * FROM image WHERE auditID = '$audit_id'";
        $result = mysqli_query($mysqli,$sql) or die(mysqli_error($mysqli));
          $numRows = mysqli_num_rows($result);
          $my_id = mysqli_insert_id($mysqli);
          $output_array = array(
              'my_id' => $my_id,
              'grade' => $grade,
              'numRows' => $numRows
          );
    }
//etc...

Then at the end of the file:

echo json_encode($output_array);

Now you do the HTML formatting in your AJAX success function:

    jQuery.ajax({
    type: "POST",
    url: "response.php",
    dataType: "json",
    data: $('#test_form').serialize(),
    success:function(response){
        $("#responds").empty().append('<li id="item_'+response.my_id+'" class="audit_item">'+
        '<div class="del_wrapper"><a href="#" class="del_button" id="del-'+response.my_id+'">'+
        '<img src="images/icon_del.gif" border="0" />'+
        'Grade - '+response.grade+' - '+response.my_id+' - '+response.numRows+'</li>'+
        '</a></div>')            
        $('#test_form')[0].reset();
        $("#test_form").get(0).scrollIntoView();
        $("#results").empty().append('<b>'+response.numRows+'</b>')
    },
    error:function (xhr, ajaxOptions, thrownError){
        alert(thrownError);
    }
    });

Upvotes: 1

Related Questions