Search code examples
jqueryjsonjsonp

Send json data as parameter via $.Ajax


I want to send to the backend a json string as one parameter and also other parameters. I am expecting to receive results as jsonp.

the parameters are

$param1 = '                          {
                              "MetaData": [
                                    {"Index": "0", "Name": "COLUMN_NAME"},
                                    {"Index": "1", "Name": "VALUE"},
                                    {"Index": "2", "Name": "VALUE_CHANGED"}
                                            ],
                              "Data": [
                                    ["ORDER_NO","*2733","f"],
                                    ["DISCOUNT_NO","1","f"],
                                    ["DISCOUNT_TYPE","S1","f"],
                                    ["DISCOUNT","11.4","t"],

                                            ]
                            } ';

how should I write the syntax in js and how should I receive it from the php side? when I try to use it like below it doesn't work.

$.ajax({

    url: 'http://... myfile.php',
    data: {PARAMETER1: $param1, PARAMETER2: $param2}
    type: 'GET',
    crossDomain: true,
    dataType: 'jsonp',
    error: function() { alert('Failed!'); }

}).done(function( data ) {
                            $.each(data, function(k,v) {
                               alert( "key: "+k+"  val:" + v);
                            })
                         });

Solution

  • Your Javascript code looks OK to me. On the PHP side, it would be:

    $param1 = json_decode($_GET['PARAMETER1'], true);
    

    Then you can access $param1['MetaData'][$i]['Index'], for instance.