I am trying to pass a javascript array
to a php
script using JQuery load()
.
This is my JQuery
:
$('#saveBtn').click(function(e){
e.preventDefault();
//Get hidden field values and store in an Array
$tagArray = [];
//Get the Checked Tags and store in an Array
$('#tag_results :checked').each(function(){
$tagArray.push(this.value);
});
//Make Ajax request to the add_tags script and pass Array as parameter. When response recieved show dialog.
//Pass the name, id and type of company with the array of tags to the save_tags.php script.
$('#test').load('pages/ajax/save_tags.php', {'tags': JSON.stringify($tagArray) ,'name': $('#comp_name').val(), 'id': $('#comp_id').val(), 'type': $('#type').val() });
});
I then access the POST
Array from my php script
:
$id = $_POST['id'];
$name = $_POST['name'];
$type = $_POST['type'];
$tags = $_POST['tags']; //Should be an Array but is a String...
//Type can be company, contact, column, supplement, programme.
if($type === 'company'){
$company = new DirectoryCompany($id);
}
//Loop through the Tag array and add to the item.
foreach($tags as $tag){
$company->addTag($tag, $id);
}
However when I do a var_dump($tags)
I'm told it is a String
, not an Array
and as a result I get an error when I pass $tags
to the foreach
loop. I know that an array should be in a key value pair format when passing via POST but I'm not entirely sure how I can do that, I thought by converting it to JSON
before passing it would do the trick but it still isn't working.
Any help is much appreciated.