2

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"

user1286956
  • 277
  • 3
  • 19
  • please check this example link [https://stackoverflow.com/questions/5004233/jquery-ajax-post-example-with-php](https://stackoverflow.com/questions/5004233/jquery-ajax-post-example-with-php) – Shital Marakana Oct 30 '17 at 07:42

2 Answers2

1

Your "name" is DOM object. To get value use:

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

You now submit not a string, but Object and this may be the reason why it fails.

Lukas Liesis
  • 24,652
  • 10
  • 111
  • 109
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);
  }
 });
apelidoko
  • 782
  • 1
  • 7
  • 23