简体   繁体   中英

Pass php array to Ajax variable

i need to pass an array variable to Ajax request

<?
   $postData = array(
   'FirstName'=>$_POST['user_name'],
   'Telephone'=>$_POST['user_phone'],
   'Description' =>$_POST['komment'],   
   'Classifierid'=>'5E0696FD-831E-E611-9426-005056BAB261'
);

$postData = json_encode($postData);?>

i need to pass $postData to ajax variable data:

$(document).ready(function () {
    var postData=<?php $postData ?>;
    $.ajax({
            url: "http://XXXXXXXXX/api/CallBackForm",
            type: "POST",
            crossDomain: true,
            data: I need to put $posData here,
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
        });
    });

`

I get the $postData successfully. All the code is in one php page.

Defining $postData like :

<?php $postData = json_encode(array('FirstName'=>$_POST['user_name'])); ?>

You can send directly the Json without datatype like :

$.ajax({
    url: "http://XXXXXXXXX/api/CallBackForm",
    type: "POST",
    crossDomain: true,
    data: '<?php echo $postData; ?>',
});

Or if you have to use the dataType: 'json' and ContentType option (important for server side), you can parse the json before sending ajax like :

$.ajax({
    url: "http://XXXXXXXXX/api/CallBackForm",
    type: "POST",
    crossDomain: true,
    data: JSON.parse('<?php echo $postData; ?>'),
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM