Here is the code to call webservice to return json
$('#page_job_list_pages').live('pageshow',function(){
try {
$.ajax({
url: "http://domain.com/json/" + encodeURIComponent(tid),
type: 'get',
dataType: 'json',
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('page_job_list_pages - failed to retrieve pages');
console.log(JSON.stringify(XMLHttpRequest));
console.log(JSON.stringify(textStatus));
console.log(JSON.stringify(errorThrown));
},
success: function (data) {
$("#page_job_list_pages_list").html("");
$.each(data.nodes,function (node_index,node_value) {
console.log(JSON.stringify(node_value));
if(node_index != 0) {
var companyName = node_value.node.field_basic_info.match("Company:(.*)date");
$("#page_job_list_pages_list").append($("<li></li>",{"html":"<a href='#node_view' id='" + node_value.node.Nid + "' class='page_job_list_pages_list_title'>" + companyName[1] + "</a>"}));
}
});
$("#page_job_list_pages_list").listview("destroy").listview();
$("#page_job_list_pages_list").append('<a onclick="()" data-role="button" data-theme="a">TEST</a>');
}
});
}
catch (error) { alert("page_job_list_pages_list - " + error); }
});
this line is a button
$("#page_job_list_pages_list").append('<a onclick="()" data-role="button" data-theme="a">TEST</a>');
i want to call the jquery function to query the json again.
HOW to do that?
I've wrapped your query in a function. I am assuming this is what you want. I've also added the call in the click handlers of your buttons to query again.
Note:
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live(). (Source: http://api.jquery.com/live/)
$('#page_job_list_pages').live('pageshow',function(){
queryJSON();
});
function queryJSON(){
try {
$.ajax({
url: "http://domain.com/json/" + encodeURIComponent(tid),
type: 'get',
dataType: 'json',
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('page_job_list_pages - failed to retrieve pages');
console.log(JSON.stringify(XMLHttpRequest));
console.log(JSON.stringify(textStatus));
console.log(JSON.stringify(errorThrown));
},
success: function (data) {
$("#page_job_list_pages_list").html("");
$.each(data.nodes,function (node_index,node_value) {
console.log(JSON.stringify(node_value));
if(node_index != 0) {
var companyName = node_value.node.field_basic_info.match("Company:(.*)date");
$("#page_job_list_pages_list").append($("<li></li>",{"html":"<a href='#node_view' id='" + node_value.node.Nid + "' class='page_job_list_pages_list_title'>" + companyName[1] + "</a>"}));
}
});
$("#page_job_list_pages_list").listview("destroy").listview();
$("#page_job_list_pages_list").append('<a onclick="queryJSON();" data-role="button" data-theme="a">TEST</a>');
}
});
}
catch (error) { alert("page_job_list_pages_list - " + error); }
}
this line is a button
$("#page_job_list_pages_list").append('<a onclick="queryJSON();" data-role="button" data-theme="a">TEST</a>');
Related
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);
}
});
}
}
i have a getJSON very large, and while this load all data in the document, how i can do to read other getJSON data while this is yet loading?
the event in .on( is detected, but the getJSON not, is detected only when the another getJSON is loaded all
$.getJSON('./master-list.php?q=master', function(data) {
$.each(data, function(i, item) {
if(i >= 120)
return false;
addServer(item);
});
});
$(document).on('click', '.servergetid', function() {
console.log('Hey!');
$('#pd').html('');
$.ajax({
url: './data.php?ip=' + $(this).data('server') + '&data=l_by_id',
dataType: 'json',
type: 'GET',
async: true,
success: function(data) {
$.each(data.players, function(i, item) {
$('#pd').append('<tr><td>' + item.Nickname + '</td><td>' + item.Score + '</td></tr>');
});
}
});
});
function addServer(ip)
{
var response = false;
$.getJSON('./data.php?ip=' + ip + '&data=info', function(data)
{
response = addServerInfo(data, '[x]');
});
return response;
}
Forget it, the solution is change async: true to async: false, thanks.
I am trying hard to fix this issue but still didn't get the solution, tried many links and code, but facing a bit problem to fix this.
ISSUE:
I have an input type 'Text' to search the employees name.
When I Start entering characters like 'WY', it shows all the names starting with WY.
Once I get the employee I need, I can move that to other control and Run PDF report (which loads in another Tab).
The issue is when I go back to the page where I should start searching the employees again, it won't search! as shown below:
Here is my ajax code :
$("#EmployeeSearchBox").bind('input propertychange', function () {
if ($('#EmployeeSearchBox').val() != '') {
$('#EmployeeList').empty();
$.ajax({
type: "GET",
url: "SomeSelectionPage.aspx/GetEmployees",
data: { 'searchText': "'" + $("#EmployeeSearchBox").val() + "'" },
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
//alert('success');
if (data.d.length > 0) {
$("#EmployeeList").removeClass("hideControl").addClass("showControl");
}
else {
$("#EmployeeList").removeClass("showControl").addClass("hideControl");
// $('select').multipleSelect();
alert("No data");
}
$.each(data.d, function (index, value) {
$('#EmployeeList').append($('<option>').text(value.FullName).val(value.EmployeeId));
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + XMLHttpRequest.responseText);
}
});
}
else {
$('#EmployeeList').empty();
$("#EmployeeList").addClass("hideControl");
}
});
UI Control :
<input type="text" id="EmployeeSearchBox" class="search-box" aria-multiselectable="true" />
Please let me know, what I should be doing to get it fixed.
This might be the reason for the issue
The $("#EmployeeSearchBox").bind('input propertychange', function () { ..}); might not be available in the DOM.
To ensure whether the EmployeeSearchBox and propertyChange handler are still alive, place an alert inside the propertychange function. If the alert is shown then the issue is some where else.
$("#EmployeeSearchBox").bind('input propertychange', function () {
if ($('#EmployeeSearchBox').val() != '') {
alert("Inside Property Change "); // Add this alert
$('#EmployeeList').empty();
$.ajax({
type: "GET",
url: "SomeSelectionPage.aspx/GetEmployees",
data: { 'searchText': "'" + $("#EmployeeSearchBox").val() + "'" },
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
//alert('success');
if (data.d.length > 0) {
$("#EmployeeList").removeClass("hideControl").addClass("showControl");
}
else {
$("#EmployeeList").removeClass("showControl").addClass("hideControl");
// $('select').multipleSelect();
alert("No data");
}
$.each(data.d, function (index, value) {
$('#EmployeeList').append($('<option>').text(value.FullName).val(value.EmployeeId));
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + XMLHttpRequest.responseText);
}
});
}
else {
$('#EmployeeList').empty();
$("#EmployeeList").addClass("hideControl");
}
});
what do you mean by bind it again
This is the function which is binding the EmployeeSearchBox with the DOM $("#EmployeeSearchBox").bind('input propertychange', function () {.... and when you are moving to the PDF tab and coming back again to SearchBox tab the binding of this element is lost, it means the DOM doesnot know what to be done when the property change is fired on the EmployeeSearchBox. Two ways to solve it
1) Ensure that the Event handler is always present in the DOM even when you navigate between tabs.
2) If option 1 is not achievable in your scenario, kindly rebind the event handlers whenever you are coming to the search tab. Explicitly invoke this $("#EmployeeSearchBox").bind when you are in the search tab.
Please check that the ajax call has raised for your second search.. if not there must be a problem in condition checking area or function calling method. I always use this function for searching data
$("input").change(function(){
ajax call.....
})
Am upvoting the suggestion provided from "Clement Amarnath", which helped me to resolve this issue.
I found the fix for this , instead of using .Bind(), I used .on() inside (document), am posting the answer which I have fixed it.
Thanks all!
$(document).on("input propertychange", "#EmployeeSearchBox", function () {
if ($('#EmployeeSearchBox').val() != '') {
$('#EmployeeList').empty();
$.ajax({
type: "GET",
url: "SomeSelectionPage.aspx/GetEmployees",
data: { 'searchText': "'" + $("#EmployeeSearchBox").val() + "'" },
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
//alert('success');
if (data.d.length > 0) {
$("#EmployeeList").removeClass("hideControl").addClass("showControl");
}
else {
$("#EmployeeList").removeClass("showControl").addClass("hideControl");
// $('select').multipleSelect();
alert("No data");
}
$.each(data.d, function (index, value) {
$('#EmployeeList').append($('<option>').text(value.FullName).val(value.EmployeeId));
});
},
//error: function (XMLHttpRequest, textStatus, errorThrown) {
// alert(textStatus);
//}
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + XMLHttpRequest.responseText);
}
});
}
else {
$('#EmployeeList').empty();
$("#EmployeeList").addClass("hideControl");
}
});
NOTE :
below line too works :
.live() method
$("#EmployeeSearchBox").live('input propertychange', function () {... });
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);
}
});
}
I have the following code that will hide the list-btn div and load the list-response div. It may however take 1-5 seconds for the list-response div to load, so I'd like to make it show a div called list-waiting while that happens and then once list-response shows, hide the list-waiting again.
They are all in the same place, basically replacing eachother, so I need to show one of them at a time only.
How would I do that?
jQuery(document).ready(function($){
$('.add-to-list').click(function (e) {
e.preventDefault();
var id = $(this).data("id");
$.ajax({
url: "https://www.domain.com/page.php?add=" + id,
type: "GET",
success: function (data) {
$("#list-btn-" + id).hide();
$("#list-response-" + id).show();
},
error: function (xhr, ajaxOptions, thrownError) {
$("#list-btn-" + id).hide();
$("#list-response-" + id).html('ERROR');
},
timeout: 15000
});
});
});
Hide list-btn and show list-waiting div just before AJAX call. Then hide list-waiting div in callbacks before showing list-response div.
jQuery(document).ready(function($){
$('.add-to-list').click(function (e) {
e.preventDefault();
var id = $(this).data("id");
$("#list-btn-" + id).hide();
$("#list-waiting-" + id).show();
$.ajax({
url: "https://www.domain.com/page.php?add=" + id,
type: "GET",
success: function (data) {
$("#list-waiting-" + id).hide();
$("#list-response-" + id).show();
},
error: function (xhr, ajaxOptions, thrownError) {
$("#list-waiting-" + id).hide();
$("#list-response-" + id).html('ERROR');
},
timeout: 15000
});
});
});
If you are using jQuery 1.8 or higher, I would suggest
jQuery(document).ready(function($){
$('.add-to-list').on("click",function (e) {
e.preventDefault();
var id = $(this).data("id");
$("#list-btn-" + id).hide();
$("#list-response-" + id).empty().hide();
$("#list-waiting-" + id).show();
$.ajax({
url: "https://www.domain.com/page.php?add=" + id,
type: "GET",
timeout: 15000
}).done(function (data) {
$("#list-response-" + id).html(data).show();
}).fail(function (xhr, ajaxOptions, thrownError) {
$("#list-response-" + id).html('ERROR').show();
}).always(function() {});
$("#list-waiting-" + id).hide();
});
});
});
Another way to accomplish this would be "beforeSend". Just like you have events like "success" and "error", there is a "beforeSend" event:
$.ajax({
url: "the.url.org",
beforeSend: function() {
$("#list-waiting-" + id).show();
//doStuff
},
success: function() {
$("#list-waiting-" + id).hide();
//doOtherStuff
}
})