Ajax firing success event but not getting to the web method - javascript

I'm using ajax to call a server side function. for some reason, the success is firing but it doesn't get to the function
here is the javascript
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
url: "Server.aspx/sendEmail",
data: { name: "foo", company: "bar", country: "foo", email: "bar", msg: "bla" },
async: false,
success: function (data) {
var a = 3;
},
error: function (a, b) {
alert("error");
var a = 43;
}
});
});
here is the c#
[WebMethod]
public static string sendEmail(string name, string company, string country, string email, string msg)
{
//somecode here
}
the data message(for some reason it is breaking)
<form method="post" action="./sendEmail?%7b%22name%22%3a%22foo%22%2c%22company%22%3a%22bar%22%2c%22country%22%3a%22foo%22%2c%22email%22%3a%22bar%22%2c%22msg%22%3a%22bla%22%7d" id="form1">
<div>
</div>
<input type="hidden" name="__VIEWSTATEGENERATOR" id="__VIEWSTATEGENERATOR" value="368A1591" />

Take the following points into account when you are calling an ASP.NET AJAX page methods:
To use ASP.NET AJAX page methods, you need to make a POST request. This is to prevent CSRF
Ensure that the contentType is set to application/json.
Use JSON.stringify to convert the JavaScript object into JSON text.
Your JS code could be something similar to this:
$(document).ready(function () {
var data = { name: "foo", company: "bar", country: "foo", email: "bar", msg: "bla" };
$.ajax({
url: "Server.aspx/sendEmail",
type: "POST",
data: JSON.stringify(data),
async: false,
contentType: 'application/json',
success: function (data) {
//Do something
},
error: function (xhr) {
alert('Request Status: ' + xhr.status
+ ' Status Text: ' + xhr.statusText
+ ' ' + xhr.responseText);
}
});
});
If it still doesn't work, check the statusText for the error.

Related

Sending Array Object Data in Javascript to ASP.NET Core Controller using AJAX ()

I've tried all other solutions pertaining to the problem, but still can't find what i'm missing for my code. Here's my AJAX() Code.
var group = JSON.stringify({ 'listofusers': listofusers });
console.log("listofusers : " + JSON.stringify({ 'listofusers': group }));
(Assuming I have my listofusers object ready, and yes i've checked the console and it has data inside.)
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: "POST",
url: url,
data: group,
success: function (data) {
console.log("output : " + JSON.stringify(data));
//doSend(JSON.stringify(data));
//writeToScreen(JSON.stringify(data));
},
error: function (data) {
console.log("error : " + JSON.stringify(data));
},
});
Here's my Server Side Controller.
[HttpPost]
public IActionResult GetMesssage(List<UserModel> listofusers)
{
var g = listofusers;
}
Just a simple fetch from the controller, so I could verify that the data from client side has really been sent.
I've tried the [FromBody] attribute, but still no luck in fetching the data from the server-side.
Here is a working demo like below:
1.Model:
public class UserModel
{
public int Id { get; set; }
public string Name { get; set; }
}
2.View(remove Content-type):
<script>
var listofusers = [
{ id: 1, name: 'aaa' },
{ id: 2, name: 'bbb' },
{ id: 3, name: 'ccc' }
];
var group = { 'listofusers': listofusers };
console.log(group);
$.ajax({
dataType: 'json',
type: "POST",
url: "/home/GetMesssage",
data: group,
success: function (data) {
console.log("output : " + JSON.stringify(data));
},
error: function (data) {
console.log("error : " + JSON.stringify(data));
},
});
</script>
3.Console.log(group):
4.Result:
Update:
Another way by using json:
1.View(change group from JSON.stringify({ 'listofusers': listofusers });
to JSON.stringify(listofusers);):
<script>
var listofusers = [
{ id: 1, name: 'aaa' },
{ id: 2, name: 'bbb' },
{ id: 3, name: 'ccc' }
];
var group = JSON.stringify(listofusers);
console.log(group);
$.ajax({
contentType:"application/json",
dataType: 'json',
type: "POST",
url: "/home/GetMesssage",
data: group,
success: function (data) {
console.log("output : " + JSON.stringify(data));
},
error: function (data) {
console.log("error : " + JSON.stringify(data));
},
});
</script>
2.Controller(add FromBody):
[HttpPost]
public IActionResult GetMesssage([FromBody]List<UserModel> listofusers)
{
//...
}
You can try this one.
First stringify the parameter that you want to pass:
$.ajax({
url: url,
type: "POST",
data: {
listofusers: JSON.stringify(listofusers),
},
success: function (data) {
},
error: function (error) {
}
});
Then in your controller:
[HttpPost]
public IActionResult GetMesssage(string listofusers)
{
var jsonModel = new JavaScriptSerializer().Deserialize<object>(listofusers); //replace this with your deserialization code
}
What we're doing here is passing your object as a string then deserializing it after receiving on the controller side.
Hope this helps.
I found the solution to my problem guys, but I just want a clarification that maybe there's a work around or another solution for this one.
I've studied the data passed by "JSON.stringify();" from AJAX() and it's somehow like this.
"[[{\"ID\":0,\"UserID\":1014,\"Level\":\"support\",\"Department\":\"\",\"Facility\":\"Talisay District Hospital\",\"Firstname\":\"Joseph\",\"Middlename\":\"John\",\"Lastname\":\"Jude\",\"LoginStatus\":false,\"IPAddress\":\"192.168.110.47:12347\"},{\"ID\":0,\"UserID\":1014,\"Level\":\"support\",\"Department\":\"\",\"Facility\":\"Talisay District Hospital\",\"Firstname\":\"Joseph\",\"Middlename\":\"John\",\"Lastname\":\"Jude\",\"LoginStatus\":false,\"IPAddress\":\"192.168.110.47:15870\"}]]"
to which I was wondering that if the JSON format is a factor in parsing the data from the controller side. (Which of course is stupid since there's only one JSON format. (or maybe there's another, if there is, can you please post some source for reference.))
so I tried Serializing a Dummy Data in my model in "JsonConvert.Serialize()" Method and the output JSON data is like this.
[{"ID":0,"UserID":1014,"Level":"support","Department":"","Facility":"Talisay District Hospital","Firstname":"Joseph","Middlename":"John","Lastname":"Jude","LoginStatus":false,"IPAddress":"192.168.110.47:12347"},{"ID":0,"UserID":1014,"Level":"support","Department":"","Facility":"Talisay District Hospital","Firstname":"Joseph","Middlename":"John","Lastname":"Jude","LoginStatus":false,"IPAddress":"192.168.110.47:16709"}]
and I tried sending the output JSON Data from JsonConvert.Serialize() Method to controller via AJAX() and it worked! And I feel so relieved right now as this problem was so frustrating already.
If there's something wrong with what I found, please respond with what might be wrong or correct. Thank you!

