Getting text value to Controller using jquery ajax call - javascript

My text box and button
<input type="text" class="form-control" name="ClaimNumber" placeholder="Enter a claim number"
id="ClaimNumber" />
<button class="btn btnNormal" type="submit" id="btnSearch">
<i class="fa fa-search"></i>
</button>
My jquery
$(document).ready(function () {
$("#btnSearch").on("click", function () {
var enteredClaimNumber= $("#ClaimNumber").val();
alert(enteredClaimNumber);
$.ajax({
type: "POST",
url: "/Home/ClaimsSearch",
data: enteredClaimNumber
});
});
});
My controller
[HttpPost]
public ActionResult ClaimsSearch(string enteredClaimNumber)
{
_lfAPI.ClaimsAdvanceSearch(enteredClaimNumber);
return View();
}
I'm not able to get the value in controller..Thanks in advance..

Data in AJAX request must be like name, value pair:
data: {"enteredClaimNumber": ClaimNumber}
Write like this:
$(document).ready(function () {
$("#btnSearch").on("click", function () {
var ClaimNumber = $("#ClaimNumber").val();
alert(enteredClaimNumber);
$.ajax({
type: "POST",
url: "/Home/ClaimsSearch",
data: {"enteredClaimNumber": ClaimNumber}
});
});
});

var datum = {"claimNum": ClaimNumber};
$.ajax ({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Home/ClaimsSearch",
dataType: "json",
data: JSON.stringify(datum),
});

![Check This][1]
In
data : { parameter : value }
if there are multiple parameter then separate with comma (,)
data : { parameter1 : value1,parameter2 : value2 }
as shown below
$.ajax({
url: this.href,
type: 'POST',
data: { input: $('#caption').val() },
success: function (result) {
alert(result.name);
},
error: function () {
alert("error");
}
});

Related

Problem on passing array to ajax request in laravel

