Post multiple select in php

Sending HTML Form Multiple box via POST request with AJAX?

I have an html form with a multiple select box. I can’t figure out how to send the values to my php application with AJAX via a post request. It works just fine if I use a GET request and use a single select box but not when I use a multiple select box. The idea is for users to hold control (or command with mac) and select one or more categories. Depending on which categories are selected will determine what other form options will be displayed using AJAX. The select box looks like this: Edit: SOLVED

  
function sendCategories(sel) < if (window.XMLHttpRequest) < xmlhttp=new XMLHttpRequest(); >else < xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); >xmlhttp.onreadystatechange=function() < if (xmlhttp.readyState==4 && xmlhttp.status==200) < document.getElementById("my_div").innerHTML=xmlhttp.responseText; >> xmlhttp.open("POST","http://www.mysite.com/update_categories.php",true); xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); var values = $(sel).serialize(); xmlhttp.send(values); > 

4 Answers 4

You’ll have to generate the query string to send in the POST on your own. Here’s the HTML tag to use:

And the Javascript function:

function sendCategories(sel) < var xmlhttp; if (window.XMLHttpRequest) < xmlhttp = new XMLHttpRequest(); >else < xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); >xmlhttp.onreadystatechange = function () < if (xmlhttp.readyState === 4 && xmlhttp.status === 200) < document.getElementById("my_div").innerHTML = xmlhttp.responseText; >>; xmlhttp.open("POST","http://www.mysite.com/update_categories.php",true); xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); var values = [], i, j, cur; for (i = 0, j = sel.options.length; i < j; i++) < cur = sel.options[i]; if (cur.selected) < values.push(encodeURIComponent(cur.value)); >> if (values.length) < values = encodeURIComponent(sel.name) + "=" + values.join("&" + encodeURIComponent(sel.name) + " http://jsfiddle.net/kKWQM/" rel="noreferrer">http://jsfiddle.net/kKWQM/

)" data-controller="se-share-sheet" data-se-share-sheet-title="Share a link to this answer" data-se-share-sheet-subtitle="" data-se-share-sheet-post-type="answer" data-se-share-sheet-social="facebook twitter devto" data-se-share-sheet-location="2" data-se-share-sheet-license-url="https%3a%2f%2fcreativecommons.org%2flicenses%2fby-sa%2f3.0%2f" data-se-share-sheet-license-name="CC BY-SA 3.0" data-s-popover-placement="bottom-start">Share
)" >Improve this answer
)">edited Aug 28, 2013 at 1:41
answered Feb 8, 2013 at 5:29

11

    Hmmm. definitely getting warmer. Seems like this would work but for some reason when I try to retrieve the post request on the server end with my php application, I'm still not getting anything. I'm trying to to check the values like this: print_r($_POST['values'])
    – denvdancsk

    Feb 8, 2013 at 15:52

    1
    @kyzer1978 Awesome, glad you're getting closer! So, I'm not sure why you're using $_POST['values'] - if you look at the alert in the jsFiddle, you'll notice the querystring is something like: categories[]=asdf&categories[]=fdsa&categories[]=aaa. So the "key" that should be used is "categories[]" when accessing $_POST. That means, you should try $_POST['categories[]']. Does that make sense? Try that out and let me know what happens. If that doesn't work, try $_POST['categories']. values is just the name of the Javascript variable and has no relation to what's sent to the server

    – Ian

    Feb 8, 2013 at 15:57

    1
    @kyzer1978 The reason it "has no relation to what's sent to the server" is because I am emulating what is done when a multiple is normally submitted (without AJAX). When forms are submitted, each input's value is submitted as key=value, where the key is the name attribute of the element, and the value is the current value of the element. With a multiple , there needs to be a way to distinguish between all values selected. So while normally, it would be categories[]=val1 for a non-multiple , it replicates that for every value selected.

    – Ian

    Feb 8, 2013 at 16:00

    Thanks for the quick response. Makes total sense now to use $_POST['categories']. Unfortunately though it doesn't seem to be working yet with or without the extra brackets. I did notice in the jsFiddle you sent that when I changed the values in the select box I still got the same query string.

    – denvdancsk

    Feb 8, 2013 at 16:19

    1
    @kyzer1978 Ahh I see what .serialize is doing differently. It doesn't seem to be encoding = and &. So I updated my answer to only encode the key and value in the pairs and that's it. Yet another dumb mistake by me. Hopefully that would fix it. I could've sworn it was okay to just call encodeURIComponent on the final querystring you were going to pass.

    – Ian

    Feb 8, 2013 at 19:40

|Show 6 more comments

4

You can do something like this,

And Make AJAX using JQuery,

function sendCategories(sel) < var values = $(select).serialize(); console.log (values); // See if you get the serialized data in console. $.ajax(< type: 'POST', url: "http://www.mysite.com/update_categories.php" data: values, success: function (data) < document.getElementById("my_div").innerHTML = data; >>); > 

And FYI, Netscape event binding model is deprecated, you could use the cross browser event binding like this

Источник

PHP Select Option

Summary: in this tutorial, you will learn how to use the element to create a drop-down list and a list box and how to get the selected values from the element in PHP.

A quick introduction to the element

The is an HTML element that provides a list of options. The following shows how to define a element in HTML:

label for="color">Background Color: label> select name="color" id="color"> option value="">--- Choose a color --- option> option value="red">Red option> option value="green">Green option> option value="blue">Blue option> select>Code language: HTML, XML (xml)