Get hold of json content that is being sent to Jquery

That's how I reach when I send some values that are specified in my input and therefore they need to send to a API.
When I try to send them to the monkey, my monkey tells me that nothing has been sent.
At my console.log(token), it tells me what data is available and I also agree that it all fits together. But the problem is just that it has to come over to my API.
function PayStripe() {
// Open Checkout with further options:
handler.open({
name: 'XXX ',
description: 'XX abonnement',
currency: "dkk",
amount: $('#HiddenPrice').val() * 100,
email: $('#Email').val()
});
};
// Close Checkout on page navigation:
$(window).on('popstate', function () {
handler.close();
});
var handler = StripeCheckout.configure({
key: 'pk_test_xxxx',
locale: 'auto',
token: function (token) {
token.subscriptionId = $('#SubscriptionId').val();
token.City = $('#City').val();
token.Postnr = $('#Postnr').val();
token.Mobil = $('#Mobil').val();
token.Adresse = $('#Adresse').val();
token.CVRVirksomhed = $('#CVRVirksomhed').val();
console.log(token.subscriptionId);
console.log(token);
$.ajax({
type: "POST",
url: "/api/Stripe",
contentType: "application/json",
data: token,
success: function (data) {
//window.location.href = '/Subscriptions/Succes';
alert(data + "Succes")
},
error: function (data) {
console.log(data + "Error");
},
dataType: 'json'
});
// You can access the token ID with `token.id`.
// Get the token ID to your server-side code for use.
}
});
Where the problem lies is that the API is by no means able to get informed information from jquery. so it's like it can not / will receive it.
[HttpPost]
[Route("api/Stripe")]
[Produces("application/json")]
public async Task<IActionResult> Post([FromForm] JObject token)
When I grab the token that I need for example. then I do this here:
var SubscriptionId = (int)token.GetValue("subscriptionId");
When you set contentType: "application/json", you need to stringify the data to json yourself
data: JSON.stringify(token),

Ajax POST don't work after button click

