How to pass value from javascript to php?

  • # March 14, 2013 at 6:11 am

    Hi , I m learning jquery , and I was trying to achieve this…
    There are two drop- down(select) , the first drop-down has a category, and the other drop-drown has sub catergory. And I want that when the user selects one category only the corrosponding subcategory should show up. I also used php and I was able to achieve what I wanted however I think this script can be written in more better way, and that’s where I need your suggestion. If you notice , I m repeating the code in ‘else if’ statement. I wanted to do it probably in a loop but for that I need the length of the category array. And I cannot pass value from javascript to php.

    < !DOCTYPE >

    < ?php
    $firstCat= array(‘Cars’, ‘Bikes’, ‘Food’, ‘Movies’, ‘Computers’);
    $Cars= array(‘BMW’,’Zen’,’Maruti’,’Scorpio’);
    $Bikes= array(‘ZMR’,’Karizma’,’Pulsur’,’Boxer’,’Splendor’);
    $Movies= array(‘Social Network’,’Zombie’,’Hang Over’,’Wrong Turn’,’Resident Evil’);
    $Computers= array(‘laptop’,’desktop’);

    # March 14, 2013 at 4:41 pm

    You will want to use JSON to communicate between javascript and php. What you do is build a JSON object or an array of JSON objects within php and then generate javascript using php doing something like:

    jQuery.parseJSON(‘< ?php json_encode($php_json_object_or_array); ?>‘);

    Then instead of building your subcategory select through php variables, you can build it entirely inside javascript using JSON.

    If you want to do this dynamically, you can additionally use ajax to post JSON.stringify(js_json_object_or_array) to php and call json_decode() on the post variable to get the JSON object or array and process in php. Once processing is finished, the php can echo the json_encode of the results and that will be available to javascript as the returned results (so instead of html, you will have a JSON string) on which you can run jQuery.parseJSON. Keep in mind the restrictions of form posting on the server applies to posting JSON as well.

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.