Reputation: 9855
Im having trouble trying to post data correctly using jQuery/AJAX
I have the following...
<script type="text/javascript">
function notifyPPAComplete() {
$.ajax(
{
type: "POST",
url: "PsychometricTest.aspx/UpdateDB",
data: {'3'},
dataType: json,
success: success,
contentType: application/json
});
}
$.post('PsychometricTest.aspx/UpdateDB', function(data) {
alert ('success');
});
</script>
I dont seem to receive my alert after the post neither, can anybody see an obvious problem?
Upvotes: 0
Views: 412
Reputation: 1039398
data: {'3'}
That's an invalid javascript literal. You may try like this:
data: JSON.stringify({ model: { foo: '3' } })
Notice the usage of the JSON.stringify
method which serializes a javascript literal into a JSON string. It's natively built into modern browsers. And if you need to support legacy browsers you vould include the json2.js script.
Also contentType: application/json
is pretty invalid javascript. Should be:
contentType: 'application/json'
Also: dataType: json
is invalid. Should be dataType: 'json'
.
So at the end of the day:
<script type="text/javascript">
function notifyPPAComplete() {
$.ajax({
type: "POST",
url: "PsychometricTest.aspx/UpdateDB",
data: JSON.stringify({ model: { foo: '3' } }),
dataType: 'json',
success: function(result) {
},
contentType: 'application/json'
});
}
</script>
would successfully post to:
[WebMethod]
public static void UpdateDB(MyModel model)
{
...
}
where MyModel:
public class MyModel
{
public string Foo { get; set; }
}
Upvotes: 3
Reputation: 14856
In your snippet notifyPPAComplete()
never gets called and $.post('PsychometricTest.aspx/UpdateDB
doesn't post any data.
Also try using Firebug in Firefox for better AJAX debugging.
It should be:
$.post('PsychometricTest.aspx/UpdateDB', { name: "John", time: "2pm" }, function(data) {
alert ('success');
});
where { name: "John", time: "2pm" }
is the data you want to post.
Upvotes: 0
Reputation: 1805
<script type="text/javascript">
function notifyPPAComplete() {
$.ajax(
{
type: "POST",
url: PsychometricTest.aspx/UpdateDB,
data: {'3'},
dataType: json,
success: function(success){a = success},<-- here use the function()
contentType: application/json
});
}
$.post('PsychometricTest.aspx/UpdateDB', function(data) {
alert (data); <-- here use the variable not the literal string
});
</script>
and by the way you have $.post and $.ajax ??? is this a homework ?
Upvotes: 0