smith
smith

Reputation: 5461

pass array and individual string to php file using ajax call

I try to implement the following code

 var flag = new Array();
 var name = $("#myselectedset").val();      
$.ajax({
    type:         'post',
    cache:         false,
    url:          'moveto.php',
    data:     {'myselectset' : name,
              'my_flag' : flag
              },
    success: function(msg){
                     $("#statusafter").ajaxComplete(function(){$(this).fadeIn("slow").html(msg)});
                      }     
          });       

You can see that the name is a single string and the flag is an arry, am I using the right format for passing them throw ajax call, anyone could help me, thanks

Upvotes: 0

Views: 178

Answers (2)

LetterEh
LetterEh

Reputation: 26696

You should be able to do something quite simple, like replace your "data" property with:

data : JSON.stringify( { myselectset : name, my_flag : flag } )

That will convert the data into a JSON string that you can turn into PHP on the other side, using json_decode($_POST["my_flag"]);

Very important note:

For JSON.stringify to work, there can't be any functions in the array - not even functions that are object methods.

Also, because this is a quick example, make sure that you're testing for null data and all of the rest of the best-practices.

Upvotes: 0

Madara's Ghost
Madara's Ghost

Reputation: 174957

It is impossible to pass arrays in a POST request. Only strings.

You will either need to stringify your array, or consider posting as JSON instead.

Upvotes: 1

Related Questions