MVC Razor Ajax call from button click - ajax

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);
}
});
});

Related

Laravel Return Response From Ajax

I am trying to learn Laravel9. For this I have Created a Controller, a model and blade view file. Below is my vatprofile.blade.php file code
<script type="text/javascript" src="https://code.jquery.com/jquery-2.0.2.js"></script>
<script>
$(document).ready(function () {
$.ajax({
type: "get",
url: "/vatprofile",
dataType: "json",
success: function (response) {
alert(response);
}
});
});
</script>
And this is my Rout,
Route::get('/vatprofile',
[VatProfileController::class,'index']);
And Below is my Controller Function
public function index(){
return response()->json(['success'=>'Record is successfully added']);
}
It is not Giving Error, Not printing out any response. Only the Blank Page is Showing up. Can you Correct me Pls
Please try this:
<script type="text/javascript" src="https://code.jquery.com/jquery-2.0.2.js"></script>
<script>
$(document).ready(function () {
$.ajax({
type: "get",
url: "{{ url('vatprofile') }}",
dataType: "json",
success: function (response) {
alert(response);
}
});
});
</script>

Buttons received from Ajax are not clickable

I'm using the following code to receive some content from a page called filter.PHP. But the issue is the buttons become not clickable once fetched.
<script type="text/javascript">
$(document).ready(function() {
$("#display").click(function() {
$.ajax({
type: "POST",
url: "filter.php",
dataType: "html",
success: function(response) {
$("#responsecontainer").html(response);
}
});
});
});
</script>
I have buttons like these on the filter.php file.
<button onclick="location.href='details.php?id=<?php echo htmlspecialchars($result->nid); ?>'" class="buttonnew">Details </button>
Any help would be much appreciated.
You have to add the event listener from JavaScript, when you fetch the html from an ajax response.
document.querySelector('.buttonnew').addEventListener('click', () => { location.href=''});
Or
document.querySelectorAll('.buttonnew').forEach(btn => { btn.addEventListener('click', () => { location.href='';})});

how to make successfull ajax success

Button code
this is my button code with id 123
<button type="submit" class="addto" id="123">Add to cart</button>
ajax code
This is my ajax code
$(document).ready(function(){
$('.addto').click(function (event) {
event.preventDefault();
$id=this.id;
//alert($id);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '/test', //route url
dataType:"json",
type:"POST",
data:{id:this.id},
success: function(result){ //success function
alert("success"); //test alert
}});
});
});
Route code
this is my route code
Route::match(['get','post'],'/test','ajaxcontrol#test'); //route url
Controller code:
How to solve this, i have included all the imports
class ajaxcontrol extends Controller
{
public function test(Request $request){
$valu=$request->id;
echo json_encode($valu);
}
}
Try to change your ajax like this:
$(document).ready(function(){
$('.addto').click(function (event) {
event.preventDefault();
id=this.id;
//console.log(id);
$.ajax({
url: "{{ url('/test') }}", //route url
dataType:"json",
type:"POST",
data:{
id:id,
"_token": "{{ csrf_token() }}",
},
success: function(result){ //success function
alert("success"); //test alert
}});
});
});

Ajax success function not receiving data ASP.NET MVC

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

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()" />

Resources