Ankit Ankit - 3 months ago 13
jQuery Question

How to print this value using AJAX JQUERY on HTML

HTML

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">

$(document).ready(function(){
$("#but").click(function(){

$.ajax({
url: "action.php",
type: "POST",
dataType: "text",
success: On_success,
error: On_error
});

function On_success(response){
alert(response);
//$("#show").html(response);
}

function On_error(data){
console.log(data);
}
});
});

</script>
</head>
<body>

<form action="action.php" method="post">
<input type="text" name="mine">
<input type="submit" id="but">
</form>
<p id="show">HI</p>
</body>
</html>


PHP

<?php

$name = $_POST['mine'];

echo $name;

?>


There is a input box, a submit button and a para tag on HTML
When I input a value and click the button.....the value is passed to PHP file...where the value is echoed.

Now using AJAX I fetch the response..(which should be value from the input box)

but the response I receive is :

Image of response

and then it goes on PHP page and displayed the input box value.

How should I print the value using AJAX response in the para tag?

Thanks in advance
Please help

Answer

Several things

  1. do not submit the form if you want to stay on the page
  2. move the functions you want to call later to a scope where they are available or have them as anonymous functions: success: function() {...}
  3. send the data from the form

Like this:

$(function(){
  $("form").on("submit",function(e){
    e.preventDefault(); // or make the button it type="button:
    var data = $(this).serialize();
    $.ajax({
      url: "action.php", // or $(this).attr("action"),
      type: "POST",
      data: data,
      success: On_success,
      error: On_error
    });
  });
});
function On_success(response){
    $("#show").html(response);
}

function On_error(data){
   console.log(data);
}