The element has two important attributes:

  • id – the id associates the element with a element
  • name – the name attribute associates with the value for a form submission.

The element nested inside the element defines an option in the menu. Each option has a value attribute. The value attribute stores data submitted to the server when it is selected.

If an option doesn’t have the value attribute, the value attribute defaults to the text inside the element.

To select an option when the page loads for the first time, you can add the selected attribute to the element.

The following example selects the Green option when the page first loads:

label for="color">Background Color: label> select name="color" id="color"> option value="">--- Choose a color --- option> option value="red">Red option> option value="green" selected>Green option> option value="blue">Blue option> select>Code language: HTML, XML (xml)

Getting the selected value from a element

We’ll create a form that uses a element.

First, create the following folders and files:

├── css | └── style.css ├── inc | ├── footer.php | ├── get.php | ├── header.php | └── post.php └── index.php Code language: JavaScript (javascript)

Second, place the following code in the header.php file:

html> html lang="en"> head> meta charset="UTF-8"> meta name="viewport" content="width=device-width, initial-scale=1.0"> link rel="stylesheet" href="css/style.css"> title>PHP select option title> head> body class="center"> main>Code language: HTML, XML (xml)

Third, place the following code in the footer.php file:

 main> body> html>Code language: HTML, XML (xml)

Fourth, add the following code to the get.php file to create a form that has one element with a submit button:

form action="" method="post"> div> label for="color">Background Color: label> select name="color" id="color"> option value="">--- Choose a color --- option> option value="red">Red option> option value="green" selected>Green option> option value="blue">Blue option> select> div> div> button type="submit">Select button> div> form>Code language: HTML, XML (xml)

The form uses the POST method to submit data to the webserver.

Finally, add the following code to the post.php file:

 $color = filter_input(INPUT_POST, 'color', FILTER_SANITIZE_STRING); ?>  if ($color) : ?> p>You selected span style="color:"> echo $color ?> span> p> p>a href="index.php">Back to the form a> p>  else : ?> p>You did not select any color p>  endif ?>Code language: HTML, XML (xml)

To get the selected value of the element, you use the $_POST superglobal variable if the form method is POST and $_GET if the form method is GET .

Alternatively, you can use the filter_input() function to sanitize the selected value.

If you select the first option of the element, the selected value will be empty. Otherwise, the selected value is red, green, or blue.

Select with multiple options

To enable multiple selections, you add the multiple attribute to the element:

select name="colors[]" id="colors" multiple> . select>Code language: HTML, XML (xml)

When you select multiple options of a element and submit the form, the name will contain multiple values rather than a single value. To get multiple selected values, you add the square brackets ( []) after the name of element.

Let’s take a look at an example of using a element with multiple selections.

First, create the following folders and files:

. ├── css | └── style.css ├── inc | ├── footer.php | ├── get.php | ├── header.php | └── post.php └── index.phpCode language: JavaScript (javascript)

Second, place the following code into the header.php file:

html> html lang="en"> head> meta charset="UTF-8" /> meta name="viewport" content="width=device-width, initial-scale=1.0" /> title>PHP Listbox title> link rel="stylesheet" href="css/style.css"> head> body class="center"> main>Code language: HTML, XML (xml)

Third, add the following code to the footer.php file:

 main> body> html>Code language: HTML, XML (xml)

Fourth, include the header.php and footer.php files in the index.php :

 require __DIR__ . '/inc/header.php'; $request_method = strtoupper($_SERVER['REQUEST_METHOD']); if ($request_method === 'GET') < require __DIR__ . '/inc/get.php'; > elseif ($request_method === 'POST') < require __DIR__ . '/inc/post.php'; > require __DIR__ . '/inc/footer.php'; Code language: HTML, XML (xml)

If the HTTP request is GET, the index.php file will show a form from the get.php file. When the form is submitted, the post.php file will handle the form submission.

Fifth, create a form that contains a element with the multiple attribute in the get.php file. The name of the element has an opening and closing square bracket [] so that PHP can create an array that holds the select values.

form action="" method="post"> div> label for="colors">Background Color: label> select name="colors[]" id="colors" multiple> option value="red">Red option> option value="green">Green option> option value="blue">Blue option> option value="purple">Purple option> option value="magenta">Magenta option> option value="cyan">Cyan option> select> div> div> button type="submit">Submit button> div> form>Code language: HTML, XML (xml)

Finally, handle the form submission in the post.php file:

 $selected_colors = filter_input( INPUT_POST, 'colors', FILTER_SANITIZE_STRING, FILTER_REQUIRE_ARRAY ); ?>  if ($selected_colors) : ?> p>You selected the following colors: p> ul>  foreach ($selected_colors as $color) : ?> li style="color:"> echo $color ?> li>  endforeach ?> ul> p> p>  else : ?> p>You did not select any color. p>  endif ?> a href="index.php">Back to the form a>Code language: HTML, XML (xml)

The post.php file uses the filter_input() function to get the selected colors as an array. If you select one or more colors, the post.php file will display them.

Summary

  • Use the element to create a dropdown list.
  • Use the multiple attribute to create a list that allows multiple selections.
  • Use $_POST to get the selected value of the select element if the form method is POST (or $_GET if the form method is GET ).
  • Add square brackets( [] ) after the name of the element to get multiple selected values.

Источник

Читайте также:  Питон цикл for else
Оцените статью