0

I'm trying message application. My goal is get sender id and receiver id with a click on one button. After then post this datas with ajax or ajax(json) to php in same page.

I will use the incoming data in php with mysql_query. I tryed many examples. But never get result. My example code at below.

Little Note: Success alert comes but doesn't print any data on screen.

<html>
<head>
  <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
  <body>
    <button type="button" onclick="myFunc()">Get ID</button>
    <script>
    function myFunc()
    {
    var id = 'example';
    jQuery.ajax({
        url:'index.php',
        type: "POST",
        data: {'name':id},
        success: function(data)
            {
               alert("success");
            }
    });
    };
    </script>
   <?php
   if(isset($_POST['name']))
   {
      $value = $_POST['name'];
      echo $value;
   }
   else
   {
      echo "don't work.";
   }
   ?>
  </body>
</html>

1 Answer 1

1

<?php
   if(isset($_POST['name']))
   {
      echo json_encode(array(
        'value' => $_POST['name']
      ));
      exit();
   }
?>

<html>
<head>
  <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
  <body>
    <button type="button" onclick="myFunc()">Get ID</button>
    <script>
    function myFunc()
    {
    var id = 'example';
    jQuery.ajax({
        url:'index.php',
        type: "POST",
        data: {'name':id},
        dataType : 'json', 
        success: function(data)
            {
               alert("success");
            }
    });
    };
    </script>

  </body>
</html>

Sign up to request clarification or add additional context in comments.

1 Comment

thanks, but i tried before this way. This code doesn't show any data on page. Success alert comes but doesn't print data on screen.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.