1

I am trying to do a foreach loop in php and jquery for multiple select but all i am getting to echo out is Array.

html

<select multiple="multiple" class="select tagz" required>

php

if(!empty($_POST['tagz'])){
            $tag = $_POST['tagz']);

            foreach($tag as $tagz){
            echo $tagz;
            }

        }else{
            echo "Please select tags";
        }

Jquery

function serealizeSelects (select)
        {
            var array = [];
            select.each(function(){ array.push($(this).val()) });
            return array;
        }
        var tagz = serealizeSelects($(".tagz"));
$.post('upload.php', {tagz:tagz, title:title, category:category, description:description, price:price}, function(data){

            $('#confirm').html(data);

        });

Please tell me what i am doing wrong

6
  • 3
    Your select element is not named therefor $_POST['tagz'] is empty. Commented May 12, 2016 at 12:53
  • 2
    php and jquery (javascript) are two different worlds ... the php is running on your server ... the javascript is running on your browser .. Commented May 12, 2016 at 12:54
  • @subby3 you have doing many typo mistake check in my ans Commented May 12, 2016 at 13:05
  • @Wobbles please let them check,i think you didn't specify $tag = $_POST['tagz']); to $tag = $_POST['tagz']; Commented May 12, 2016 at 13:08
  • 1
    if you think something is helpful but not clear explanation so you can edit my ans.it's my pleasure if you make me correct @Wobbles Commented May 12, 2016 at 13:13

2 Answers 2

1

You are doing select.each(function(){ array.push($(this).val()) }); but select variable contains only the select element and each has no meaning.You need to use each in the options.So change your selector.

           var tagz = serealizeSelects($(".tagz option"));

or if you dont want to change the selector just use find to find all options inside your select

           select.find('option').each(function(){ array.push($(this).val()) })

Of course i cannot know where you define your other variables.If you have other problems too just show me your whole javascript code so I can help you more.

Sign up to request clarification or add additional context in comments.

Comments

0

You are trying to get a post variable for a field named tagz, but you do not have a field named tagz (at least not in the code you have provided).

Consider changing the HTML to this:

<select name="tagz" multiple="multiple" class="select tagz" required>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.