jQuery Ajax Submit Post not getting success message back

The code works on until I reach the action.php where I post my input. The issue is that the Post never reaches the action.php and all I get is a blank variable.

using: https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js

<script type="text/javascript">

function submitdata()
{
 var name=document.getElementById('name');

 $.ajax({
  type: 'post',
  url: 'action.php',
  data: {
   'name':name
  },
  cache:false,
  success: function (data) {
   $('#msg').html(data);
  }
 });

 return false;
}

</script>

<form onsubmit="return submitdata();">
    <input type="text" name="name">
    <input type="submit" value="Check">
</form>

<p id="msg"></p>

action.php:

<?php
$name=$_POST['name'];
echo "Response: ".$name;
?>

EDIT: Fixed it by adding:

var name=document.getElementById('name').value;

and

input type="text" id="name" instead of name="name"

Answers 1

  • Try to add the dataType on your ajax request make it 'text'

     $.ajax({
      type: 'post',
      url: 'action.php',
      dataType: 'text',
      data: {
       'name':name
      },
      cache:false,
      success: function (data) {
       $('#msg').html(data);
      }
     });
    

Related Articles