How to populate data from API and load into dropdown - javascript

I am working on MVC application that uses API and i want to call a method from the API so that it will load the data to the combo-box. I have no idea on how i can tackle this as am new this.
Thanks.
ClaimController function from the API which got this function.
[RoutePrefix("api/Claim")]
[Route("GetScheme")]
[HttpGet]
public HttpResponseMessage GetScheme()
{
try
{
using (IBusinessLogic logic = new BusinessLogic.Implementation.BusinessLogic())
{
Request.Headers.Clear();
var tmpresults = logic.GetScheme();
var results = (from x in tmpresults.Result select new { text = x.Description, value = x.Id }).ToArray();
var response = Newtonsoft.Json.JsonConvert.SerializeObject(results);
return Request.CreateResponse(HttpStatusCode.OK, results);
}
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.BadRequest, ex);
}
}
Views from the Client which is the UI
I want to call that function from API to load the data into the combo-box
function GetAllScheme() {
var select = $("#ddlScheme");
$.ajax({
type: "GET",
url: "http://localhost:55393/_Api/Claim",
dataType: "json",
success: function (data) {
debugger;
var datavalue = data;
var serverResponse = datavalue;
contentType: "application/json";
$.each(serverResponse, function (i, serverResponse)
{
select.append("<option value='" + serverResponse.Description + "'>" + serverResponse.Description + "</option>")
});
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
Dropdown
<select class="dropdown form-control input-xs required" id="ddlScheme" onclick="GetAllScheme()(this)">
<select
</select>
</div>

You have to append option elements into your select (dropdown) element after you get the server response. Something like this:
function GetAllScheme() {
// get the dropwdown by its id
var select = $("#ddlScheme");
$.ajax({
...
success: function (data) {
$.each(myJsonObject, function (i, mobj) {
$("#Cartbl").append('<tr><td width="50px">' + mobj.Description + '</td></tr>');
// for each element, add an option into the dropdown
select.append('<option>"+ mobj.Description +"</option>')
}
});
...
)}
See jsfiddle https://jsfiddle.net/n4mtj9om/

If use Chrome enter in developers tools a see how response the server put a breakpoint after server response because when use maybe
put this
function GetAllScheme() {
$.ajax({
type: "GET",
url: "http://localhost:32359/api/Claim",
dataType: "json",
success: function(data) {
$.each(data.responseJSON, function(i, mobj) {
$("#Cartbl").append('<tr><td width="50px">' + mobj.Description +
'</td></tr>');
});
},
error: function(xhr) {
alert(xhr.responseText);
}
});
}

Related

Fetching data from MSSQL

I got an interface that sends (FROMDATE and TODATE) to the MSSQl and retrieves the selected details and after receiving them the data is shown on the grid.
I'm using the MVC.
This is the js script that I'm using.
$('body').on('submit', '#form', function (e) {
e.preventDefault();
$('#btnSubmit').html('<i class="fa fa-refresh fa-spin" style="font-size:14px"></i> Please wait ....');
$('#btnSubmit').prop('disabled', true);
var fromdate = $('#PeriodFrom').val();
var todate = $('#PeriodTo').val();
if ($('#PeriodFrom').val() > $('#PeriodTo').val())
{
ToastMessage("To date cannot be less than From date ");
return false;
}
debugger;
$.ajax({
url: '/ReservationInquiries/ReservationInquery?fromdate=' + fromdate + '&todate=' + todate,
dataType: 'JSON',
method: 'GET',
beforeSend: function () {
$('#btnSubmit').html('<i class="fa fa-refresh fa-spin" style="font-size:14px"></i> Please wait ....');
$('#btnSubmit').prop('disabled', true);
},
complete: function () {
$('#btnSubmit').html('Save');
$('#btnSubmit').prop('disabled', false);
},
success: function () {
FillGrid();
},
error: function (xhr, status, error) {
console.log(error);
}
});
});
url: '/ReservationInquiries/ReservationInquery?fromdate=' + fromdate + '&todate=' + todate,
When the user picks the date range.By using the following URL it sends the Fromdate and Todate toward the controller then the Service and then the Entry.
It returns backs ReservationNo and Name from MSQL.
So according to my program, everything is fetched to the model (the values which is fetched from MSQL).
As you can see when it redirects back I'm calling a function called **FillGrid();**in my js.
function FillGrid() is the function that I'm using to draw the grid in the HTML.
Even the data is fetched nothing is displayed on my grid is this wrong?
can anyone help me?
function FillGrid() {
debugger;
if ($('#grid').length == 1) {
$('#grid tr').not(':first-child').remove();
$.ajax({
//url: '/ReservationInquiries/select?search=' + $('#txtSearch').val(),
//dataType: 'JSON',
beforeSend: function () {
$('.grid').hide();
$("#loadingProjects").show();
},
complete: function () {
ShowGrid();
$("#loadingProjects").hide();
},
method: 'POST',
success: function (data) {
debugger
//var inquirieslist = JSON.stringify(data.InqueryList)
$('#grid tr:not(:first)').empty();
if (inquirieslist != null) {
$.each(inquirieslist, function (index, item) {
$('<tr>' +
'<td>' + item.ReservationNo + '</td>' +
'<td>' + item.Name + '</td>' +
'</tr>').appendTo($('#grid'));
});
}
},
error: function (xhr, status, error) {
console.log(error);
}
});
}
}

wordpress ajax returning zero instead of string message

My ajax call is returning zero even though I wrote die() at the end of my PHP function.
I looked over the other questions here and did not figure it out, please take a look at my code
I make an ajax call using this function:
$('.aramex-pickup').click(function() {
var button = $(this);
var pickupDateDate = $('.pickup_date').val();
var pickupDateHour = $('.pickup_date_hour').val();
var pickupDateMinute = $('.pickup_date_minute').val();
var pickupDate = pickupDateDate + ' ' + pickupDateHour + ':' + pickupDateMinute;
var orderId = button.data('id');
if (pickupDate) {
//show loader img
button.next('.ajax-loader').show();
var data = {
'action': 'aramex_pickup',
'order_id': orderId,
'pickup_date': encodeURIComponent(pickupDate)
};
$.ajax({
url: ajaxurl,
data: data,
type: 'POST',
success: function(msg) {
console.log(msg);
if (msg === 'done') {
location.reload(true);
} else {
var messages = $.parseJSON(msg);
var ul = $("<ul>");
$.each(messages, function(key, value) {
ul.append("<li>" + value + "</li>");
});
$('.pickup_errors').html(ul);
}
}, complete: function() {
//hide loader img
$('.ajax-loader').hide();
}
});
} else {
alert("Add pickup date");
}
return false;
});
in the back-end I wrote this function just to test the ajax is working ok:
public function ajax_pickup_callback() {
echo 'ajax done';
die();
}
I registered the action by:
add_action('wp_ajax_aramex_pickup', array($this, 'ajax_pickup_callback'));
all of this returns 0 instead of "ajax done".
Any help please?
Actually your hook is not get executed. You have to pass the action in the ajax request as you can see here.
jQuery.post(
ajaxurl,
{
'action': 'add_foobar',
'data': 'foobarid'
},
function(response){
alert('The server responded: ' + response);
}
);

Populate Dropdown List based on Autocomplete Value

I have three form fields for country(text input), city(text input) and street(dropdown):
country is autocomplete
city is auto-filled based on the result of country
street I want to generate dropdown list based on selected city
Here is my current JavaScript script:
$(".country").autocomplete("get_city.php",{ mustMatch:true })
.result(function (evt, data, formatted) {
$(".city").val(data[1]);
});
So far it's auto-filling the city(text input).
My problem now is to generate drop down list based on the filled city.
I Think you need somthing like this:
$(".country").change(function () {
var webMethod = "filewithdata.php";
var parameters = { id: $('.country').val() };
$.ajax({
type: "GET",
url: webMethod,
data: parameters,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
//console.log(response);
json_obj = $.parseJSON(response);
var output = '';
for (var i in json_obj) {
if (json_obj[i][4] == 1) {
output += '<option value="' + json_obj[i][0] + '">' + json_obj[i][0] + '</option>'
}
}
$('#dropdownElement').empty().append(output);
},
error: function (e) {
$(divToBeWorkedOn).html("Unavailable");
alert("Errror:" + e);
}
});
});

Jquery, For each looping a List of objects

I have a list of "User" with has Name, Surname and Email.
I need to loop through it on Jquery. This list is returned by a server side method
success: function (result) {
// var res = result.d
$.each(result, function (index, obj) {
alert(obj);
});
}
Does anyone know how it can be done?
Edit: The entire Ajax list:
var param = '{"NameofMap":"' + nofm + '", "VillNum":"' + numberV + '"}';
$.ajax({
url: 'GenerateMap.aspx/AddVill',
type: "POST",
data: param,
dataType: "json",
contentType: "application/json",
error: function (msg)
{ alert("Fails"); },
success: function (result) {
$.each(result, function (index) {
alert("Test");
});
}
});
This is the entire Ajax. It returns a list of Class instances ("User")
It displays "Test" but if I change that with alert(result[index].Name); , it displays just an empty box.
As you haven't provide proper information, still you can give this a try.
If you're getting into the success: and able to get alert, you can try like this:
You can have properties with it's name
--> result.Name
--> result.Surname
--> result.email
So Your code will be like following:
$.each(result, function(index) {
alert(result[index].Name);
.......
});
Or
$.each(result, function(index, item) {
alert(item.Name);
.......
});
This might help!
try
$.each(data,function(i, item){
alert(item.name)
});

Variable not accesable in ajax response

I'm having troubles using a global variable in my ajax response.
LastDate is a variable defined in the page I loaded into my second page. (function load_table)
I am able to acces the variable before the ajax call, but I can't seem to acces it in my ajax succes. because it gives undefined. <==== in code
my code:
var dia_date = {};
$(window).load(function()
{
DP("eerste keer")
load_table();
} );
function load_table()
{
DP('load_table');
$.ajax({
type: "POST",
url: "/diagnose_hoofdpagina/table_diagnose/" + DosierID,
success: function (data) {
$("#diagnoses_zelf").html('');
$("#diagnoses_zelf").append(data).trigger('create');
//initialize_table();
update_table();
},
error: function(){
alert('error');
}
});
return false;
}
function update_table()
{
if(LastDate > Datum)
{
alert("LasteDate" + LasteDate);
}
else
{
alert("Datum" + Datum);
}
alert('gast .... ' + LastDate); // <========== this is promted on the screen so there is no problem
$.ajax({
type: "POST",
url: "/refresh_diagnose/" + DosierID,
dataType: "json",
data : JSON.stringify(dia_date),
success: function (data) {
var DataDate = new Date(data.Year, data.Month, data.Day, data.Hour, data.Minute, data.Second);
alert('lastdate :'+ LastDate + 'date.date :' + DataDate);
//<============ BUT HERE HE GIVES LastDate AS UNDEFINED
},
error: function(data){
alert(data);
}
});
return false;
}
I can't see what I'm doing wrong. Can annyone help me plaese ? Thanks in advance.
You can try making a function.
var lastDate = #;
function getLastDate(){return lastDate;}
ajax.blablabla.success :{getLastDate();}

Categories