Reputation: 137
REFINED QUESTION
My JS code for live form and live form submit...
$('#addHotlink').click(function() {
$('body').after('<div id="lightBox" style="height: ' + htmlHeight + 'px;"><div><h3>Choose a name for your hotlink:<img id="lightBoxClose" src="http://www.example.com/images/closedAccordion.png" height="17" width="17" alt="" title="Close this box" /></h3><form id="addHotlinkForm" action="#" method="post" autocomplete="off"><input id="hotlinkName" type="text" maxlength="15" /><input class="submit" type="submit" value="Add Hotlink" /></form></div></div>');
$('#lightBox').hide().fadeIn('fast');
return false;
});
$('#addHotlinkForm').live('submit', function(event) {
event.preventDefault();
var hotlinkName = $('#hotlinkName').val();
if (hotlinkName.length > 0) {
$.ajax({data: {hotlinkName: hotlinkName, hotlinkURL: pageURL},
error: function() {
alert('Error');
},
success: function() {
alert('Yay');
}
});
}
});
My ajax.php...
if (isset($_REQUEST['hotlinkName']) && isset($_REQUEST['hotlinkURL'])) {
$q = $dbc -> prepare("INSERT INTO hotlinks (id, hotlinkName, hotlinkURL) VALUES (?, ?, ?)");
$q -> execute(array($_SESSION['id'], $_REQUEST['hotlinkName'], $_REQUEST['hotlinkURL']));
}
I have my ajax settings set up like so before the ajax call...
$.ajaxSetup({
type: 'GET',
url: 'http://www.example.com/ajax',
dataType: 'json'
});
The ajax call doesn't succeed or get an error! In chrome console I get this:
Uncaught TypeError: Illegal Invocation
Upvotes: 0
Views: 441
Reputation: 5150
live()
methods are attached to a parent component, high up in the DOM hierarchy. Your default behavior is triggered long before the live()
function is even reached because the live()
is triggered after a long bubble up process.
The only real solution is to ensure that the default behavior is a no-op. You can do this by changing your form's href to javascript:void(0);
.
Update
Your code triggers the alert at this JSFiddle: http://jsfiddle.net/vD2pz/ The only other thing I can think of is that your addHotLink
creates invalid code by repeatedly creating forms with duplicate ID fields, which is invalid.
Upvotes: 1
Reputation: 8941
Try using preventDefault()
:
$('#addHotlinkForm').live('submit', function(event) { // add 'event' here
var hotlinkName = $('#hotlinkName').val();
if (hotlinkName.length == 0) {
return false;
}
else {
$.ajax({data: {hotlinkName: hotlinkName, hotlinkURL: pageURL},
success: function(response) {
alert('Yay!');
}
});
}
event.preventDefault(); // and add in this line
return false;
});
Upvotes: 1