skip to Main Content

I have a php function and in this php function I am trying to implement an API call using jQuery. I could not use PHP for this because of some restrictions so I need to use jQuery in this function. I added my jquery code inside PHP function which is working correctly for static data. But I do not know how I should pass PHP variables in data. Any suggestion regarding this will be appreciated.
Here is my code for jQuery

var settings = {
"url": "MY_URL_TO_CREATE_USER_ACCOUNT",
"method": "POST",
"timeout": 0,
"headers": {
    "external-token": "MY_TOKEN",
    "Content-Type": ["application/json", "text/plain"]
},
"data": "{rn"UserName": "user6",rn"FirstName": "F_NAME",rn"Password": "user6_pass",rn"LastName": "L_NAME",rn"Subscription": "Full",rn"ExpireDate": "2020-11-08"rn}",
};

jQuery.ajax(settings).done(function (response) {
    console.log(response);
});

This code works for static data but I do not know how to pass php variables for the data attribute.

3

Answers


  1. More proper solution would be using form.data for this.

    Probably not the best solution, but try this,

    1. Echo out the variable and assign it to javascript variable
    2. Use that variable in the data attribute
    Login or Signup to reply.
  2. Try this. Store the value of your PHP variable in a field then get the value of the field via jQuery.

    <?php
    
    $settings = '{
    "url": "MY_URL_TO_CREATE_USER_ACCOUNT",
    "method": "POST",
    "timeout": 0,
    "headers": {
    "external-token": "MY_TOKEN",
    "Content-Type": ["application/json", "text/plain"]
    },
    "data": "{rn"UserName": "user6",rn"FirstName": "F_NAME",rn"Password": "user6_pass",rn"LastName": "L_NAME",r "Subscription": "Full",rn"ExpireDate": "2020-11-08"rn}",
    };';
    echo "<textarea style='display:none' id='some_data'>$settings</textarea>";
    
    //Then your jQuery
    var settings = $("#some_data").val();
    jQuery.ajax(settings).done(function (response) {
    console.log(response);
    });
    ?>
    
    Login or Signup to reply.
  3. Pass PHP variable to SCRIPT by echo

    <?php
    
    $data_to_pass = //Your Dynamic data
    
    ?>
    
    <script>
    
        var settings = {
            "url": "MY_URL_TO_CREATE_USER_ACCOUNT",
            "method": "POST",
            "timeout": 0,
            "headers": {
                "external-token": "MY_TOKEN",
                "Content-Type": ["application/json", "text/plain"]
            },
            "data": <?php echo json_encode($data_to_pass); ?>;
        }
    
        jQuery.ajax(settings).done(function (response) {
           console.log(response);
        });    
    
    <script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search