user3580499
user3580499

Reputation: 1

How do i get to show my php response on my page without refreshing with ajax?

I have this form

    <form action="send.php" method="post">
          <div class="col-md-12">
            <div class="input-group input-group-lg">
              <span class="input-group-addon" id="sizing-addon1"><i class="fa fa-credit-card"></i></span>

             <input id="nfc" name="nfc" type="text" required class="form-control" placeholder="Wristband UID will appear here...." aria-describedby="sizing-addon1">
             </div>

<br>
              <div class="input-group input-group-lg">
                  <span class="input-group-addon" id="sizing-addon1"><i class="fa fa-phone"></i></span>
                   <input id="phone" name="phone" type="text" value="254" required class="form-control" placeholder="Registered Phone Number" aria-describedby="sizing-addon1">
             </div>  

<br>
          <button type="submit" class="btn btn-color btn-lg">OK, Im Done</button>
</div>
            <div id="alert"></div>
</form>

I would like to process the input via this php script:

<?php 
$nfc = $_POST["nfc"];
$phone = $_POST["phone"];


$post = [
'nfc' => $nfc,
//'password' => '9907',
'phone' => $phone,

];

header( "Content-Type: application/json" );

$ch = curl_init('myAPIUrl');//posts input to my api and i get a response

curl_setopt($ch, CURLOPT_POSTFIELDS, $post);


curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$server_output = curl_exec ($ch);

curl_close ($ch);

header( "refresh:1400;url=http://www.swype.co.ke/counter/index.html" );

var_dump($server_output);
?>

and show the form response in the div id "ALERT" on the same page. My API URL is an api whose parameters are the input fields. I get the api response as shown below.

string(121) "{"idUser":42,"rfid":"4534543","username":"","transactionStatus":"NFC tag has been updated successfully","statusCode":200}"

Upvotes: 0

Views: 50

Answers (1)

Rebecca Close
Rebecca Close

Reputation: 940

In order to process the input via PHP, you need to send the form data to the server. In order to display an alert with the response from the server, you need to either submit the form (thereby refreshing the page) or use AJAX to submit form data and wait for a response.


Right now you're using PHP to do something that you could potentially do with AJAX. Try something like this:

$( "form" ).submit(function( event ) {
  // request json with 
  $.getJSON( "http://www.swype.co.ke/counter/index.html", 
    // whatever data you want to send from your form
    { name: "John", time: "2pm" },
    function( data ) {
      // show the result of processing the data
      alert(data);
    }
  );

  // prevent form from refreshing the page
  event.preventDefault();
});

Upvotes: 1

Related Questions