This is my first post and I have the feeling that this is something stupid. I have already been to this question: https://stackoverflow.com/questions/511947?tab=newest#tab-top although that still did not really help.
I have 3 PHP pages. The main page is the one with all the jQuery on it:
<body>
<script type="text/javascript" src="includes/jquery-1.4.2.js"></script>
<script type="text/javascript">
$(document).ready(function() {
// for each trade, load the current comparisons
<?php
foreach ($trades as $trade) {
?>
$("#<?php echo $trade; ?>Div").load("functions/loadPriceSurveyComparisons.php", {
trade: "<?php echo $trade; ?>"
});
$("#addComp<?php echo $trade; ?>").click(function() {
$.post("functions/addP开发者_开发百科riceSurveyComparisons.php", {
trade: "<?php echo $trade; ?>",
alb: $("#albProd<?php echo $trade; ?>").val(),
comp: $("#compProd<?php echo $trade; ?>").val()
}, function(data) {
$("#<?php echo $trade; ?>Div").load("functions/loadPriceSurveyComparisons.php", {
trade: "<?php echo $trade; ?>"
});
}, "xml");
});
<?php
}
?>
});
</script>
This page basically loads a list of items into div elements on load. $.load is used for this. The $.load has a callback which assigns click event handlers to 3 different HTML elements (hence the PHP echo of $trade).
These click handlers basically do an AJAX request using $.post. The page being posted to is as follows:
<?php
header("Content-type: text/xml");
include("../includes/db_connection.php");
$sql = "INSERT INTO pricesurvey_compare (alb_product_id, comp_product_id, trade)
VALUES (".$_POST['alb'].", ".$_POST['comp'].", '".$_POST['trade']."')";
mysql_query($sql);
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
?>
<data>
<trade><?php echo $_POST['trade']; ?></trade>
<alb><?php echo $_POST['alb']; ?></alb>
<comp><?php echo $_POST['comp']; ?></comp>
<errors><?php echo mysql_error(); ?></errors>
</data>
This jquery.post() request for some reason refreshes the page in Firefox and I'm not seeing any errors generated. I can't even view the request with firebug in the Net tab as when the page refreshes this is cleared. What's also interesting is that no javascript at all is appearing in the script tab? But that's another headache I'm not gonna pay attention to right now.
Please note that I am pretty much a noob when it comes to jQuery.
Don't forget to add e.preventDefault()
$("#addComp<?php echo $trade; ?>").click(function(e) {
e.preventDefault();
// ...
}
Try adding
return false;
right after the call to $.post(...)
in your "click" handler. I don't know exactly what those "addComp" elements are, but if they're elements that cause the form to be submitted then your problem is that the form is being posted twice: once by your "click" handler, and once by ordinary browser form functionality.
精彩评论