简体   繁体   中英

want to use JavaScript and Ajax to send to a php script using curl to connect to a remote server

Please i want to use JavaScript and Ajax to send to a php script that sends to a remote server using Curl. But the first time i will send to this php script, i will get a result, after the first time i will no longer get a result, except i refresh the page. I want to do this without refreshing the page. that is, i want to send to the remote server so many times and get a result.

function go() {
    var xmlhttp = new XMLHttpRequest();
    var url = "url.php";
    var text = document.getElementById("text").value;
    var name = document.getElementById("name").value;
    var email = document.getElementById("email").value;
    var variables = "text="+text+"&name="+name+"&email="+email;

    xmlhttp.open("POST", url, true);variables in the request
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

    xmlhttp.onreadystatechange = function() {
        if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            var data = xmlhttp.responseText;
            document.getElementById("flash-message").innerHTML = data;
        }
    }
    xmlhttp.send(variables);
}

my php script

<?php
  if(!empty($_POST['text']) && !empty($_POST['name']) && !empty($_POST['email']) {
  $url = "http://url.com/api";
  $xmlString = "
    <profile>
      <names>
        <firstname>john</firstname>
        <lastname>doe</lastname>
      </names>
    </profile>";
    $fields = "XML=" . urlencode($xmlString);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    echo $response = curl_exec($ch);
    curl_close($ch);
  }else {
   echo "Please fill in those fields";
  }
?>

As long as you are able to send requests you could get response from the php script.

Check you are sending requests from the browser net panel using firebug

In js code see calling go() function by logging some help text to console panel using console.log('calling go function')

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