2

I am trying to submit this form without refreshing the page. I'm using jquery; upon submit the page still refreshes.

$(function(){ $('#submit').click(function(){ $('#container').append('loading'); var sthis = $('#sthis').val(); $.ajax({ url: 'f.php' , type: 'POST', data: 'sthis: ' + sthis, success: function(result){ $('#container').append('<p>' + result + '</p>') } }); return false; }); }); 

html page (f.php)

<div id="container"> <form method="post" action="f.php"> something<input name="sthis" type="text" /> <input type="submit" value="submit" id="#submit" /> </form> </div> 

php page

<?php if(isset($_POST['sthis'])){ $sthis = $_POST['sthis']; if(empty($sthis)) { echo 'put something in this box'; } else echo 'ready'; } ?> 

5 Answers 5

3

your problem is here id="#submit" should be id="submit", that should work.

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

1 Comment

won't this reload the f.php page after ajax response is received, due to action="f.php"?
3

Change this:

<input type="submit" value="submit" id="#submit" /> 

To this:

<input type="button" value="submit" id="#submit" /> 

Then hook up an event handler that calls your ajax function, instead of submitting the form.

2 Comments

Problem there is if the user hits "enter" in the input box, they will still trigger the form submit event.
agreed, if the form submits, the page will refresh, which could be caused, among other things, but an enter in a text field
1

The easiest thing to do in this case is change your form tag like so:

<form method="post" action="f.php" onSubmit="return false;"> 

2 Comments

when i do this the form does nothing, even if the field is empty
Something else must be going on, then. It shouldn't have any affect on your jquery ajax code. Are you getting a JS error?
1

in your form tag, just add an onsubmit="return false". That will prevent the form from submitting it's request and refreshing your page. The click event on that button will still work so you can control everything via javascript. Here's more info:

http://www.htmlcodetutorial.com/forms/_FORM_onSubmit.html

1 Comment

when i do this the form does nothing, even if the field is empty
0

There is still something wrong.

First: in f.php:

 <input name="sthis" type="text" /> 

Change it to :

 <input id="sthis" type="text" /> 

Second: the data format in .ajax is wrong:

 data: 'sthis: ' + sthis, 

Change it to:

 data: {sthis: sthis}, 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.