I am trying to check a JSON for the "start" object, and what it value is.
For example, if my AJAX is
$(document).ready(function () {
$.ajax({
url: "Content/events/document.json",
type: "GET",
success: function (resp) {
alert(JSON.stringify(resp)); //Stringify'ed just to see JSON data in alert
},
error: function () {
alert("failed");
}
});
});
and it returns
[
{"title":"Bi-weekly Meeting1","start":"2014-07-09","color":"red"},
{"title":"Bi-weekly Meeting2","start":"2014-08-06","color":"red"},
{"title":"Bi-weekly Meeting3","start":"2014-07-23","color":"red"},
{"title":"Test Event","url":"http://google.com/","start":"2014-07-28"}
]
How can I check every "start" value? and if it is today, store that event in a different array?
I just want to keep track of today's events and I am not sure how to iterate through a JSON Object.
Note you should set dataType: "json" so that JQuery will parse the ajax response coming back as JSON automatically. Then just iterate through the array you receive, like so:
function sameDay( d1, d2 ){
return d1.getUTCFullYear() == d2.getUTCFullYear() &&
d1.getUTCMonth() == d2.getUTCMonth() &&
d1.getUTCDate() == d2.getUTCDate();
}
$(document).ready(function () {
$.ajax({
url: "Content/events/document.json",
type: "GET",
dataType: "json",
success: function (resp) {
resp.forEach(function(item) {
console.log(item.start);
if (sameDay( new Date(item.start), new Date)){
// This one has today's date!
}
});
},
error: function () {
alert("failed");
}
});
});
Related
I would like to ask You for help mi to figure it out, how to use result of first Complete which is giving me a client number as #select_client_id in another autocomplete.
At one page, i'm selecting order from autocomplete list:
$( function() {
$( "#select_order" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "data/orderData.php",
type: 'post',
dataType: "json",
data: {
find_order_out: request.term
},
success: function( data ) {
response( data );
}
});
},
select: function (event, ui) {
$('#select_order').val(ui.item.label); // display the selected text
$('#select_order_id').val(ui.item.value); // save selected id to input
$('#select_client_id').val(ui.item.client_id);
return false;
}
});
});
Then there is another input field which is selecting packages for this order, where i`m using a client id, from first autocomplete:
$("#select_package").autocomplete({
source: function( request, response ) {
$.ajax({
url: "data/orderData.php",
type: 'post',
dataType: "json",
data: {
find_client_package_on_storage: request.term, client: client
},
success: function( data ) {
response( data );
console.log(client);
}
});
},
select: function (event, ui) {
$('.select_package').val(ui.item.label);
$('.select_package_id').val(ui.item.value);
return false;
}
});
For now, i've got only one client, so variable is declared by:
<script>
client="1";
</script>
How can i do it properly? :)
Well, it takes a little bit longer than normally, but it wasn't priory to figure it out :)
Answer is very simple :)
In #select_order autocomplete, i've add:
select: function (event, ui) {
$('#select_order').val(ui.item.label);
$('#select_order_id').val(ui.item.value);
$('#select_client_id').val(ui.item.client_id);
client_number=$("#select_client_id").val();
return false;
And at the end of body set a variable declaration:
<script>
let client_number = 0;
</script>
That solved my problem :)
I have this code where i am trying to retrieve data from model.findall() and display in UI as table
model.js
define(['jquery', 'can'], function ($, can) {
var serviceModel = can.Model.extend({
findAll: function (params,servicename) {
return $.ajax({
type: 'POST',
dataType: 'JSON',
contentType: 'application/json',
url: 'data/+ servicename',
success: function (data) {
console.log("Success ");
},
error: function () {
console.log("Error");
}
});
}
}, {});
return serviceModel;
});
controller.js
serviceModel.findAll(params,"SP_table", function(data) {
if (data.status === "success") {
$('#idtable').dataTable().fnClearTable();
$('#idtable').dataTable().fnAddData(data.result);
}else{
alert("inside alert");
}
});
issue is in serviceModel.findAll() i am unable to get data inside serviceModel.findAll() because data is in the form of stored procedure or macro, which i am getting using "servicename" from function above
please let me know how to resolve this issue.
You can access the raw xhr data from the ajax call and convert it to an appropriate format by overriding the parseModels method:
https://canjs.com/docs/can.Model.parseModels.html
Overwriting parseModels If your service returns data like:
{ thingsToDo: [{name: "dishes", id: 5}] } You will want to overwrite
parseModels to pass the models what it expects like:
Task = can.Model.extend({ parseModels: function(data){ return
data.thingsToDo; } },{}); You could also do this like:
Task = can.Model.extend({ parseModels: "thingsToDo" },{});
can.Model.models passes each instance's data to can.Model.model to
create the individual instances.
In their example above, the response is a nested JSON: in yours, it is your procedure or macro. You have the opportunity here in parseModels to rewrite the response in the appropriate format.
Edit: could've researched better... reading this post now: How do I return the response from an asynchronous call?
I have an ajax request which returns JSON data. When I watch it in fiddler, it does go out to the service and get the JSON data, but when I try to set a variable to it's response, that variable is "undefined". If I alert in the success method, it alerts, but the variable is still undefined.
I tried changing the function(data) to function(something) incase that had anything to do with it... same story.
var returndata
$.ajax({
type: "GET",
url: "GetSecurables/",
data: { etaNumber: etaNumber },
success: function (data) {
returndata = data; //undefined
alert('haaalp');
}
});
The JSON is like below
[
{
"DelegateSid":null,
"DisplayName":"Tom",
"HasDelegation":true,
"HasEtaManagement":false
},
{
"DelegateSid":null,
"DisplayName":"Tim",
"HasDelegation":true,
"HasEtaManagement":false
},
{
"DelegateSid":null,
"DisplayName":"Jake",
"HasDelegation":true,
"HasEtaManagement":false
},
{
"DelegateSid":null,
"DisplayName":"Ryan",
"HasDelegation":true,
"HasEtaManagement":false
}
]
Try:
var returndata;
$.ajax({
type: "GET",
url: "GetSecurables/",
data: { etaNumber: etaNumber },
success: function (data) {
console.log(data);
returndata = data;
console.log(returndata);
}
});
If the 2 outputs are the same it might be the case that you're trying to access returndata from outside its scope, hence the undefined, or that you're accessing returndata before the Ajax call completes.
I have two function of jQuery. Both the functions are calling jQuery ajax.
both have property async: false.
In both the function I am redirecting on basis of some ajax response condition.
In the success of first function I am calling the another function and then redirecting to another page. But my first function is not redirecting because my second function is not waiting of the response of the first function.
Hope problem is clear from my question.
my first function is as below
function fnGetCustomer() {
function a(a) {
$("#loading").hide();
//on some condition
//other wise no redirection
self.location = a;
}
var b = $("input#ucLeftPanel_txtMobile").val();
"" != b && ($("#loading").show(), $.ajax({
type: "POST",
url: "Services/GetCustomer.ashx",
data: { "CustMobile": b },
success: a,
async: false,
error: function () {
$("#loading").hide();
}
}));
}
and my second function I am calling the first function
function fnSecond() {
$.ajax({
type: "POST",
url: "some url",
async: false,
data: { "CustMobile": b },
success: function(){
fnGetCustomer();
//if it has all ready redirected then do not redirect
// or redirect to some other place
},
error: function () {
$("#loading").hide();
}
}));
}
I am using my first function all ready. So I don't want to change my first function.
A set up like this should work;
$.ajax({
data: foo,
url: bar
}).done(function(response) {
if (response == "redirect") {
// redirect to some page
} else {
$.ajax({
data: foo,
url: bar
}).done(function(response2) {
if (response2 == "redirect") {
// redirect to some other page
} else {
// do something else
}
});
}
});
I've not tested doing something like this, but that's roughly how I'd start off
If you don't need the result of the first AJAX call to be able to send the second you could add a counter to keep track of the calls. Since you can send both calls at the same time it'll be a lot more responsive.
var requestsLeft = 2;
$.ajax({
url: "Firsturl.ashx",
success: successFunction
});
$.ajax({
url: "Secondurl.ashx",
success: successFunction
});
function successFunction()
{
requestsLeft--;
if (requestsLeft == 0)
doRedirectOrWhatever();
}
If you absolutely need to do them in order you could do something like this. My example expects a json response but that's no requirement for this approach to work.
var ajaxurls = ["Firsturl.ashx", "Secondurl.ashx"]
function doAjax()
{
$.ajax({
url: ajaxurls.shift(), // Get next url
dataType: 'json',
success: function(result)
{
if (result.redirectUrl) // or whatever requirement you set
/* redirect code goes here */
else if (ajaxurls.length>0) // If there are urls left, run next request
doAjax();
}
});
}
doAjax();
how come when I send ajax request like this everything works
$(".btnDeleteSong").click(function () {
var songId = $(this).attr('name');
$.ajax({
type: 'POST',
url: "/Home/DeleteSong/",
data: { id: songId },
success: ShowMsg("Song deleted successfully"),
error: ShowMsg("There was an error therefore song could not be deleted, please try again"),
dataType: "json"
});
});
But when I add the anonymous function to the success It always showes me the error message although the song is still deleted
$(".btnDeleteSong").click(function () {
var songId = $(this).attr('name');
$.ajax({
type: 'POST',
url: "/Home/DeleteSong/",
data: { id: songId },
success: function () { ShowMsg("Song deleted successfully"); },
error: function () {
ShowMsg("There was an error therefore song could not be deleted, please try again");
},
dataType: "json"
});
});
what if i wanted few things on success of the ajax call, I need to be able to use the anonymous function and I know that's how it should be done, but what am I doing wrong?
I want the success message to show not the error one.
function ShowMsg(parameter) {
$("#msg").find("span").replaceWith(parameter);
$("#msg").css("display", "inline");
$("#msg").fadeOut(2000);
return false;
}
Make sure your action is returning Json data.
"json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)
http://api.jquery.com/jQuery.ajax/
Your action method should surely return Json data. I have the similar code see if that helps.
public ActionResult GetAllByFilter(Student student)
{
return Json(new { data = this.RenderPartialViewToString("PartialStudentList", _studentViewModel.GetBySearchFilter(student).ToList()) });
}
$("#btnSearch").live('click',function () {
var student = {
Name: $("#txtSearchByName").val(),
CourseID: $("#txtSearchByCourseID").val()
};
$.ajax({
url: '/StudentRep/GetAllByFilter',
type: "POST",
data: JSON.stringify(student),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(result) {
$("#dialog-modal").dialog("close");
RefreshPartialView(result.data);
}
, error: function() { alert('some error occured!!'); }
});
});
Above code is used to reload a partial view. in your case it should be straight forward.
Thanks,
Praveen