0

I would like store data from ajax call inside php variables.

I have a list of orders taken directly from DB. I need ,at the click of a specific order, an ajax call provide to get the informations of this specific order with the ID order. I made this, but i don't understand how can i get the return data and store them in php variables.

I have correctly the JSON with all data inside, but i can't get it.

I tried with store, with some functions that work correctly, the result of json inside variables but i get nothing and i don't understand why.

My principal file are two:

  1. table_orders.tpl.php Here i have the list of all orders stored in DB, and if i click on one of them, i can explode a second file (order_details.tpl.php) with all details reported inside with the AJAX call.
...some code....
                    <td class="product_list"  data-id="<?= $ordine["id_order"] ?>">
                        <?PHP 
                        $idCart  = $ordine["id_cart"];
                        $idOrder = $ordine["id_order"];
                        $prodotti = $dataProducts->getListProducts($idCart);
                        $nbProducts = $dataProducts->getCountProducts($idCart);
                        foreach ($prodotti as $prodotto):
                        ?>    
                            <b><?= $prodotto["reference"] ?></b>  <?= $prodotto["reference"] ? "|" : "" ?> <?= $prodotto["quantity"] ?><br>
                            <?= ucfirst(strtolower($prodotto["name"])) ?><br>
                        <?PHP endforeach ?> 
                    </td>
...some code...

