0

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.

Javacadabra
  • 5,578
  • 15
  • 84
  • 152

3 Answers3

2

Your variable $_POST['tags'] is encoded with JSON also, its converted into string.

in php you can use json_decode():

$tags = json_decode(stripslashes($_POST['tags']));

This way, you get your required array.

Pupil
  • 23,834
  • 6
  • 44
  • 66
2

You could try json_decode to get an array.

Ferret
  • 1,440
  • 2
  • 12
  • 17
0

$tagsArray is already in JSON format.

Just make the request like this

$("#test").load("pages/ajax/save_tags.php", {
    "tags": $tagArray ,
    "name": $("#comp_name").val(), 
    "id": $("#comp_id").val(), 
    "type": $("#type").val() 
});
mvpasarel
  • 775
  • 5
  • 13