This is my layout
I want to update in relativaly "real-time" let's say every 10 seconds or so... the badge that says approved will say the getStatus()
My problem is that i need to fetch data from a List and I have no idea how to send all this data to the JavaScript file.
runningContainers is a List and i need to get runningContainers.getName() and runningContainer.getStatus() for every one in the list and send it to the javascript.
I just need a way to pass all the data to the javascript so I can update the badges relativally to that name.
Java
try {
DockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder()
.withDockerHost("tcp://localhost:2375")
.withDockerConfig("/")
//.withRegistryUsername("profile")
//.withRegistryPassword("profile")
.build();
DockerClient dockerClient = DockerClientBuilder.getInstance(config).build();
List<Container> runningContainers = dockerClient.listContainersCmd()
.exec();
JavaScript
$.ajax({
type: 'post',
url: 'Containers',
success: function () {
},
error: function() {
}
});
});
Related
I'll preface this with I'm still new to JavaScript. So problem is in a larger application, our controller is passing in a list of information to the view where certain JavaScript functions rely on certain ViewModel properties. I've written a simple application to hopefully illustrate what I'm getting at.
Below is a sample controller that's passing in List to the Index page:
public ActionResult Index() {
List<int> activeIds = new List<int>();
SqlConnection sqlConn = new SqlConnection(connection_String);
sqlConn.Open();
string sqlStr = "SELECT * FROM dbo.[JS-Test] WHERE Active = 1";
SqlCommand sqlCmd = new SqlCommand(sqlStr, sqlConn);
SqlDataReader sqlDR = sqlCmd.ExecuteReader();
if(sqlDR.HasRows) {
while (sqlDR.Read()) {
activeIds.Add((int)sqlDR["ID"]);
}
}
sqlDR.Close();
sqlCmd.Dispose();
sqlConn.Close();
return View(activeIds);
}
This returns the current "active" items in the database. The (rough) view is as follows...
#model List<int>
#{
ViewBag.Title = "Index";
}
<p>Current Recognized Count: #Model.Count() </p>
Print
<script>
$(document).ready(function () {
$('#printBtn').click(function () {
var numberOfActiveIds = #Model.Count();
$.ajax({
type: "POST",
url: "/Home/PostResults",
data: { ids: numberOfActiveIds},
success: function (results) {
if(results == "Success") {
window.location.href = '/Home/Results';
}
}
});
});
});
</script>
The issue is getting the current number of active items from the database when the button is clicked. Let's say that the user remains idle on the page after it loads for a few minutes. When their page originally loaded, the model returned 5 items listed as active... but while they've been waiting 3 additional items were switched to active in the database for a total of 8. However, when the user finally clicks the button it'll submit 5 items instead of the current 8.
I'm unable to run the query to get the current number of active items in the "/Home/PostResults" ActionResult due to the nature of how the larger application is set up. Is there a way I could refresh the page (getting the updated model) before the rest of the function carries out using values of the refreshed model?
If you have any additional questions, please let me know and I will gladly comply. I've looked at other questions and answers on SO but I haven't found one that quite works for my situation. Thanks!
Edit #1
So, I've added this function to the Home controller which just returns the list count as Json.
public ActionResult GetIds(){
List<int> activeIds = new List<int>();
SqlConnection sqlConn = new SqlConnection(connection_String);
sqlConn.Open();
string sqlStr = "SELECT * FROM dbo.[JS-Test] WHERE Active = 1";
SqlCommand sqlCmd = new SqlCommand(sqlStr, sqlConn);
SqlDataReader sqlDR = sqlCmd.ExecuteReader();
if (sqlDR.HasRows) {
while (sqlDR.Read()) {
activeIds.Add((int)sqlDR["ID"]);
}
}
sqlDR.Close();
sqlCmd.Dispose();
sqlConn.Close();
return Json(activeIds.Count());
}
The view script now looks like this...
<script>
$(document).ready(function () {
$('#printBtn').click(function () {
var numberOfActiveIds = #Model.Count();
$.ajax({
type: "GET",
url: "/Home/GetIds",
success: function(response) {
numberOfActiveIds = response;
$.ajax({
type: "POST",
url: "/Home/PostResults",
data: { ids: numberOfActiveIds},
success: function (results) {
if(results == "Success") {
window.location.href = '/Home/Results';
}
}
});
}
});
});
});
</script>
I'm currently getting the following error...
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
Edit #2
I had to set the JsonRequestBehavior to AllowGet for it to work properly. Thanks again, everyone!
gforce301 mentioned to GET the current actives via an ajax call to an additional, separate method making the query to the database and THEN ajax post the returned "actives". Is that possible?
Yes this is possible. That's why I mentioned it. Irregardless of other peoples opinions on how they think you should do this, I understand that you may be limited on why you can't do it their way even if they don't.
The code below is a restructuring of your code. It chains 2 ajax calls together, with the second one depending on the success of the first. Notice the comment block in the success handler of the first ajax call. Since I don't know what the response will be, I can't fill in the part on how to use it. This accomplishes your goal of having the user only make a single button click.
<script>
$(document).ready(function () {
$('#printBtn').click(function () {
var numberOfActiveIds = #Model.Count();
$.ajax({
type: 'GET',
url: '/path/to/get/activeIds',
success: function(response) {
/*
Since I don't know the structure of response
I have to just explain.
use response to populate numberOfActiveIds
now we just make our post ajax request.
*/
$.ajax({
type: "POST",
url: "/Home/PostResults",
data: { ids: numberOfActiveIds},
success: function (results) {
if(results == "Success") {
window.location.href = '/Home/Results';
}
}
});
}
});
});
});
</script>
I can give you an idea, i hope it can help,
run another ajax 1st on btnclick to get the data(or datat count) again, if the record count is greater then current then update the view and don't PostResults and if its same then just PostResults
on ajax success you can reload the data or view
and on failure(when no new record) just do PostResults
I am desperately trying to submit multiple POST variables via AJAX, but just cant get manage to get the formatting right... Problem is that I have both a hardcoded / written action=problem_lookup variable and a dynamic field input as $(this).val and just cant manage to get both into one data string...
this works well:
data: 'problem=' + $(this).val(),
This does not:
data: { action: 'problem_lookup' , problem: $("problem").val() },
data: { action: 'problem_lookup' , problem: $(this).val() },
data: { action: problem_lookup, problem: $(this).val() },
I tried numerous formats from other threads and looked at the official jquery manual, but cant seem to get this figured out. Any help is appreciated.
EDIT:
full script below, tried the solutions posted so far but no success. $("problem") is a <select> field (with Select2 running) hence shouldnt cause me so much frustration, especially since the original approach with data: 'problem=' + $(this).val(), works fine.
$(function () {
$('#problem').change(function () { // on change in field "problem"
var data = {
action: 'problem_lookup',
problem: $("problem").val()
}
$.ajax({ // launch AJAX connection
type: 'POST', // via protocol POST
url: 'ajax.php',
//data: 'problem=' + $(this).val(), // send $_POST string
//data:"{'action':'"+action+"','problem':'"+$(this).val()+"'}",
//data:"{'action':'problem_lookup','problem':'"+$(this).val()+"'}",
//data: { action: 'problem_lookup' , problem: $("problem").val() },
//data : data_string,
data: $.param(data),
dataType: 'json', // encode with JSON
success: function (data)
{
// do something
},
});
});
});
An issue is in the
$("problem")
Jquery call.
If.problem is a css class try with
$(".problem")
if problem is a css id try with
$("#problem")
For posting arrays of object you can build data as an object containing arrays, changing a little bit your structure. Something like this
Var obj={};
obj.postData=[];
obj.postData.push(/*your first object here*/);
...
obj.postData.push(/*your n-th object here*/);
$.ajax({
.....
data:obj;
......
});
Try the FormData() FormData.
var data = new FormData();
data.append('action', value);
...
You need to specify your data variable first like this:
var data = {
action: 'problem_lookup',
problem: $("problem").val()
}
In AJAX serialize your data using $.param,
data: $.param(data),
Note: Twice check if $("problem").val() is correct. If problem is a class, you need to specify like this $(".problem").val() or if it is ID, $("#problem").val()
i have been able to fetch data with an ajax call from active directory .
the php file used to make the ajax call to active directory :http://pastebin.com/tSRxwQL8
The browser console shows that an ajax call returns this :
<p> sn: xxxxxx<br/>givenname: xxxxx<br/>
employeeID: 0050<br/
>distinguishedName: CN=xxxx xxxxx,OU=Employees,OU=Accounts,OU=India,DC=asia,DC=xxxxxxx,DC=com<br/>
displayName: Mark Hewettk<br/>sAMAccountName: xxxxxxx<br/>
department: xxxxx<br/>manager: CN=xxxxxx xxxxxxx,OU=Employees,OU=Accounts,OU=India,DC=asia,DC=xxxx,DC=com
<br/>
mail: mhewettk#abc.com<br/>
title: xyz<br/>
I want to take only some attributes above like mail,displayname etc and display in my HTML :
<h2 class="profile__name" id="emailOfUser">Email : </h2>
Now the problem is the jquery that I have used here :
$('.leaderboard li').on('click', function() {
$.ajax({
url: "../popupData/activedirectory.php", // your script above a little adjusted
type: "POST",
data: {
id: $(this).find('.parent-div').data('name')
},
success: function(data) {
console.log(data);
$('#popup').fadeIn();
$('#emailOfUser').html(data); //this line displays all data whereas I want to select only email,displayname from the above console data
//whatever you want to fetch ......
// etc ..
},
error: function() {
alert('failed, possible script does not exist');
}
});
});
problem is this :
$('#emailOfUser').html(data);
this line displays all data whereas I want to select only email,displayname from the above console data
kindly help me how to select only desired attribute data from the above browser console data.
Ideally you should return JSON from PHP file, however if it is not possible for you to make changes to PHP file then you can use split("mail:") and split("title:") to extract data
success: function(data) {
console.log(data);
$('#popup').fadeIn();
var email=(data.split("mail:")[1]).split("title:")[0];
$('#emailOfUser').html(email); //this line displays all data whereas I want to select only email,displayname from the above console data
//whatever you want to fetch ......
// etc ..
},
You are getting response in HTML which makes difficult for you to extract mail, displayname, etc.
You should get the response in JSON which will make it easy for you to extract the required info.
Ask your back-end team to send response in JSON format.
Working Fiddle
Try :
var lines = 'sn: xxxxxx<br/>givenname: xxxxx<br/>employeeID: 0050<br/>distinguishedName: CN=xxxxxxxxx,OU=Employees,OU=Accounts,OU=India,DC=asia,DC=xxxxxxx,DC=com<br/>displayName: Mark Hewettk<br/>sAMAccountName: xxxxxxx<br/>department: xxxxx<br/>manager: CN=xxxxxx xxxxxxx,OU=Employees,OU=Accounts,OU=India,DC=asia,DC=xxxx,DC=com<br/>mail:mhewettk#abc.com<br/>title:xyz<br/>'.split('<br/>');
jQuery.each(lines, function() {
var val = this;
if (val.indexOf('mail') > -1)
// alert(val.split(':')[1]); //Only for test
$('#emailOfUser').html(val.split(':')[1]);
});
I'm working on project that simulates Twitter and I'm using HTML + JS on client and WCF services on server side (ajax calls), and Neo4J as database.
For example:
in $(document).ready(function ()
there is DisplayTweets service call -> DisplayTweets(username)
function DisplayTweets(userName) {
$.ajax(
{
type: "GET", //GET or POST or PUT or DELETE verb
url: "Service.svc/DisplayTweets", // Location of the service
data: { userName: userName },
contentType: "application/json; charset=utf-8", // content type sent to server
dataType: "json",
processdata: true, //True or False
success: function (msg) //On Successfull service call
{
DisplayTweetsSucceeded(msg);
},
error: function () // When Service call fails
{
alert("DISPLAY TWEETS ERROR");
}
}
);
}
and then DisplayTweetsSucceeded(msg) where msg would be json array of users tweets
function DisplayTweetsSucceeded(result)
{
for (var i = 0; i < result.length; i++)
{
var tweet = JSON.parse(result[i]);
var id_tweet = tweet.id;
var content_tweet = tweet.content;
var r_count_tweet = tweet.r_count;
NewTweet(null, id_tweet, content_tweet, r_count_tweet);
}
}
Function NewTweet is used for dynamic generating of tweets.
Problem is when I first load html page, nothing shows up, neither when I load it multiple times again. It only shows when I go through Firebug, line by line.
I'm presuming that maybe getting data from database is slower, but I'm not sure and also have no idea how to solve this. Any help will be very much appreciated, thank you in advance!
I am using jQuery to delete some data from database. I want some functionality that when jQuery returns success I want to execute a query. I want to update a another table on success of jQuery without page refresh. Can I do this and if yes how can I do this?
I am newbie to jQuery so please don't mind if it's not a good question for stackoverflow.
This is my script:
<script type="text/javascript">
$(document).ready(function () {
function delete_comment(autoid, btn_primary_ref) {
$.ajax({
url: 'rootbase.php?do=task_manager&element=delete_comment',
type: "POST",
dataType: 'html',
data: {
autoid: autoid
},
success: function (data) {
// I want to execute the Update Query Here
alert("Comment Deleted Successfully");
$(btn_primary_ref).parent().parent().hide();
var first_visible_comment = $(btn_primary_ref).parent().parent().parent().children().find('div:visible:first').eq(0).children('label').text();
if (first_visible_comment == "") {} else {
$(btn_primary_ref).parent().parent().parent().parent().parent().parent().prev().children().text(first_visible_comment);
}
load_comment_function_submit_button(autoid, btn_primary_ref);
},
});
}
$(document).on('click', '.delete_user_comment', function (event) {
var autoid = $(this).attr('id');
var btn_primary_ref = $(this);
var r = confirm("Are you sure to delete a comment");
if (r == true) {
delete_comment(autoid, btn_primary_ref);
} else {
return false;
}
});
});
</script>
You can't do database operations directly in Javascript. What you need to do is to simply make a new AJAX request on success to a php file on the backend to update given table. However this would mean two AJAX requests to the backend, both of which manages database data. Seems a bit unnecessary. Why not just do the update operation after the delete operation in the php file itself?
add a server sided coded page that will execute your query.
example :
lets say you add a page named executequery.php.
with this code:
when you want to execute your query do the following :
$.post("executequery.php",//the URL of the page
{
param1:value1,
param2:value2....//if you want to pass some parameters to the page if not set it to null or {}
},
function(data){
//this is the callback that get executed after the page finished executing the code in it
//the "data" variable contain what the page returened
}
);
PS : tha paramters sent to the page are conidired like $_POST variables in the php page
there is an other solution but its UNSAFE i recomand to NOT use it.
its to send the query with the paramters and that way you can execute the any query with the same page example :
$.post("executequery.php",//the URL of the page
{
query:"insert into table values("
param1:value1,
param2:value2....//if you want to pass some parameters to the page if not set it to null or {}
},
function(data){});