<script>
$(".product_list").on("click", function () {
    $("#order_detail").css("display", "block");
    var id_ordine = $(this).attr("data-id");
    $.ajax({
        type: 'GET',
        dataType:"jsonp",
        data:{"id_ordine":id_ordine},
        async:false,
        url: 'http://localhost/en-manager/views/components/orders/order_details.tpl.php',
        success: function (data, status, xhr) {
            console.log('data: ', data);
        }
    });
});
</script> 
  1. order_details.tpl.php This is the file called by AJAX and where i will put all the information order inside. As we can see in the screenshot, the data are correctly showed in JSON but, when i try to stored them in a php variable, i have absolutely nothing (even the dump $_REQUEST didn't get the 'id_ordine')
if ($_GET['id_ordine'])
{
   
    if ( $indirizzoConsegna= ['Consegna' => $addressData::getAddressDeliveryWithIdOrder($_GET['id_ordine']) ] ) 
    {
        echo(json_encode($indirizzoConsegna, JSON_PRETTY_PRINT));
    };
    if ($invoiceAddress = ['Fattura' => $addressData::getAddressInvoiceWithIdOrder($_GET['id_ordine'])]) 
    {
        echo(json_encode($invoiceAddress, JSON_PRETTY_PRINT));
    };
    if ($orderDetail = ['DettaglioOrdine' => $orderData->getOrderById($_GET['id_ordine'])]) 
    {
        echo(json_encode($orderDetail, JSON_PRETTY_PRINT));
    };
}

?>
<div class="container" id="order_detail" style="display:none;" >
    <div class="row">
        <div class="col-2">
            <button type="button" onclick="closeWindow()" id="close_order_detail" class="btn btn-danger">Chiudi</button>
        </div>
        <div class="col-10">       
        </div>
    </div>
    <div class="row">
        <div class="col-8">
            <div class="row">
                <div class="col">
                    <?= var_dump($indirizzoConsegna)?>
                <b>ORDINE</b> n° del <b>DATA</b>  
                </div>   
            </div>
            ...some code...

enter image description here

Zed93
  • 39
  • 5
  • 1
    If you're seeing that output directly within your page, then it means the request is not being done via AJAX. The response to your AJAX call is delivered into a JavaScript variable: `data` in the "success" function in your case - and you have only written code which would log that response to the console, not show it within the web page. – ADyson May 24 '22 at 09:27
  • 1
    P.S. As an aside, `dataType:"jsonp"` makes no sense in your case because it looks like order_details.tpl.php returns HTML, not a JS callback. And `async:false` is deprecated because it leads to a very poor user experience (i.e. freezing the browser) and it's also really not necessary...AJAX is intended to be asynchronous, and that's a good thing, so you should work _with_ that, not against it. – ADyson May 24 '22 at 09:30
  • you should separated the ajax response and html output, inside the `if ($_GET['id_ordine']) { /* here */ }` you are echoing all the data as json, which is what you want to store as php variable (not sure why you want it but there it is), and after that you should call `exit;` to not print the html part – Kazz May 24 '22 at 09:37
  • @ADyson and in success what i have to do? Store the value into a JS variable? Thank you for your help! – Zed93 May 24 '22 at 09:44
  • Well that response value is already in a JS variable as I said - anything which is echoed from PHP is returned into `data` when the AJAX request finishes. But what I was actually saying to you is that the error you're reporting appears to come from a _non-AJAX_ request. From the code and description you've shown though, it's unclear how that would be happening. I suspect that we don't have a [mre] of your issue - maybe you need to do some more investigation on your side to narrow down the problem area. e.g. Are you actually calling or requiring `order_details.tpl.php` at some other time too? – ADyson May 24 '22 at 09:58
  • Yes, it's required in the index.php file. – Zed93 May 24 '22 at 10:11
  • But what i don't understand is: why i can get the id of order and execute my php correctly function, but i can't store the result into a variable? Because $deliveryAddress = $addressData::getAddressDeliveryWithIdOrder($_GET['id_ordine']) work correctly, but outside of php part that is not defined – Zed93 May 24 '22 at 10:22
  • You really need to clarify what you are talking about now. There is no `$deliveryAddress = ...` anywhere in the code you have shown us so far, so we don't know what _"but outside of php part that is not defined"_ actually means now. Please edit your question, and add the current code that you are talking about here. – CBroe May 24 '22 at 10:59
  • `it's required in the index.php file`....well then, when you include the script there, you are not passing `id_ordine` into it - that only happens in the AJAX request, which is a _totally separate_ request to that script, which only happens later, when someone clicks on an item in your page. If you want to use that script via AJAX and send the ID to it dynamically, then it's unclear why you also included it in index.php...that doesn't make a lot of sense. – ADyson May 24 '22 at 11:06
  • @CBroe sorry, i have translate the variable XD! I m talking about of $indirizzoConsegna. In the condition `if ( $indirizzoConsegna= ['Consegna' => $addressData::getAddressDeliveryWithIdOrder($_GET['id_ordine']) ] )`, the function work correctly and $indirizzoConsegna contain the array of values. But i don't understand why this variable became not defined outside the `if ($_GET['id_ordine'])` – Zed93 May 24 '22 at 11:06
  • Are you actually looking at the response your AJAX request got? Or are you making a second, separate request now to "check" on the result? – CBroe May 24 '22 at 11:10
  • And why does your script even respond with JSON _and_ HTML, at the same time? That doesn't make much sense to begin with. – CBroe May 24 '22 at 11:11
  • @CBroe I get the sense the JSON part was done for debugging purposes, although I agree it's unclear. OP is making a second request to the script as per their earlier comment where they confirmed that order_details.tpl.php is also required in their index.php script, as well as being called via AJAX. That explains the in-page output visible in the screenshot. At the bottom we can of course see the separate output from the AJAX-triggered request. – ADyson May 24 '22 at 11:14
  • @CBroe Yes JSON part it war for debug. I want fill the html part with the return values of `getAddressDeliveryWithIdOrder`, is for that i need to store the result into a variable. – Zed93 May 24 '22 at 13:46
  • @Kazz but if i put the exit inside the condition, how can i keep the value of `getAddressDeliveryWithIdOrder` and fill the html part? – Zed93 May 24 '22 at 13:47
  • @Zed93 just decide which way you wanna update your site, either you send only json data and do filling on js side, or you send only prefilled html data – Kazz May 24 '22 at 13:55
  • @Kazz can you give me some exemples for do that? Because with ajax, i get the `id_ordine`, but the rest of data i get with the php function. So, how can i prefill html data with js through the php function? Sorry but i don't know very well JS, i take some pieces but it s not very clear how that working – Zed93 May 24 '22 at 14:04
  • you need to understand the server side vs client side code, i don't think you're clear on that: https://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming#13840431 the need of having the information in php variable indicate that – Kazz May 24 '22 at 14:17
  • imagine doing the same thing without javascript, instead `onclick` you have anchor, then php is designed to output entire page, now if you add the ajax then you just separate the changing part of html, which js receive and replace it, which works well as long as there isn't a lot of same data, when there is you want to output from php just the changing data, json is great format to pass data between php and js, but then you have just object created out of the json passed, with raw data, so you have to assign each data to specific html creating elements on the way (reconstructing what php does) – Kazz May 24 '22 at 14:46
  • @Kazz thank you very much for your patient . I appreciate it! That became more clear to me – Zed93 May 24 '22 at 15:56

0 Answers0