0

I'm asking my server for some data. I used an AJAX call with a JSON object (which contains the ID of the selected object), and I want the server to return back to the AJAX call a new JSON object containing all the information about the product with the specified ID. here below there's the code

JavaScript:

$(document).ready(function() {

    // AJAX request on submit (login form)
    $("#form-login").submit(function (e) { // this works
        e.preventDefault();
        $.ajax({
            type: "POST",
            url: "submit.php",
            data: {
                Email: document.getElementById('login-email').value, // Email in the form
                Password: document.getElementById('login-password').value // Password in the form
        },
            cache: false,
            success: function() {
                window.location.href = "home.php"; // load the home.php page in the default folder
            }
        });
    });

    function getProduct(ID_product) {
        //AJAX request to get a product data from the server
        $.ajax({
            type: "POST",
            url: "product.php",
            dataType: "json",
            data: {
                 id_product: ID_product // the id of the single product
            },
            // success: function(data){ // here begin problems
            //     var obj = JSON.parse(data);
            //     alert(obj); // debug
            // }
            complete: alert("TEST")
        });
    }
});

PHP, product.php code:

<?php
require('include/header.php');

#Detect AJAX and POST request, if is empty exit
if((empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') or empty($_POST)){
    exit("Empty post to product.php");
}

if(!empty($_POST)){
    $id = $_POST['id_product'];

    $query_findProduct =  $db->query("SELECT Name, Description, Price, Available FROM PRODUCTS WHERE ID_product='$id' ");
    $product = $query_findProduct->fetch(PDO::FETCH_ASSOC);
    output($product);
}
?>

PHP, output function:

# Function to set JSON output
function output($Return=array()){
    header('Content-Type: application/json; charset=UTF-8');
    #exit(json_encode($Return)); # what's the difference with echo?
    echo json_encode($Return); # what's the difference with exit?
}

Home.php code for utility:

<?php
# getting all the product
$query_showProducts =  $db->query("SELECT ID_product, Name, Description, Picture, Price FROM PRODUCTS");

# putting all the products in an array
$products = array(); # an array that will contain all the product in the DB
while($prod = $query_showProducts->fetch(PDO::FETCH_ASSOC)){
    $products[] = $prod; # filling the array
}

#query that will store the total number of products in $productNumTot
$query_countProducts =  $db->query("SELECT COUNT(ID_product) FROM PRODUCTS");
$transitory = $query_countProducts->fetch(PDO::FETCH_ASSOC);
$productNumTot = $transitory['COUNT(ID_product)']; # total number of products

?>

<div id="products_area">
    <div id="categories">
        <ul>
            <li><a href="">Other</a></li>
            <li><a href="">Laptop</a></li>
            <li><a href="">Smartphone</a></li>
        </ul>
    </div>
    <div id="products">

        <?php
        for ($i=0; $i<$productNumTot; $i++){
            ?>
                <div id="product-box" onclick="getProduct(<?= $products[$i]['ID_product'] ?>)">
                    <div id="product-area-image">
                        <div id="product-image">
                            <?php
                                echo '<img src="data:image/png;base64,'.base64_encode( $products[$i]['Picture'] ).'"/>';
                            ?>
                        </div>
                    </div>
                    <div id="product-name">
                        <p><?= $products[$i]['Name'] ?></p>
                    </div>
                    <div id="product-price">
                        <p><?= $products[$i]['Price'] ?></p>
                    </div>
                </div>
            <?php
        }
        ?>

    </div>
</div>

My question is: will the server store the JSON object in a global variable for sending it back to the AJAX request? How can the client be able to receive and display the JSON obtained from the server (have I to build a function in JS with a parameter that will contain the JSON response?)? What I have to do if I simply want my client to pick this JSON and display it?

I apologize for the question, but I'm desperate!

2
  • actually what you're doing seems right - from a quick look if you uncomment the success-callback. You've commented // here begin problems - what problems? Commented Feb 2, 2018 at 23:55
  • The problem is that my server recive the request, and it do the echo of the product, but then on the client side I don't recive nothing! As you said, my code seems right. I don't know where is my error... Commented Feb 3, 2018 at 9:24

1 Answer 1

2

in your js file:

 function getProduct(ID_product) {
        //AJAX request to get a product data from the server
        $.ajax({
            type: "POST",
            url: "product.php",
            dataType: "json",
            data: {
                 id_product: ID_product // the id of the single product
            },
            success: function(data){ // data is a json object
                  console.log(data);//don't convert it (it's already an object)
            }
        });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.