Reputation: 9855
Im trying to update my DB using AJAX and PHP. I'm sure everything is right only my page refreshes and nothings inserted into my table.
HTML
<form id="salary-upd">
<input type="text" class="defaultText" id="monthly-income" name="monthly-income" title="What is your salary?">
<input type="submit" class="salary-upd-submit">
</form>
<div></div>
AJAX
// UPDATE INCOME
$(".salary-upd-submit").click(function() {
var elem = $(this);
$.post("update_salary.php", elem.parent("#salary-upd").serialize(), function(data) {
elem.next("div").html(data);
});
});
PHP
$uid = $_SESSION['oauth_id'];
$monthly_income = $_POST['monthly-income'];
#update Record
$query = mysql_query("SET `income` (user_id, monthly_income) VALUES ($uid, '$monthly_income')") or die(mysql_error());
tried to update my PHP as I thought it may be that...
$query = mysql_query("UPDATE `income` SET (user_id, monthly_income) VALUES ($uid, '$monthly_income')") or die(mysql_error());
Upvotes: 2
Views: 953
Reputation: 425371
I think the others will fix your JS-side issues, but the query you are passing to MySQL
in your script won't parse.
Try using something like this:
$sanitized_monthly_income = mysql_real_escape_string($_POST['monthly-income']);
mysql_query("INSERT INTO income (user_id, monthly_income) VALUES ('$uid', '$sanitized_monthly_income') ON DUPLICATE KEY UPDATE monthly_income = VALUES(monthly_income)");
Upvotes: 1
Reputation: 91734
To avoid the page-refresh, I would recommend attaching the action to the form submit handler and prevent the default submit event:
$("#salary-upd").on("submit", function(event) {
event.preventDefault();
var elem = $(this);
$.post("update_salary.php", $(this).serialize(), function(data) {
elem.next("div").html(data);
});
});
Edit: For older versions of jQuery, the first line would be:
$("#salary-upd").submit(function(event) {
About the php:
Upvotes: 1
Reputation: 218732
Are you clicking on the button before the dom finishes loading ? I would wrap the functionality in document ready to make sure it executes only after the dom finishes loading.
add preventDefault to prevent the default form submit behaviour. Other wise you may not be able to notice that it is reloaded via ajax because the entire page will be submited.
$(function(){
$(".salary-upd-submit").click(function(e) {
e.preventDefault(); //prevent default submit behavior.
var elem = $(this);
$.post("update_salary.php", elem.parent("#salary-upd").serialize(), function(data) {
elem.next("div").html(data);
});
});
});
Upvotes: 0
Reputation: 2747
Try this:
$(".salary-upd-submit").click(function (e) {
e.preventDefault();
var elem = $(this);
$.post("update_salary.php", elem.parent("#salary-upd").serialize(), function (data) {
elem.next("div").html(data);
});
});
Upvotes: 0