I am trying to pass array through ajax request
<input type="text" name="item_name[]">
<input type="text" name="address">
$(document).on('click', '#save_info', function () {
var address = $("#address").val();
var item_name = $("[name^='item_name']");
$.ajax({
url: '/save_information',
dataType: "json",
type: 'POST',
data: {
_token: '{{ csrf_token() }}',
address: address,
item_name: item_name,
}
});
});
In my controller
$item_name = $request->item_name;
$array_count = count($item_name);
It makes error. How can i save array value using loop. Thanks in advance
#Mujahidur Rahman Mithun IUB you can write this more shortly by using serializeArray.
$(document).on('click', '#save_info', function () {
var serializeData = $("[name^='item_name']").serializeArray();
serializeData.push(
{
name: "address", value: $("#address").val()
},
{
name: "_token", value: '{{ csrf_token() }}'
},
);
$.ajax({
url: '/save_information',
dataType: "json",
type: 'POST',
data: serializeData
});
});
Or if you use <form>, then you can use with very few line code :
$(document).on('click', '#save_info', function () {
$.ajax({
url: '/save_information',
dataType: "json",
type: 'POST',
data: $('form#myform').serialize(),
});
});
`
The variable item_name holds DOM Node instead of input values. You'd have to make it either var item_name = $("[name^='item_name']").val() or var item_name = $("[name^='item_name']").value

I want to use the data in the Controller in the View side javascript

this is my controller:
public ActionResult AjaxSmsSend(Sms smsInfo)
{
var sms = smsInfo.smsCode;
var telephone = smsInfo.telephone;
ViewBag.Code = sms;
return Json(sms);
}
In the View :
<button id="getDataBtn">Click me</button>
When I press this button :
<script type="text/javascript">
$(function () {
$("#getDataBtn").click(function () {
$.ajax({
type: "GET",
url: "/Home/AjaxSmsSend",
data: sms,
contentType: "application/json; charset=utf-8",
dataType: "json",
});
});
</script>
I will use it to compare the sms data I received from the controller.
<p style="text-align: center;margin-top: 10%;">Enter your sms code</p>
<input type="text" id="pincode" maxlength="4">
This input is entered by the user. I have generated sms data in the controller itself.
I'm sure it's actually a very simple process. But since I've just started, I can't find what I'm looking for. I'd appreciate it if you could help me with that.
I don't think it's a good practice, normaly the comparison should in server side but you can Add this :
success: function (response) {
if (response.smsCode)
{
}
}
it will be like this :
<script type="text/javascript">
$(function () {
$("#getDataBtn").click(function () {
$.ajax({
type: "GET",
url: "/Home/AjaxSmsSend",
data: sms,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (response.smsCode)
{
}
}
});
});
</script>
Then put your code inside this if :
if (response.smsCode)
{
}
That's all, I hope you find this helpful

Use AJAX response to update select option

This code can fetch data from a database then return it to a select option:
$(document).on('click', '.renew', function() {
var user_id3 = $(this).attr("id");
$.ajax({
url: "../controller/fetch_single.php",
method: "POST",
data: {
user_id3: user_id3
},
dataType: "json",
success: function(data) {
$('#bus_type').html(data.type);
}
})
});
The AJAX is successful and returning the JSON but the select option is still returning blank instead of the data coming from AJAX. What am I doing wrong?
Example output of data:
{
"id":"575",
"bus_name":"THIS LOVE",
"type":"RERE",
"address":"SDF"
}
$(document).on('click', '.renew', function() {
var user_id3 = $(this).attr("id");
$.ajax({
url: "../controller/fetch_single.php",
method: "POST",
data: {
user_id3: user_id3
},
dataType: "json",
success: function(data) {
// If the option is in the select
$('#bus_type').find('option[value="'+data.id+'"]').prop('selected', true);
// Or if the option is not there yet
var $option = $('<option></option>').html(data.type).attr('value', data.id).prop('selected', true);
$('#bus_type').append($option); // Adds the new option as last option
$('#bus_type').prepend($option); // Adds the new option as first option
}
})
});
Assuming your HTML is:
<select id="bus_type">
<!-- no content yet -->
</select>
and your response is :
{
"id":"575",
"bus_name":"THIS LOVE",
"type":"RERE",
"address":"SDF"
}
Then your success() method would just print the following:
<select id="bus_type">
RERE
</select>
which is not a valid HTML for a <select>.
Your JS should look like this for it to work:
$(document).on('click', '.renew', function() {
var user_id3 = $(this).attr("id");
$.ajax({
url: "../controller/fetch_single.php",
method: "POST",
data: {
user_id3: user_id3
},
dataType: "json",
success: function(data) {
$('#bus_type').html("<option value='"+ data.type +"'>"+ data.type +"</option>");
}
})
});
Or like this if you want to preserve the existing options:
$(document).on('click', '.renew', function() {
var user_id3 = $(this).attr("id");
$.ajax({
url: "../controller/fetch_single.php",
method: "POST",
data: {
user_id3: user_id3
},
dataType: "json",
success: function(data) {
$('#bus_type').append("<option value='"+ data.type +"'>"+ data.type +"</option>");
}
})
});
The success() method would print the following:
<select id="bus_type">
<option value="RERE">RERE</option>
</select>
If you would provide us some HTML I could edit my answer to your specific needs.

C# How to call MVC Controller function by using javascript or jquery

I have this at my controller:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DeleteUser(UserViewModel viewModel)
{
}
I have this at my cshtml:
<input type="button" id="btnDelete" value="Delete" />
I have this at my js file:
$('#btnDelete').click(function (e) {
});
How do I call controller function from js file?
$.post("Controller/CreateUser", dataToPost)
.done(function(response, status, jqxhr){
// this is the "success" callback
})
.fail(function(jqxhr, status, error){
// this is the ""error"" callback
});
or
var data = {
username: $('#username').val().trim(),
password: $('#password').val()
};
$.ajax({
type: "POST",
url: "Controller/CreateUser",
content: "application/json;",
dataType: "json",
data: JSON.stringify(data),
success: function(d) {
},
error: function (xhr, textStatus, errorThrown) {
}
});
ps: compose the data object according to the UserViewModel properties.
Inside the button click, execute ajax request
$('#btnDelete').click(function (e) {
$.ajax({
type: "POST",
url: 'controller/DeleteUser',
dataType: "json",
success: function(data){
//html content
},
});
}
It's very easy to access any controller method using ajax post method.
As here I'm getting states as per selected country using
'RegionesController' method name 'GetStates' also here I'm passing
CountryId to get states as per this id.
EX:
function GetStates() {
$.ajax({
type: "POST",
async: false,
url: abp.appPath + 'Regiones/GetStates?CountryId=' + $("#ddlCountry").val(),
success: function (result) {
//return data or object
},
error: function (err) {
abp.notify.info(err.statusText);
}
});
}

Dynamically get URL for JQuery Ajax request from Data Attribute

I have a JQuery Autocomplete function that I need to be able to pass a url into. I'm trying to pull the url from the html data-url attribute, however I'm currently getting a variable is undefined message in the JavaScript console, so I know I'm not getting the values I expect. I've included my code below. Any help would be greatly appreciated.
JQuery Function:
$(function () {
$(".autocomplete").autocomplete({
delay: 0,
source: function (request, response) {
var baseURL = $(this).data("url");
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: baseURL + request.term,
dataType: "json",
success: function (data) {
response(data)
}
});
},
minLength: 1,
});
HTML Element:
<td style="width: 90%">
<label for="tag_Name" class="inline">Server Tags: </label>
<input class="fixed autocomplete" type="text" id="tag_Name" placeholder="Type tags to add..." data-url="/RequestFieldValues/GetLikeResourceTags/?prefix=" />
</td>
Try this instead...
$(function () {
$(".autocomplete").each(function() {
var baseURL = $(this).data("url");
$(this).autocomplete({
delay: 0,
source: function (request, response) {
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: baseURL + request.term,
dataType: "json",
success: function (data) {
response(data)
}
});
},
minLength: 1,
});
});
});
I've put the .autocomplete() inside an each() function so you can refer to this to get the base url from the data attribute. You can then pass that into the source function.
Incidentally, if there is more than 1 input then you need to make each one have a unique ID. You shouldn't have elements with the same ID :)
Another way to change the URL in a ajax request
$.ajax({
url: "http://static.url/",
beforeSend: function (xhr) {
this.url = "http://dyn.url/" + "here"
}
});
i think what you should be doing is :
$(function () {
var baseURL = $(".autocomplete").data('url');
$(".autocomplete").autocomplete({
delay: 0,
source: function (request, response) {
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: baseURL + request.term,
dataType: "json",
success: function (data) {
response(data)
}
});
},
minLength: 1,
});

Categories