Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Retrieve array via AJAX response and populate dropdown menu.

Options
  • 05-04-2010 10:21pm
    #1
    Registered Users Posts: 2,234 ✭✭✭


    Hi,

    I have the following code that will make an ajax request to a php file which returns data.

    I would like to know how I can send the data from my php script to the browser (JS) as an array. I would then like to be able to iterate through that array so I can populate a dropdown box with the data from the array.

    Any advice greatly appreciated as i'm way out of my depth with javascript.

    Thanks.
    $(document).ready(function()
    {
    	$("div#calendar").datepicker(
    	{
    		altField: 'input#date',
    		altFormat: 'dd-mm-yy',
    		onSelect: function(dateText, inst)
    			{
    				$.post(
    					"server.php",
    						{
    						type: 'POST',
    						date: dateText
    						},
    					function(data)
    					{
    						alert(data);
                                                    // Do magic stuff here.
    					}
    				);
    			}
    	}
    	);
    });
    


Comments

  • Registered Users Posts: 7,468 ✭✭✭Evil Phil


    I would suggest passing it back to your javascript as JSON. I'm sure there's many php JSON libraries that will do this for you.


  • Closed Accounts Posts: 1,150 ✭✭✭Ross


    Evil Phil wrote: »
    I would suggest passing it back to your javascript as JSON. I'm sure there's many php JSON libraries that will do this for you.
    Notably, json_encode, which is a native PHP function that converts an associative array into a JSON structure.


  • Registered Users Posts: 7,468 ✭✭✭Evil Phil


    Ross wrote: »
    Notably, json_encode, which is a native PHP function that converts an associative array into a JSON structure.

    Or that even :pac:


  • Registered Users Posts: 2,234 ✭✭✭techguy


    Yea, I had seen the json_encode function. Does this return a JSON object or JSON array? Or is there a difference?

    How would I go about getting this returned text into a Javascript type that I can itereate through?


  • Registered Users Posts: 2,234 ✭✭✭techguy


    Ok..

    What I've done is create an associative array in PHP and then echo it using json_encode(). Here is the php:
    	$arr[0] = "1|test1";
    	$arr[1] = "2|test2";
    	$arr[2] = "3|test3";
    		
    	echo json_encode($arr);
    

    I then retrieve this in my javascript and foreach array item I will split it by the pipe '|' and put the data into a html select group. The data to the left of the pipe is the value of the option and the right hand side is the option for the user.

    Here we go..:
         var arr = JSON.parse(data);
         alert(data);
         for(var k in arr)
         {
              var tmp = arr[k].split("|");
              $("#date").append("<option value=\""+tmp[0]+"\">" + tmp[1] + "</option>");
         }
    
    <select name="date" id="date">
         <!-- dynamic options here -->	
    </select>
    

    What do you guys think of this? It's a little hacked together but it seems to work for me and i'll probably roll with it as I haven't any other solutions.

    Check it out here.

    Any comments?


  • Advertisement
  • Registered Users Posts: 569 ✭✭✭none


    Since arrays always start either from 0 or 1 and then get incremented strictly by 1, I wouldn't pass array index at all. It would save you some bytes of network traffic and some parsing operations on the client which may speed things up a bit.

    The point is that on the client you don't seem to need an array passed but rather built and you can build it in the same loop.

    So instead of this:
         for(var k in arr){
              var tmp = arr[k].split("|");
              $("#date").append("<option value=\""+tmp[0]+"\">" + tmp[1] + "</option>");
         }
    

    you can do this:
         for(var k in arr){
              //var tmp = arr[k].split("|");
              $("#date").append("<option value=\""+k+"\">" + arr[k] + "</option>");
         }
    

    Sorry, not sure it's JavaScript syntax above?? But you got the idea.


  • Registered Users Posts: 2,234 ✭✭✭techguy


    I understand what you are saying but the id for the selected option will actually be an in from the database so that will need to be sent from the server.

    What about my idea of splitting with the pipe?


  • Registered Users Posts: 26,579 ✭✭✭✭Creamy Goodness


    even still, send the selected value from the DB, and when you're looping through printing out the <option value="n">blah</option> do a check on i to see if i is equal to the selected value.


  • Registered Users Posts: 2,234 ✭✭✭techguy


    even still, send the selected value from the DB, and when you're looping through printing out the <option value="n">blah</option> do a check on i to see if i is equal to the selected value.

    But why, chances are that the DB id's will run into multiple digits but the option ID's probably won't. Why would I want to check at that stage any way if the id has already been sent from the server?


  • Registered Users Posts: 1,393 ✭✭✭Inspector Gadget


    Admittedly the last time I used AJAX/JSON etc. was on a Pylons project rather than a PHP one, but there's absolutely nothing I can see that'll stop you from JSONifying an associative array that contains both the IDs and the values for the options and sending that rather than having to do stuff with String.split() etc. on the client side? Example #1 at http://php.net/manual/en/function.json-encode.php illustrates this.

    The main reason to send the id number along with the name of whatever's to appear in the select option would be to simplify the parsing at the other end. If the select you're populating this way is part of a form that gets submitted to the server for processing, being able to identify exactly which database record the user's referring to can be very, very handy depending on exactly what you're trying to do. Is there an obvious relationship between the single-digit option IDs you have in mind and the database records they represent? If your plan involves you doing some sort of algorithm or database query just to resolve the DB record ID from the option ID, you'll save yourself a lot of hassle by just specifying the database ID at the outset.

    Just my 2c...
    Gadget


  • Advertisement
Advertisement