ajax reading/getting variable sometimes cannot get the exact variable with codeigniter - javascript

I am having a problem in my ajax or i don't know if it is a problem with ajax. I have an ajax code to get a value from label and concat it in my fresh data from database. Everytime i refresh the page, it outputs different. Sometimes it works fine, and sometimes it doesn't.
I am having my trouble in this part :
else {
value = value + "-"+init;
$('#checkID').text(value);
$("#checkID").css('visibility','visible');
}
sometimes it outputs 1-0 and sometimes the output became -0.
I am thinking of var value = $('#clinicID').html(); cannot concat with my -0 where the 1 of the output 1-0 is came from value variable
Here is my ajax full code :
function getcheckupID() {
var init = 0;
var value = $('#clinicID').html();
$.ajax ({
url: siteurl+"myclinic/getcheckID",
type: "GET",
dataType: "JSON",
success: function(data) {
if(data.length>0) {
$('#checkID').text(data[0]['check_up_id']);
$("#checkID").css('visibility','visible');
}
else {
value = value + "-"+init;
$('#checkID').text(value);
$("#checkID").css('visibility','visible');
}
}
})
}
my document ready code:
$(document).ready(function() {
get_clinicID();
show_patients();
checkupme();
});
where checkupme() function got a nested getcheckupID() runtime

I suggested another way to get data in #clinicID that you can use
When you refresh the page, insert your #clinicID like:
<span id="clinicID" data-value="1-0"><span> or whatever data you wanna input.
Then in getcheckupID function you'll call:
function getcheckupID() {
var init = 0;
var value = $('#clinicID').attr("data-value");
// Your code ajax
}
If it still have problem, please check your echo when page generated. Maybe there're not any value to print.
Hope this help.

Related

How to increment skip count until results is found in API?

I have the following api which returns thousands of result: http://xxx/xxx/CarRoutes. The API creator however limits only 50 results to be return at once. Hence, to see get another 50 more results to be returned, "?$skip=50" needs to be used. Also, the api url does not allow to add in any parameters behind.
Now I would like to search for CarRoutes id = 123. How can I auto increment the $skip count until results is found?
Appreciate if it can be done Javascript language.
Current idea I have, which is not efficient.
function getInfo() {
$.ajax({
url: "http://xxx/xxx/CarRoutes?$skip="+skip,
success: function(result) {
var obj = JSON.stringify(result);
var routetimeobj = JSON.parse(obj);
var data = routetimeobj['value'];
var data_filter = data.filter(element => element.CarRoute =="123");
if(data_filter.length==0){
skip+=50;
getInfo();
return;
}
});
};
If you want to follow the pattern you are using in your code, you can add a parameter to your function
function getInfo(skip)
and when you are calling again, call it like this
getInfo(skip + 50);

Reading in view return values ​from the controller AJAX / ASP.NET Update NEW

called by selectbox go into function 'getDepAndMan()',
there is a value taken from the selectbox (works)
calls functions in the controller 'GetDepartmentAndManager' (works)
controller returns value (works)
{Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable<<>f__AnonymousType6<'string, string>>}
Result View: [0] { UserDepartament = "there is value here / string", UserManager = "there is value here / string" }
should go back to ajax and call 'succes: function (employee data)' (works)
should assign values ​​to the fields (doesn't work)
show an alert (work)
show alert with values (doesn't work, show an alert with: undefined undefined)
View:
#(Html
.DevExtreme()
.SelectBox()
.DataSource(d => d
.Mvc()
)
.OnValueChanged("getDepAndMan")
)
#(Html.DevExtreme().TextBox()
.ID("Id_department")
.ReadOnly(true)
)
#(Html.DevExtreme().TextBox()
.ID("Id_manager")
.ReadOnly(true)
)
<script type="text/javascript">
function getDepAndMan() {
var userId = {
nazwaValueId: $("#idName").dxSelectBox("instance").option("value")
};
$.ajax({
url: "#Url.Action("GetDepartmentAndManager", "Uzytkownicy")",
type: "POST",
dataType: "json",
data: {"userId": JSON.stringify(userId)},
cache: false,
success: function (danePracownika) {
$("#Id_department")
.dxTextBox("instance")
.option("value", danePracownika.UserDepartament);
$("#Id_manager")
.dxTextBox("instance")
.option("value", danePracownika.UserManager);
alert(danePracownika.UserDepartament + " " + danePracownika.UserManager);
},
failure: function (error) {
alert(error);
},
error: function (error) {
alert(error);
}
});
}
</script>
Controller:
[HttpPost]
public ActionResult GetDepartmentAndManager(string userId)
{
dynamic serializer = JsonConvert.DeserializeObject<IDictionary>(userId);
var IdCzlowieka = serializer["nazwaValueId"];
int IntIdCzlowieka = Convert.ToInt32(IdCzlowieka);
var danePracownika = _uzytkownicyContext.Uzytkownicy.Where(x => x.Id == IntIdCzlowieka).Select(s => new
{
UserDepartament = s.Departament,
UserManager = s.ManagerLogin
});
return Json(danePracownika);
}
return : //
[0] { UserDepartament = "there is value here / string", UserManager = "there is value here / string" }
EDIT
The question is, what's wrong with the code, why it doesn't work for me?
.
I see that in Your GetDepartmentAndManager You are not using Your passed parameter userID:
var danePracownika = ... .Where(x => x.Id == IntIdCzlowieka)...
should be Where(x => x.Id == userId) instead.
The next thing that came to me is the value You are acctualy getting inside the controller action; based on the JS code I would say that this is not the ID of the employee what You are passing but the stringified object { "nazwaValueId": ... } that in the best case would be handled by the server and You will get the raw string as a value of userId (unless You have defined a IModelBinder class that would handle conversion from stringified { "nazwaValueId": ... } to the value of that field - more on that You can find here).
Oh any by the way - please try to avoid mixing languages. I have a friend in the company which was forced to work with the german project and all their code was written in German - You would DEFINETLY won't be happy working with it. But if this a project made only by PL for PL, that is some kind of acceptable approach I assume.
Also I highly advice You to not use HTTP POST method for getting data. To make long story short there is a convention that GET requests are for getting the data and You can call it as many times You like without affecting the state (było takie mądre słowo na to, ale nie pamiętam ;)) and POST is for saving/modifing data and should always redirect to GET method on return. You can read more about it here.
EDIT:
Ok, for some reason I have found that the call in the current form is sending data not as a body but as a form. I don't know, I don't use jQuery. But here is the reqest:
so I changed the signature of the action to
public ActionResult GetDepartmentAndManager([FromForm]string userId)
to get is started working. Maybe on Your side it is just working fine, I don't know. But what I have found is that while sending the responce to the client we end up with... this:
so as You can see either Ajax or server changed the JSON keys to be kebabCase not PascalCase and that's why You are getting undefined values. Because properties You arereading do not exists. Just check it out: alert(danePracownika.userDepartament + " " + danePracownika.userManager);
UPDATE:
I checked it, it was not server's fault:

How to get a callback on an Ajax function

I am trying to find out if a text file (note) exists on the server.
I want to return "yes" if it does, "no" if it does not.
I am able to get this into an alert successfully (for each of the 7 occurrences) but I want to return it back into the originating html doc so I can use it in future code. I am reading about callbacks on this site, but not sure how to implement it.
I tried adding some callback code to the success function, that I saw in an example elsewhere here but am unsure how to edit my function call:
tmpNoteFileSun is a text string that matches the format of the text files stored on the server.
The function call (there are 7 of these in separate places, 1 for each day of the week):
CheckNoteExist(tmpNoteFileSun);
var DoesTheNoteExist = ""; //code needs to go here that returns noteexists (as in the alert below).
I tried changing the above to:
var DoesTheNoteExist = CheckNoteExist(tmpNoteFileSun);
console.log("Does Note Exist " + DoesTheNoteExist);
But get undefined in the console.
The Ajax Function:
function CheckNoteExist(ThisNoteName, callback) {
var NoteFileName = ThisNoteName;
// Ajax to call an external php file, pass the notes filename to it and check if the file
// exists. If it does, change noteexists variable to Yes", else it is "no".
$.ajax({
url: 'ajaxfile_note_exists.php',
type: 'GET',
data: {NoteFileName: NoteFileName},
success: function(noteexists) {
alert("Does the note exist: " + noteexists);
callback && callback(noteexists);
}
});
}
The external PHP file:
$filename = "upload/" . $_GET['NoteFileName'];
if (file_exists($filename)) {
$noteexists = "yes";
}
else {
$noteexists = "no";
}
echo $noteexists;
?>
You're not using the callback, that's what it's there for.
CheckNoteExist(ThisNoteName, val => console.log("Does Not Exist " + val));
See also How do I return the response from an asynchronous call? and Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference

Interrupting an looping function