My problem is lack of action after pressing the button. Under the button hook AJAX function.
Please a hint where I have a bug // errors.
My code:
Controller:
[HttpPost]
public ActionResult InsertCodesToDB(string name)
{
cl.InsertCodesToDB(name);
fl.MoveCodeFileToAccept(name);
string response = "Test";
return Content(response, "application/json");
}
View / Button:
<input type="button" class="btn btn-success sendCodesToDB" value="Umieść kody w bazie" data-value="#item.Name"/>
View / Script:
<script>
$('.sendCodesToDB').on('click', function () {
var name = $(this).data("value");
$.ajax({
url: '/ActualCodes/InsertCodesToDB',
type: 'POST',
dataType: 'json',
cache: false,
data: JSON.stringify({ 'name': 'name' }),
success: function (response) {
#(ViewBag.MessageOK) = response;
},
error: function () {
onBegin;
}
});
});
function onBegin() {
$('#files').hide();
$('#insertFiles').hide();
$('#loading').show();
$('#lblSelectedProductName').text('Trwa umieszczanie kodów w bazie danych. Proszę czekać ...');
$('#ttt').show();
}
</script>
Thank you in advance for your help.
You seem to not be adding the on ready function for jQuery. Try adding it before your click action and closing it before your onBegin() function, like so:
<script>
// open here
$( document ).ready(function() {
$('.sendCodesToDB').on('click', function () {
var name = $(this).data("value");
$.ajax({
url: '/ActualCodes/InsertCodesToDB',
type: 'POST',
dataType: 'json',
cache: false,
data: JSON.stringify({ 'name': 'name' }),
success: function (response) {
#(ViewBag.MessageOK) = response;
},
error: function () {
// function call missing "()"
onBegin();
}
});
});
// and close here
});
function onBegin() {
$('#files').hide();
$('#insertFiles').hide();
$('#loading').show();
$('#lblSelectedProductName').text('Trwa umieszczanie kodów w bazie danych. Proszę czekać ...');
$('#ttt').show();
}
</script>
The code in Ajax must be JavaScript. You cannot use C# code there (except to print some values). What is #(ViewBag.MessageOK) doing here:
success: function (response) {
#(ViewBag.MessageOK) = response;
},
If you want to display the response in a message box, try something like:
success: function (response) {
$("#your_message_id").html(response);
},
Notes: aside from that, you have several errors in your code as others pointed out in the comments.
1- Remove the quotes from the data like this:
data: JSON.stringify({ name: name }),
2- Change the error to this:
error: function () {
onBegin(); // You need "()" here
}
Or better this:
error: onBegin // You don't need "()" here
I guess you are sending data inside the AJAX call in the wrong way.
Try it like this
data: JSON.stringify({ name: name })
Hope this will help you.

AJAX array stopping AJAX call

Please see the AJAX code below:
function Save()
{
var checkBoxArray = $("input:checkbox:checked").map(function () {
return this.id
}).get();
var str = JSON.stringify(checkBoxArray);
var user = document.getElementById("ctl00_ContentPlaceHolder1_lstUsers");
$.ajax({
type: "POST",
url: "frmReview.aspx/AllocateReview",
data: '{strUser: "' + user.value + '", strCheckBoxes: ' + str + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess(),
async: false,
failure: function (response) {
alert('There was a problem allocating the reviews')
}
});
function OnSuccess() {
return function (response) {
alert("The reviews where allocated successfully");
}
}
}
and the server side code below:
<System.Web.Services.WebMethod()> _
Public Shared Sub AllocateReview(ByVal strUser As String, ByVal strCheckBoxes As String)
msgbox("got here")
End Sub
I put a breakpoint on the messagebox (server side). However, it is not reached. It is reached if I do not pass str (which is an array) i.e. I exclude it on the client side and server side. Why is the array not passed to the server? There is no error - it is as if nothing happens.
In a jQuery $.ajax() call, the data property should be either
a URL-style query string ("foo=bar&hello=world");
a plain object ({ foo: "bar", hello: "world" });
an array of objects with name and value properties
[ { name: "foo", value: "bar" },
{ name: "hello", value: "world" }]
Your code is building a JSON string, and I don't think it should be.

JavaScript not working in MVC web application

I have a ASP.NET MVC application and I have a few entries on the page that user can change and click Save and I go save those entries. My problem: It works fine for some entries and for other entries it just doesn't go in the controller Save function to do the save.
My code:
function DoSave() {
$("#pisave").attr("disabled", true);
var pid = $("#personid").val();alert(pid);
var firstname = $("#fname").val();alert(firstname);
var lastname = $("#lastname").val();alert(lastname);
var plz = $("#zip").val();alert(plz);
var ort = $("#city").val();alert(ort);
var bday = $("#birthdate").val();alert(bday);
var strasse = $("#street1").val(); alert(strasse);
var emailtext = $("#email").val();alert(emailtext);
var url = "#(Url.Action("SavePersonInfo", "Info"))";alert("URL");
$.ajax({
url: url,
data: { personid: pid,fn: firstname, ln: lastname, email: emailtext, zip: plz, city:ort, birthday: bday, street:strasse },
success: function () {
alert("Update Successful");
$("#pisave").removeAttr("disabled");
},
error: function () {
alert("Update Failed! Check entries.");
$("#pisave").removeAttr("disabled");
}
});
}
All alerts are displayed in all the cases. Only for some it goes to SavePersonInfo and for others it doesn't go in there. Any ideas what might be wrong?? Can it be validation issue for the entries?
The model binder fails to parse your date, change to post:
$.ajax({
type: "POST",
url: url,
data: { personid: pid,fn: firstname, ln: lastname, email: emailtext, zip: plz, city:ort, birthday: bday, street:strasse },
success: function() {
alert("Update Successful");
$("#pisave").removeAttr("disabled");
},
error: function() {
alert("Update Failed! Check entries.");
$("#pisave").removeAttr("disabled");
}
});​
Read more about the problems with dates in asp.net-MVC
Note that you can add all the elements a class and use the serialize function:
$.ajax({
type: "POST",
url: url,
data: $('.theClass').serialize(), // <=============
success: function() {
alert("Update Successful");
$("#pisave").removeAttr("disabled");
},
error: function() {
alert("Update Failed! Check entries.");
$("#pisave").removeAttr("disabled");
}
});​

Categories

Resources