0

I'm trying to figure out how I can send a POST request to an outside API from inside the PHP file that I'm also POSTing a form submission to to. Essentially when the PHP file receives the POST from my page, it should send the username and password it received to the outside API and then return that response to my JavaScript so I can read it and use that information. I am doing this because this request needs to go to an outside API that I have no control over, so I would normally get a Cross-Origin error.

This is my PHP. It receives a POST request from my JavaScript upon form submission. I need it to pass the form submission to an API at www.sample.com/api?hwerywer=funcName

<?php
if (is_ajax()) {
if (isset($_POST["action"]) && !empty($_POST["action"])) { //Checks if action value exists
    $action = $_POST["action"];
    switch($action) { //Switch case for value of action
    case "test": test_function(); break;
    }
}
}

//Function to check if the request is an AJAX request
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}

function test_function(){
$return = $_POST;


$return["json"] = json_encode($return);
echo json_encode($return);
}
?>

I have this form in an HTML page:

<form action="hello.php" class="js-ajax-php-json" method="post" accept-charset="utf-8">
    <input type="text" name="username" value="" placeholder="username" />
    <input type="text" name="password" value="" placeholder="password" />
    <input type="submit" name="submit" value="Submit form"  />
</form>

When it gets submitted this JavaScript runs:

$(".js-ajax-php-json").submit(function(){
    var data = {
    "action": "test"
    };
    data = $(this).serialize() + "&" + $.param(data);
    $.ajax({
    type: "POST",
    dataType: "json",
    url: "hello.php",
    data: data,
    success: function(data) {
        // manipulate response data
        // $(".the-return").html(
        // "First Value: " + data["username"] + "<br />Second Value: " + data["password"] + "<br />JSON: " + data["json"]
        // );

        alert("Form submitted successfully.\nReturned json: " + data["json"]);
    }
    });
    return false;
});
Ryan
  • 252
  • 3
  • 15
  • 1
    Post to a php file (with AJAX), then use CURL to connect to the API, get the results and return to the AJAX callback. CURL is better here because it will hide the API call from the client because it's server to server. – ArtisticPhoenix Oct 19 '18 at 05:36
  • Possible duplicate of [PHP + curl, HTTP POST sample code?](https://stackoverflow.com/questions/2138527/php-curl-http-post-sample-code) – Nigel Ren Oct 19 '18 at 05:59

0 Answers0