Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript How to pass value from javascript to php?

  • This topic is empty.
Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #43370
    sayedtaqui
    Member

    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. http://codepen.io/sayed2x2/pen/khnmc






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




    #128246
    eternalsword
    Member

    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(‘‘);

    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)
  • The forum ‘JavaScript’ is closed to new topics and replies.