0

I have an array in javascript that separated with ,. but inside of them there are some values containing , as it's value. my problem is I don't want to explode such these values but the php does it. Is there any way to handle it?

<form id="form" method="post">
<table>
<tr val="sprots, music, videos"><td>sprots, music, videos</td></tr>
......
......
<tr val="car"><td>car</td></tr>
</table>
<input type="hidden" name="category" id="category" value="">
</form>
<script>
    var Data=[];
    $('table').find('tr').each(function(){
       Data.push($(this).attr('val'));
    });
$('#category').val(Data);
</script>

<?php
$category=$_POST['category'];
$tmp=explode(',',$category);
?>

the problem occurs when it wants to explode value like this:array[0]='sports, music,videos'. it explodes it as 3 separated array which is sth like this: array[0]='sports', array[1]='music', array[2]='videos'. I want to explode this value as a unique part, I mean like this: array[0]='sports, music,videos'

1 Answers1

1

as Dinesh Suggested you can change separator, instead of comma use something that never get you in trouble

for Example:

var Data=[];
$('table').find('tr').each(function(){
   Data.push('~'+ $(this).attr('val'));
});
console.log(Data);

Output :

["~sprots, music, videos", "~car"]

But when you Post data it will become like ~sprots, music, videos,~car in server side You have to do something like this

<?php
$category=$_POST['category'];
$tmp=explode('~',$category);
unset($tmp[0]);
var_dump($tmp);
?>

Output :

array(2) {
  [1] =>
  string(22) "sprots, music, videos,"
  [2] =>
  string(3) "car"
}
chudasamachirag
  • 317
  • 5
  • 14
  • I tried this but it doesn't add `~` at the first value. what's wrong with it? – hilary clinton Jun 01 '16 at 11:26
  • If the output would be as you mentioned, there is no problem but the output is like this:`[~sports, music, videos,~car]`. it adds additional `,` because the `,` after videos, will be put inside array[0]. – hilary clinton Jun 01 '16 at 11:48
  • I am not clear. can you please add your input and output – chudasamachirag Jun 01 '16 at 12:07
  • in client-side it shows the correct form, sth like this: `array[0]="sports, music, videos"/ array[1]="car",...` but when I get at server-side, I get the array like this:`[~sports,music,videos,~car]`.if I can get this array at server-side like this , the problem will be solved.`array[0]='sprort, music,videos', array[1]="car",... – hilary clinton Jun 01 '16 at 12:16
  • yes, this given code will add `[~sports,music,videos,~car]` in your hidden form attribute "category". so, i think as per current situation your problem is solved. – chudasamachirag Jun 01 '16 at 12:45
  • yes but another problem is appeared and that's additional `,`. in this situation at the end of each explode, add`,` – hilary clinton Jun 01 '16 at 12:53
  • http://stackoverflow.com/questions/1642698/how-do-i-remove-a-comma-off-the-end-of-a-string – chudasamachirag Jun 01 '16 at 13:42