phpvariablesdrupalhook-menu

How can I pass a long javascript string to PHP hook_menu in Drupal?


On mysite/build-order I have a long order code that I'm assembling using Javacsript and sending via _GET in the URL to a hook_menu page for processing.

It can be as long as this (or longer), and am sending it to the create-order page like this:

<script type="text/javascript">
    //...building code
    var orderCode = "sku:OR-4x4>qty:2>prc:55.00>nfo:OR-4x4,sku:CVR>qty:1>prc:50>nfo:OR-4x4,sku:PF>qty:15>prc:2>nfo:OR-4x4 (sdfsdfg),sku:EM>qty:2>prc:12.95>nfo:OR-4x4 (sdfsdfg),sku:SC>prc:25>qty:4>nfo:Some description,sku:DB>qty:10>prc:4>nfo:Some description,sku:ES>qty:10>prc:3>nfo:BlahBlah,sku:OR-4x4>qty:2>prc:55.00>nfo:OR-4x4,sku:CVR>qty:1>prc:50>nfo:OR-4x4,sku:PF>qty:15>prc:2>nfo:OR-4x4 (sdfsdfg),sku:EM>qty:2>prc:12.95>nfo:OR-4x4 (sdfsdfg),sku:SC>prc:25>qty:4>nfo:Some description,sku:DB>qty:10>prc:4>nfo:BlahBlah-visiondelimiter-Phasellus laoreet lorem vel dolor tempus vehicula. Curabitur blandit tempus ardua ridiculus sed magna. Quisque placerat facilisis egestas cillum dolore.-visiondelimiter-eventName";

    var url = '/create-order/' + orderCode;
    window.location.replace(url);
</script>

Ive implemented a hook_menu setup in my custom module called "create_order_menu" and it works fine.

function mymodule_create_order_menu($ordercode){

    // do stuff with $ordercode

}

It all works fine. The only problem is that the order code string passed through the URL can sometimes be twice as long and it trips a 404 Error in the mysite/create-order page. When I shorten the code, it works. When I lengthen it again, it breaks.

Is there a better way to send such a lengthy variable to my hook_menu page setup?

EDIT (based on comments below)

On mysite/build-order I have a long order code that I'm assembling using Javacsript and using AJAX to send via POST to a hook_menu page for processing.

It can be as long as this (or longer), and am sending it to the create-order page like this:

<script type="text/javascript">
    //...building code
    var orderCode = "sku:OR-4x4>qty:2>prc:55.00>nfo:OR-4x4,sku:CVR>qty:1>prc:50>nfo:OR-4x4,sku:PF>qty:15>prc:2>nfo:OR-4x4 (sdfsdfg),sku:EM>qty:2>prc:12.95>nfo:OR-4x4 (sdfsdfg),sku:SC>prc:25>qty:4>nfo:Some description,sku:DB>qty:10>prc:4>nfo:Some description,sku:ES>qty:10>prc:3>nfo:BlahBlah,sku:OR-4x4>qty:2>prc:55.00>nfo:OR-4x4,sku:CVR>qty:1>prc:50>nfo:OR-4x4,sku:PF>qty:15>prc:2>nfo:OR-4x4 (sdfsdfg),sku:EM>qty:2>prc:12.95>nfo:OR-4x4 (sdfsdfg),sku:SC>prc:25>qty:4>nfo:Some description,sku:DB>qty:10>prc:4>nfo:BlahBlah-visiondelimiter-Phasellus laoreet lorem vel dolor tempus vehicula. Curabitur blandit tempus ardua ridiculus sed magna. Quisque placerat facilisis egestas cillum dolore.-visiondelimiter-eventName";

    $.ajax({
        type: "post",
        url: "/create-order/index.php",
        data: { 
        'orderCode': orderCode, 
        }
    })
    .done(function( msg ) {
        var newpage = '/create-order/index.php';
        window.location.replace(newpage);

  })

</script>

