-2

I have a phtml file. In file i have written some html in which there are some inputs and a button. In javascript i am validating the inputs and then posting using jquery like that

url = document.URL;    
$.post(url, { name: "John", time: "2pm" } );

Then in the same page i have written some php to get the data like that,

<?php
if(isset($_POST['name'])) {
    $name = $_POST["name"];
    $time = $_POST["time"];
}
?>

Am i doing right?

MJQ
  • 1,778
  • 6
  • 34
  • 60

1 Answers1

3

This is a method to make AJAX request to server and sending POST data asynchronously, So you can just have a look to the following code:

var url = document.location.href;

$.post(url,{name: "John", time: "2pm"},function(data){
  alert(data);
});

and on the server side :

<?php
if(isset($_POST['name'])) {
 if(!empty($_POST['name']))
 {
    $name = $_POST["name"];
 }
 else
 {
    $name = FALSE;
 } 
}

if(isset($_POST['time'])) {
 if(!empty($_POST['time']))
 {
    $time = $_POST["time"];
 }
 else
 {
    $time = FALSE;
 } 
}

if($name && $time)
{
  echo "SUCCESS";
}
else
{
   echo "FAILED";
}

?>

So this code basically post the data on the server and data is also validated at server if both the field reach the server successfully then you will get an alert showing SUCCESS otherwise FAILED.

You can test this code accordingly to see the output.

theCodeMachine
  • 1,681
  • 14
  • 11