How to create an associated array in jquery and send it via ajax to get php parsing?

How do I create an associative array (or some comparable alternative) in jQuery and send this array via ajax to a php page so that I can use php to process it?

Something like that...

// jQuery if($something == true) { data[alt] = $(this).attr('alt'); data[src] = $(this).attr('src'); else if ($something == "something else") { data[html] = $(this).html(); } 

Then send this array using the .ajax () function

 // jQuery $.ajax({ data: /* somehow send my array here */, type: 'POST', url: myUrl, complete: function(){ // I'll do something cool here } }); 

Finally, parse this data with php ...

 // php <img alt="<?PHP echo $_POST['alt']; ?>" src="<?PHP echo $_POST['src']; ?>" /> 

I worked a bit on this issue and read that you cannot create an associative array with javascript, so I'm really looking for an alternative. Thanks in advance.

+4
source share
3 answers

You can pass data as a $.ajax() object, for example:

 var data = {}; if ($something == true) { data.alt = $(this).attr('alt'); data.src = $(this).attr('src'); }else if ($something == "something else") { data.html = $(this).html(); } $.ajax({ data: data, type: 'POST', url: myUrl, complete: function(){ // I'll do something cool here } }); 

This will be serialized for the message internally using $.param(obj) to convert it to POST, for example:

 alt=thisAlt&src=thisSrc 

or

 html=myEncodedHtml 
+4
source

Isn't it easier to just send json to the php side and then use the json_decode function in php to get an associative array on the php side?

0
source

An associative array is something like PHP. But you can have something like this with curly braces ({}). In fact, you are already using it in your $.ajax() call. Pay attention to parts of "{}". In this case, you can use json_decode() on the PHP server to decode the data parameter:

// jquery
$.ajax({
url: myUrl,
data: {
foo: 0,
bar: 1,
baz: 2
},
success: function() {
},
dataType: 'json'
});

Using json_decode () will give you something like:

// php array('foo' => 0, 'bar' => 1, 'baz' => 2);

0
source

All Articles