简体   繁体   中英

Sending data via jQuery Ajax as JSON to PHP Rest API with cURL

I need to send some data to a REST API and include a custom header value. I try and echo out the data I am sending via the cURL script, but I get a blank page. Here is my HTML

<form id="RestData" action=Processor.php" method="POST">
    <ul>
        <li>
            <input type="text" id="email" name="email">
        </li>
        <li>
            <input type="submit" value="Update User" id="">
        </li>
    </ul>
</form>

my jQuery:

$(function(){
    $('#RestData').validate({
        errorPlacement: function(error, element) {},
        submitHandler: function(form) {
            $.ajax({
                type:$('#RestData').attr('method'),
                url: form.action,
                data: {
                    email = $('#email').val();
                },
                beforeSend: function(data){
                    console.log(data);
                },
                success: function(data){
                    console.log(data);
                    if(data.type == "error") {
                        //error handling
                    } else if(data.type == "success"){
                        //success handling
                    } 
                }
            });
                return false;
        },
        rules: {
            email: {
                required:true,
                email:true
            }
        }
    });
});

At this point, I am getting double quotes around my json array when I echo it out via the PHP processor

<?php
    $email = $_POST['email'];
    $expired = NULL;
    $funded = TRUE;

    $data = array(
        "email" => $email,
        "expired" => $expired,
        "funded" => $funded
    );
    echo json_encode($data);
?>

like this -> {"email":"test@test.com","expired":null,"funded":true} I don't know if that will be an issue or not, any thoughts on how to remove if necessary?

With my final cURL code, nothing happens - blank screen and nothing in the network panel for a response.

<?php
    $email = $_POST['email'];
    $expired = NULL;
    $funded = TRUE;

    $data = array(
        "email" => $email,
        "expired" => $expired,
        "funded" => $funded
    );

    $url = 'https://rest.api';

    $json_string = json_encode($data);

    $headers = array (
        "Content-Type: application/json; charset=utf-8",
        "Content-Length: " .strlen($json_string),
        "Authorization: Bearer long token here"    
    );

    $channel = curl_init($url);
    curl_setopt($channel, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($channel, CURLOPT_CUSTOMREQUEST, "PUT");
    curl_setopt($channel, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($channel, CURLOPT_POSTFIELDS, $json_string);
    curl_setopt($channel, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($channel, CURLOPT_CONNECTTIMEOUT, 10);

    curl_exec($channel);
    $statusCode = curl_getInfo($channel, CURLINFO_HTTP_CODE);
    curl_close($channel);    
    return $statusCode;
    echo $json_string;
?>

This is a little outside of my wheelhouse, I use cURL a lot, just not to a rest API. I know I should be getting a response back and am trying to echo it out on the page for debugging purposes, but I just get a blank page.

You are not getting the cURL response in a variable.

Secondly, you are doing echo after return statement, which will never execute.

<?php
    $email = $_POST['email'];
    $expired = NULL;
    $funded = TRUE;

    $data = array(
        "email" => $email,
        "expired" => $expired,
        "funded" => $funded
    );

    $url = 'https://rest.api';

    $json_string = json_encode($data);

    $headers = array (
        "Content-Type: application/json; charset=utf-8",
        "Content-Length: " .strlen($json_string),
        "Authorization: Bearer long token here"    
    );

    $channel = curl_init($url);
    curl_setopt($channel, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($channel, CURLOPT_CUSTOMREQUEST, "PUT");
    curl_setopt($channel, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($channel, CURLOPT_POSTFIELDS, $json_string);
    curl_setopt($channel, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($channel, CURLOPT_CONNECTTIMEOUT, 10);

    $response = curl_exec($channel);
    $statusCode = curl_getInfo($channel, CURLINFO_HTTP_CODE);
    curl_close($channel);

    http_response_code($statusCode);
    if ( $statusCode != 200 ){
       echo "Status code: {$statusCode} \n".curl_error($channel);
    } else {
       echo $response;
    }
?>

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