Ive implemented a hook_menu setup in my custom module called "create_order_menu" and it works fine. This creates the page mysite/create-order. There is a bunch of php in this page that has to parse the orderCode string into separate tasks. However, i can't get the hook_menu function to receive the _POST variable. This doesn't work:

function mymodule_create_order_menu(){

    $orderCode = $_POST['orderCode']; //doesn't work

    // do tasks with $orderCode

}

Neither does this, since the _POST declaration is outside of the function, it never actually gets called when loading mysite/create-order:

$orderCode = $_POST['orderCode']; //doesn't work

function mymodule_create_order_menu($orderCode){

    // do tasks with $orderCode

}

Do I have to add any arguments to my module hook_menu to pass to the create_order page?

function mymodule_menu(){
/**
 * Implements hook_menu()
 */
    $items['create-order'] = array(
        // page title
        'title' => 'Create Order',
        // function that is called when visiting the new path
        'page callback' => 'mymodule_create_order',
        'type' => MENU_CALLBACK,
        'access callback' => 'user_is_logged_in',    
    );
return $items;
}  

What's the best way to pass the _POST variable to my hook_menu page?


Solution

  • Yes you can call a PHP file, and send data to it using jQuery.ajax()

    To be able to do this you need to reference the jQuery library from where your script is running.

    Then write something like the following..

    var code = '#12345';
    
     $.ajax({
          url: 'create_order_menu.php',
          type: 'post',
          data: {'ordercode': code},
          success: function(data) {
            if(data == "received") {
              //order code received by PHP script
            }
          },
          error: function(xhr, desc, err) {
            console.log(xhr);
            console.log("Details: " + desc + "\nError:" + err);
          }
        });
    

    This ajax call posts JSON data to create_order_menu.php, and waits for a response of 'received' before continuing with the rest of the script.

    create_order_menu.php could be as simple as

    <?php
    
    $orderCode = $_POST['ordercode'];
    
    function createOrderMenu($orderCode){
    
    // do something with $orderCode
    
    return 'received';
    }
    

    This code here hasn't been tested. But the point here is yes there is an alternative way to send data to a PHP file, and this would be a better option than putting the whole order code in the URL.

    EDIT - Working Example

    <!DOCTYPE html>
    <html>
    <head>
        <script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
    </head>
    <body>
        <input type="button" class="callajax" value="Press">
    
    </body>
    
    
    <script type="text/javascript">
    
        var orderCode = '#12345';
    
        $(document).ready(function(){
            $('.callajax').on('click', function() { callAjax(orderCode); });
        });
    
    
        function callAjax(orderCode){
    
            $.ajax({
              url: 'create_order_menu.php',
              type: 'post',
              data: {'ordercode': orderCode},
              success: function(data) {
                if(data == "received") {
                  alert('Order code received.');
                }
              },
              error: function(xhr, desc, err) {
                console.log(xhr);
                console.log("Details: " + desc + "\nError:" + err);
              }
            });
    
        }
    </script>
    
    </html>
    

    create_order_menu.php file

    <?php
    
    if($_POST['ordercode']){
        createOrderMenu($_POST['ordercode']);
    }
    
    
    function createOrderMenu($ordercode){
        if($ordercode == '#12345'){
            echo "received";
        }
    }
    

    On pressing the button the ajax request will be called, POSTing our orderCode data to create_order_menu.php. If the PHP file is detected and the POST data is sent successfully the ajax 'success' function will be called upon the PHP script finishing (even if the PHP script throws an error - which can actually be viewed in the data variable for debugging).

    In this case our if condition inside the success function will evaluate to true and we will see the alert. Add an else statement and change the orderCode, then you will see another outcome.

    If the PHP script is not found or for some reason the POST data is not sent the 'error' function will be called. You can test this by renaming the PHP file and pressing the button again, then look in the console for an error.

    Notice that in this second PHP snippet I am now echoing 'received' rather than returning it, and I am calling the function we have defined.