Reputation: 7955
I want to submit my form with AJAX. I wrote a function for triggering this with pushing the button:
function putUser() {
$('button#putUser').on('click', function() {
var user = $('input#user').val(),
amount = $('input#amount').val(),
what = $('input#amount').val(),
country = $('input#country').val(),
platform = $('input#platform').val(),
formUrl = $('form#sendUser').attr('action');
var data = {
user: user,
amount: amount,
what: what,
country: country,
platform: platform
}
$.post(formUrl, $('#sendUser').serialize(), function() {
alert('test');
}).done(function() { alert('done')})
return false;
})
}
This theoretically works, because I'm getting done
alert. But no data is being submitted. What's wrong? My SQL statement works just fine.
My php code:
if(isset($_POST['putUser'])) {
$user = $_POST['user'];
$amount = $_POST['amount'];
$what = $_POST['what'];
$country = $_POST['country'];
$platform = $_POST['platform'];
$query = mysql_query('INSERT INTO sells (id, user, amount, what, country, platform) '
. 'VALUES (NULL , "' . mysql_real_escape_string($user) . '", "' . mysql_real_escape_string($amount) . '", "' . mysql_real_escape_string($what) . '", "' . mysql_real_escape_string($contry) . '", "' . mysql_real_escape_string($platform) . '")');
if($query) {
echo 'ok';
} else {
die(mysql_error());
}
}
Upvotes: 0
Views: 98
Reputation: 916
It doesn't look like you're actually sending the data you want to submit.
Note that $('#sendUser').serialize()
has been changed to your data
object. And that putUser
has been added to data
so that the server side code recognizes it.
I think you want this:
function putUser() {
$('button#putUser').on('click', function() {
var user = $('input#user').val(),
amount = $('input#amount').val(),
what = $('input#amount').val(),
country = $('input#country').val(),
platform = $('input#platform').val(),
formUrl = $('form#sendUser').attr('action');
var data = {
putUser: true,
user: user,
amount: amount,
what: what,
country: country,
platform: platform
}
$.post(formUrl, data, function() {
alert('test');
}).done(function() { alert('done')})
return false;
})
}
Upvotes: 0
Reputation: 860
What is $('#sendUser').serialize()
? is that a form you built you data
of?
EDIT: Try dataType 'json' for post - http://api.jquery.com/jQuery.post/
Upvotes: 1
Reputation: 95066
I would change putUser param to a get param.
<form action="sendUser.php?putUser">
php
if(isset($_POST['putUser'])) {
js
function putUser() {
$('#sendUser').on('submit', function() {
var formUrl = $(this).attr('action');
$.post(formUrl, $(this).serialize(), function() {
alert('test');
}).done(function() { alert('done')})
return false;
})
}
Also changed to a submit event rather than click, which allowed me to further use this
rather than a selector.
Upvotes: 2