Ajax success function not receiving data ASP.NET MVC - ajax

I can add the data to the database correctly, but Ajax success function is not working. I always get the error function :
View:
<div id="dvform">
<!-- some data-->
<input type="submit" value="submit" id="btnsubmit" />
</div>
<script>
$(document).ready(function () {
$("#btnsubmit").click(function () {
addAppointment();
});
});
function addAppointment (){
$.ajax({
type: 'POST',
url: '/FuelerAppointments/Create',
contentType: 'application/json; charset=utf-8',
dataType: "html",
data: $("dvform").val(),
success: function (data) {
swal("Done!", "The appointment was saved successfully!", "success");
},
error: function (data) {
swal("Error deleting!", "Please try again", "error");
},
});
}
Controller :
[HttpPost]
public ActionResult Create(FuelerAppointment fuelerAppointment)
{
return Json(fuelerAppointment, JsonRequestBehavior.AllowGet);
}

First you should change dataType: "html", to dataType: "json",
and create FuelerAppointment object before the $.ajax():
var fuelerAppointment = {};
fuelerAppointment.Name = $("#Name").val();
and then the data in ajax method
data: '{fuelerAppointment: ' + JSON.stringify(fuelerAppointment) + '}',
For more information check this link Using AJAX In ASP.NET MVC

change dataType: "html" to dataType: "json"
and in data properties should you write like this
var model = {
prop1: prop1Value,
prop2: prop2Value,
...
};
data: {fuelerAppointment: model}
Or
data: JSON.stringify({
fuelerAppointment: {
prop1: prop1Value,
prop2: prop2Value,
...
}
})
Notes: the fuelerAppointment object should behave a sem proprieties in C# class

Related

The GET method is not supported for this route. Supported methods: POST. Laravel Ajax

I'm using ajax to send comments. This is the route
Route::post('/users/add/comment/', 'UsersController#AddComment')->name('AddComment');
The ajax call
function SendAny(){
$.ajax({
url: '/users/add/comment/',
data: {
"_token": "{{ csrf_token() }}",
"content": 'ksdflsdfnnkn',
},
type: 'post',
success: function(result) {
if (result == 0) {
location.reload();
} else {
alert("this an ereor")
}
}
});
}
and the controller
public function AddComment(Request $request){
dd($request);
}
It always throws that error. I changed the route and the func name a lot of times. but it does the same thing and the dd(); request is always empty.
Thanks in advance!
You have to set the ajax method to post with the attribute 'method', not 'type'.
function SendAny(){
$.ajax({
url: '/users/add/comment/',
data: {
"_token": "{{ csrf_token() }}",
"content": 'ksdflsdfnnkn',
},
method: 'post',
success: function(result) {
if (result == 0) {
location.reload();
} else {
alert("this an ereor")
}
}
});
}
I was trying to send the same data using <form> I tried AJAX to have more control over the request.
my form tag goes like <form method="POST" action="/users/add/comment/">
I removed the last / in the URL and it does work. I don't know how or why.
But It works !!!
Form
<form id="YourForm">
...
your inputs
...
</form>
Button
<button type="button" class="btn btn-success SendButton">Save This</button>
JS
<script type="text/javascript">
$(document).on('click', '.SendButton', function (e) {
e.preventDefault();
var data = $("#YourForm").serialize();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
method : "POST",
url : "{{ url('users/add/comment/') }}",
data : data,
dataType : "JSON",
})
.done(function(response) {
alert('Success!');
location.reload();
.fail(function(response) {
console.log("Error: ", response);
});
return false;
});
</script>
You need to change type to method, you use the wrong keyword. Now it is a default GET
$.ajax({
url: '/users/add/comment/',
data: {
"_token": "{{ csrf_token() }}",
"content": 'ksdflsdfnnkn',
},
method: 'post', // it should be method: 'post'
success: function(result) {
if (result == 0) {
location.reload();
} else {
alert("this an ereor")
}
}
});

MVC Razor Ajax call from button click

