1

Hi I am very new to JavaScript, looking for some help. I have a form, shown below. When the user gives input and clicks submit, I want to call a php file (shown below also) to be invoked and return a hello. Here is the code I have tried, though it is not working as intended.

 <html>
<head>
 <script type='text/javascript' src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
</head>
<body>
<form>
<input id="name-typed" type="text"  />
<input id="name-submit" type="submit" value="submit" onclick="post()"/>
</form>
<div id="result"></div>
</body>
<script>
function post() {
 var hname = $('input#name-typed').val();
 $.post('dat.php',{name: hname},function(data) {
$('div#result').html(data);
});
  }
</script>
</html>

The PHP file dat.php looks like this: <?php echo "hello";?>

As in my first paragraph, can anyone suggest any changes I should make?

2
  • 1
    you need to prevent form to be submited. So in your case, use as input type button Commented Feb 6, 2016 at 16:08
  • My humble opinion, use of the onclick attribute is unnecessary. Please refer to: en.wikipedia.org/wiki/Unobtrusive_JavaScript Commented Feb 7, 2016 at 15:45

2 Answers 2

1

Try this:

you can change dat.php to say:

<?php

$name = $_POST['name'];
echo "Hello ".$name;

?>

And then your html file would be:

Notice that the button type is changed to a normal button so that it just execute the function rather than submitting the form.

<html>
<head>
 <script type='text/javascript' src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
</head>
<body>
<form>
<input id="name-typed" type="text"  />
<button type="button" onclick="post()">Submit</button>
</form>
<div id="result"></div>
</body>
<script>
function post() {
  $.ajax({
         type: "POST",
        url: "dat.php",
        data: { name: $('#name-typed').val()
             },
        success: function(response) {

                $('#result').html(response);
       }
    });
}

</script>
</html>
Sign up to request clarification or add additional context in comments.

3 Comments

thanks you very much both the files seem to be working fine individually but when i give some input and run this is how it appears localhost:82/hello/index.php? and nothing changes
check my most recent edit just so you have the correct <button>. And you are welcome
excellent, please accept the answer, and welcome to stack overflow.
1

I haven't test but something like this:

$('form').submit(function(){
post()
return false;//block the reload of the page
})

In fact I think you just forget the return false. remvove the onclick if you use my answer

1 Comment

Better example, because of the use of unobtrusive javascript, in my opinion.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.