0

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.

0

1 Answer 1

3

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',
});
Sign up to request clarification or add additional context in comments.

2 Comments

I might be wrong but I don't think you have to JSON.parse a JSON string when you use it in JavaScript as a variable? Like so: var postData = <?php echo $postData; ?>;
Without parse the json, i think Ajax will send a serialisation of the serialised array like : "string": "\" { \"toto\" }\""

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.