scubby3 scubby3 - 6 months ago 13
Javascript Question

Foreach not working in php and Jquery

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

Answer

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.

Comments