Returning two variables to two different divs from another php on onClick

The data that you send and receive to and from the server is send as text. While text itself does not have any meaning, the way it is formatted can.

Introducing JSON. JSON stands for JavaScript Object Notation and is a format that can be read by multiple languages. This makes it incredibly useful to exchange information between such platforms. JSON is represented as a string (text) which the language can transform into data that it can use.

Sidenote: although JavaScript is in the name it has nothing to do with it. The structure JSON uses resembles what objects and arrays in JS look like.

PHP for instance has the json_encode (data to JSON) and json_decode (JSON to data) functions to transform the data.

JavaScript has the JSON.stringify (data to JSON) and JSON.parse (JSON to data) methods to do the same thing but on its own side.

Let’s apply this to your case. So you’ve got more than 1 value to send to the client. But you can only send once. This calls for the use of an array() to send a list of items. In this array put your $gen and $img values.

Now call json_encode to transform your array into JSON and send it to the client.

<?php
$idno = ($_POST['idno']);
$gen = '';
$img = '';

if($idno >= 12345) {
    $gen = "ABC";
    $img = "<img src= 'abc.jpg'>";
} else {
    $gen = "DEF";
    $img = "<img src= 'def.jpg'>";
}

$response = array($gen, $img);
echo json_encode($response);

die();
?>

Now on the receiving end. The response that you now get is a string with a JSON structure. Convert this string to usable data with JSON.parse.

At this point you have received an array with two values in it. You can loop over the array or manually select something from it to output in your document.

function SubmitFormData() {
    var idno = $("#idno").val();
    $.post("submit.php", { idno: idno },
        function(response) {
             var data = JSON.parse(response);

             // data is now an array with two items.
             var gen = data[0];
             var img = data[1];
 
             $('#div1').html(img);
        }
    );
}

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top