I trigger the following function when a tooltip is clicked. It is an ajax poll.
There can be many tooltips on the page, and more than one can need access to the data retrieved from the server.
What I want to achieve is to have this poll running as one instance - so if the user clicks a different tooltip the polling stops, rather than being duplicated.
Would be grateful if you could help.
Thanks
function doConversationsAjaxLongPoll(tablename){
clientSubmit = new Object;
// HERE WE'RE GOING TO GET A LIST OF THE ROWIDS THAT WE NEED TO POLL FOR, MAKE AN OBJECT OUT OF THEM. DO THIS BY LOOKING AT WHICH //TOOLIPS HAVE CLASS OPEN
var tooltips = [];
$('.tooltipOpen').each(function(index){
tooltips.push($(this).data('idrow'))
})
console.log("tooltips length: " + tooltips.length)
if(tooltips.length==0){
// console.log("tooltip length is 0 so we're returning false")
return false
}
clientSubmit.OpenConversations = tooltips
clientSubmit.tablename = tablename
clientSubmit.CurrentData = $('body').data('conversations')
console.log(clientSubmit)
$.ajax({
type: 'POST',
url: '/conversations.php?loadNew=1',
data: clientSubmit,
timeout: 25000,
success: function(data){
console.log('success')
data=JSON.parse(data)
console.log(data)
$('body').data('conversations', data)
},
complete: function(status, jqXHR){
if(tooltips.length==0){
// console.log("tooltip length is 0 so we're returning false")
return false
}
else
{
doConversationsAjaxLongPoll(tablename);
}
}
});
updateConversations()
}
I don't doubt that there are faaaar better ways of doing this but I have worked around the problem by having a random number generated by the click function, stored in $('body').data('random') which is then passed to the poll function. When the poll function loops it checks if the random number it was passed matches the one in data-random and returns false if it doesn't.

return HTML/JSON with a normal JS function that contains a jQuery AJAX call?

I know this "technically" can't be done as AJAX is async, but an app I'm working on has a lot of AJAX API calls and I'm trying to make this extendable for future front-end devs.
I know you can just nest everything in callbacks, but that'd be super ugly and not to mention the next dev coming along wanting to extend it wont know what to do.
So, for example, here is my code (that, of course, doesn't work and just returns undefined, but here for an example of how i'd like it to logically work):
var getCategories = function(type){
var categories;
$.get('/api/categories/all',function(json){
if(type == 'html'){
categories = '';
for(x in json.data){
categories=categories+'<option id="category_'+json.data[x].category_id+'" title="'+json.data[x].description+'">'+json.data[x].category+'</option>'
}
}
else{ //JSON
categories = json.data;
}
return categories;
});
}
And later on a dev might want to use it in this way:
$('div').html('<select>'+getCategories('html')+'</select>');
How could I make this work like that? Can I with some JS trick or would every function I make like this HAVE to have a callback like, getCategories('html',function(){})?
If it's everything needs a callback, do you have any tips on making a mostly JS app w/ lots of AJAX calls easily extendable?
UPDATE
As per request, this would be a pain in the ass for a developer if he wanted to do something with, lets say, tags, categories, and posts:
//Some event on click
$('.button').click(function(){
$.ajax({
url: "/api/categories/all",
success: function(json){
categories = '';
for(x in json.data){
categories=categories+'<option id="category_'+json.data[x].category_id+'" title="'+json.data[x].description+'">'+json.data[x].category+'</option>'
}
$.ajax({
url: "/api/tags/all",
success: function(json){
tags = '';
for(x in json.data){
tags=tags+'<option id="tags_'+json.data[x].category_id+'" title="'+json.data[x].description+'">'+json.data[x].category+'</option>'
}
$.ajax({
url: "/api/posts/all",
success: function(json){
posts = '';
for(x in json.data){
posts=posts+'<option id="posts_'+json.data[x].category_id+'" title="'+json.data[x].description+'">'+json.data[x].category+'</option>'
}
//And so on...
//after getting all this data that the developer might want
//to put this in a modal to edit these items...
}
});
}
});
}
});
});
//On load tho, on the same page, he might want to list "popular" categories, tags, all, and he'd
//have to copy and paste the above code but change, all to popular
//Im looking to make a JS API almost to make this simpler, LIKE:
var tags = goGet('tags','popular');
var categories = gotGet('categoties','all');
//etc
Regarding your examples.
You have three ajax requests in the code and none of them are dependent on each other. So, no reason to execute them sequentially.
As for goGet, it can also take callback easily.
goGet('tags','popular', function(tags) {
// do something with tags
});
If you want to execute code after all data loaded, you can use counter inside.
var tags, categories;
var completed = 0;
goGet('tags','popular', function(entities) {
tags = entities;
completed++;
if (++completed == NUMBER_OF_REQUESTS) {
// execute your code
}
});
goGet('categories','popular', function(entities) {
tags = entities;
completed++;
if (++completed == NUMBER_OF_REQUESTS) {
// execute your code
}
});
You can generalize this callback function, to not declare it multiple times.
A bit simpler: fetch data sequentially.
goGet('tags','popular', function(tags) {
goGet('categories','popular', function(categories) {
// execute your code
});
});

Categories

Resources