I'm struggling to get a button click to invoke an Ajax function which then posts to a controller action. Cannot even get a simple message to work (nothing happens when button is clicked). Clearly, I'm missing something fundamental. What is it?
The Ajax script in my Razor form:
<script type="text/javascript">
$('#UseShipAddr').click(function () {
$.ajax({
url: "#(Url.Action("UseShippingAddress", "Checkout"))",
type: "POST",
data: { id: 50 },
cache: false,
async: true,
success: function (data) {
alert(data);
}
});
});
</script>
The button that I want to use to invoke the Ajax function:
<input type="button" value="Use Shipping Address" id="UseShipAddr" />
The action in CheckoutController:
// Ajax POST: /Checkout/UseShippingAddress/5
[HttpPost]
public ActionResult UseShippingAddress(int id)
{
return Content("It worked!");
}
Please try this code.
$(document).ready(function(){
$('#UseShipAddr').click(function () {
$.ajax({
url: "Checkout/UseShippingAddress",
type: "POST",
data: { id: 50 },
cache: false,
async: true,
success: function (data) {
alert(data);
}
});
});

jquery ajax web method call

I am trying to call ajax web method when button is clicked. This is the following code I have written.
$(function() {
$("<%=btnRatingSubmit.ClientID%>").click(function (e) {
var textrating = $('#<%= btnRatingSubmit.ClientID %>');
$.ajax({
type: 'POST',
url: 'NewRatings.aspx/SubmitRatings',
data: '{rating: \'' + textrating.val() + '\'}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function doNothing(data) {
},
error: function throwError(data) {
},
});
});
This is asp button I am using
<asp:Button ID="btnBack" runat="server" Text="Back To Results" OnClick="btnBack_Click" />
The code behind is
[WebMethod]
[ScriptMethod]
public static void SubmitRatings(string rating)
{
if (HttpContext.Current.Request.QueryString["ID"] != null)
{
if (HttpContext.Current.Session["LoginId"] != null)
{
string str = HttpContext.Current.Request.Form["lblRate"];
RatingsBAL bal = new RatingsBAL();
bal.StoreRatings(HttpContext.Current.Session["LoginId"].ToString(), HttpContext.Current.Request.QueryString["ID"], Convert.ToInt32(rating));
}
}
}
But for some reason the web method is not being fired. Can anyone help me please? Thanks in advance.
Change $("<%=btnRatingSubmit.ClientID%>").click to
$('#'+"<%=btnRatingSubmit.ClientID%>").click
You were missing a #, which is used to select elements by their ids in jquery.
Full Code:
$(function () {
$('#' + "<%=btnRatingSubmit.ClientID%>").click(function (e) {
var textrating = $('#<%= btnRatingSubmit.ClientID %>');
$.ajax({
type: 'POST',
url: 'NewRatings.aspx/SubmitRatings',
data: {
rating: textrating.val()
},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function doNothing(data) {},
error: function throwError(data) {},
});
});
function Functioncall(){
var textrating = $('#<%= btnRatingSubmit.ClientID %>');
$.ajax({
type: 'POST',
url: 'NewRatings.aspx/SubmitRatings',
data: {
rating: textrating.val()
},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function doNothing(data) {},
error: function throwError(data) {},
});
}
<asp:Button ID="btnBack" runat="server" Text="Back To Results" OnClientClick="Functioncall()" />

jQuery validation followed by Ajax post

I'm trying to combine jQuery validation plugin with Ajax post. This is my code:
PHP form:
<form id="newsletter_form" method="post">
<input name="newsletteremail" type="text" id="newsletteremail" class="required email">
<input name="Signup" type="submit" class="formsm" id="Signup" value="Signup">
<div id="emailerrormessage"></div>
</form>
JQuery:
$('#newsletter_form').validate({
rules: {
email: {required:true, email:true}
},
submitHandler: function(form) {
$.ajax({
data: $(this).serialize(),
type: "POST",
url: "includes/ajax.php?action=newsletter",
contentType: "application/x-www-form-urlencoded; iso-8859-7",
dataType: 'json',
success: function(response, textStatus, jqXHR) {
if(response.status == 'error'){
$("#newsletteremail").removeClass().addClass('ajaxerror');
} else {
$("#newsletteremail").removeClass();
}
},
error: function (xhr, textStatus, errorThrown) {
$("#emailerrormessage").addClass('ajaxsuccess').html(xhr.responseText).show();
}
});
return false;
}
});
Before using validate() the form would submit fine. After adding the validate() code, the validation works, the form is being submitted (I receive a 200 OK response) but the values being submitted are null. What am I doing wring here?
this refers to the validator object that you're applying to the form, so change:
data: $(this).serialize(),
to
data: $(form).serialize(),
Use jQuery.form plugin and try it as below,
submitHandler: function(form)
{
jQuery(form).ajaxSubmit(
{
dataType : 'json',
beforeSend : function(arr, $form, options)
{
},
success : function(msg)
{
return false;
}
});
}

Jquery .ajax() function not returning values from codeigniter controller

I have a site i'm working on and i'm trying to make an ajax request to a controller (codeigniter framework). I see in firebug that my controller is receiving my post value just fine but for some reason it is not sending back a response. I've set it up to be VERY simple without a database call at this point just for testing and its still not working. Any ideas?
Here is my form in my view:
<div class="purchaseState">
<input type="text" name="city" id="city" class="grayGrad"/>
</div>
<div>
<ul id="cityResults">
<!-- AJAX results here -->
</ul>
</div>
Here is my controller returning the value:
function citySearch() {
echo '<li>test</li>';
}
Here is my Jquery ajax
//New City Search
$('#city').keyup( function() {
var city = $('#city').val();
$.ajax({
type: "POST",
url: "page/citySearch",
data: { city: city },
}).done(function( data ) {
$('ul#cityResults').append(data);
});
});
you should use ajax success callback:
$('#city').keyup(function() {
var city = $('#city').val();
$.ajax({
type: "POST",
url: "page/citySearch",
data: { city: city },
success: function(data) {
$('ul#cityResults').append(data);
}
});
});
Please change the url in the AJAX function in the following way.
$('#city').keyup(function() {
var city = $('#city').val();
$.ajax({
type: "POST",
url: "<?php echo base_url; ?>page/citySearch",
data: { city: city },
success: function(data) {
$('ul#cityResults').append(data);
}
});
});

Resources