Here is the code:
<script type="text/javascript">
$.ajaxSetup ({
cache: false
});
var ajax_load = "<img src='load.gif' alt='Loading...' />";
$('#create').submit(function() {
$("#result").html(ajax_load);
$.get("actions/create.php", { url: longform },
function(data){
$('#result').html(data);
});
);
});
</script>
But all that happens is the URL in the address bar changes to:
http://domain.com/?longform=http://www.google.com/&submit=Submit
The form and result div:
<form name="create" action="" id="create">
<input type="text" name="longform" /> <input type="submit" name="submit" value="Submit" />
</form>
<div id="result">
results go here
</div>
Do I need to have the ajax code in the head section? Or does that not matter..
UPDATE:
The code on my page now looks like this:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<scrip开发者_开发问答t type="text/javascript">
$.ajaxSetup ({
cache: false
});
var ajax_load = "<img src='img/load.gif' alt='loading...' />";
$('#create').submit(function() {
event.preventDefault();
$("#result").html(ajax_load);
$.get("actions/create.php", { url: longform },
function(data){
$('#result').html(data);
});
);
});
</script>
</head>
<body>
<form name="create" action="" id="create">
<input type="text" name="longform" /> <input type="submit" name="submit" value="Shorten" />
</form>
<div id="result">
123
</div>
Still doesnt work. actions/create.php simply echos a foobar string to test it out.
UPDATE:
I have also tried this:
$('#create').submit(function() {
var formdata = $(this).serialize();
$.ajax({
url: 'actions/create.php',
data: formdata,
success: function(responseText){
$('#result').html(responseText);
}
});
return false;
});
But it also doesnt work.. could something in my htaccess be messing with it?
The submit
event doesn't happen instead of submitting but before it, thus your form submits normally after the JavaScript is executed. You need to cancel the normal submitting by either returning false
from the event handler:
$('#create').submit(function() {
$("#result").html(ajax_load);
$.get("actions/create.php", { url: longform },
function(data){
$('#result').html(data);
});
);
return false;
});
Alternatively you can call preventDefault
. See http://api.jquery.com/event.preventDefault/
Your
function(data){
$('#result').html(data);
});
should be
function(data){
$('#result').html(data);
}
and you need to prevent the default behavior of your form submit action (submitting the form via POST):
$('#create').submit(function() {
// ...
return false;
});
You can (additionally) take a look at jQuery's .load()
-method, which does exactly what you are doing, but shorter. The whole thing would look like this:
$('#create').submit(function() {
$("#result").load("actions/create.php", { url: longform });
return false;
});
Ok, it worked once I put all the jQuery BELOW the form and results div.. how tedious.
remove the action attribute from the form tag
精彩评论