How to temporary replace div content with another - javascript

So the question is in the title. How can I replace one div content with another content for some little time using jQuery? I just have one block with user information that invisible (has display: none; in styles and while info is retrieveing from server I want to display message like Loading user info....
EDIT
Here is how I retrieve information from server:
$.post("/getUserAdditionalInfo",
{ "id": pId },
function (data) {
window.user = $.extend(
{
"pid": pId,
"secondname": data.sname,
"firstname": data.fname,
"middlename": data.mname
}, existingParams);
updateUserInformationLabels();
},
"json"
);
EDIT2
Here is the code I have for user info:
<div id="UserAdditionalInfo">
<ul class="info">
<li><b>First name:</b><span id="ExInfoWorkFirstName"></span></li>
<li><b>Second name:</b><span id="ExInfoWorkSecondName"></span></li>
<li><b>Middle name:</b><span id="ExInfoWorkMiddleName"></span></li>
</ul>
</div>
And I just want to temporarely replace div with id = UserAdditionalInfo with 'loading user info' string. And then data is completely retrieved I need to restore initial content (along replacing place holders with data).

You could do...
$('div:first').html('Loading user info...').load('something.php');

store the original html in a variable like this-
var originalHTMl = $('#UserAdditionalInfo').html();
then replace the content of this div with loading info like this..
$('#UserAdditionalInfo').html('Loading user info...').show();
$.post("/getUserAdditionalInfo",
{ "id": pId },
function (data) {
window.user = $.extend(
{
"pid": pId,
"secondname": data.sname,
"firstname": data.fname,
"middlename": data.mname
}, existingParams);
updateUserInformationLabels(originalHTMl);//pass the original html to this function
var updatedHTML = $('#UserAdditionalInfo').html();// get the updated HTMl
$('#UserAdditionalInfo').html(updatedHTML).show();//Show the div..now this div has all updated htnl
},
"json"
);
function updateUserInformationLabels(originalHTMl){
if (typeof window.patient != 'undefined') {
var ExInfoWork = $(originalHTMl).find('#ExInfoWork');
ExInfoWork.html(window.patient.work);
}
// more replacement logic as you said
}
// don't return anything
}

If You are using jQuery.ajax(), then this is the way :
$.ajax({
beforeSend: function() {
// Replace with "loading..."
},
complete: function() {
// Replace with result
},
});

Related

Zoomchart net chart form links issue

I'm using the Zoomchart library's NetChart class to form netchart. But I'm facing issue with links. And not able to find any solution.
Below is the case which I want to achieve:-
Let suppose we have two nodes A and B. Here A is the seller and B is the buyer.
Seller A -> B
Buyer B -> A
I'm loading data dynamically. And when we initially loading A then we are getting B as Buyer of A. And this forms a link like A -> B. But when B loads its related data then it is getting A as it is buying data from it(A).
And this form two link nodes:-
{
"from": "A",
"to": "B"
}
{
"from": "B",
"to": "A"
}
It is creating a chart like this:-
But it should be a single link. Below is the code:-
this.chartObject = new NetChart({
container: document.getElementById('sellerBuyersLinkingChart'),
area: { height: null },
navigation:{
focusNodeExpansionRadius: 1,
initialNodes: ["n-1"],
mode:"focusnodes"
},
data: {
dataFunction: (nodeList, success, error) => {
$.ajax({
url:url+'?nodes='+nodeList.toString(),
success: (response, textStatus, jqXHR) => {
success(response, textStatus, jqXHR);
},
error: error
});
},
requestMaxUnits: 1
},
style: {
nodeStyleFunction: (node) => {
},
linkStyleFunction: (link) => {
let type = link.data['extra']['type'];
if(type == 'sellers') {
link['fromDecoration'] = "arrow";
link['fillColor'] = "rgba(47,195,47,0.8)";
link['direction'] = "L";
} else {
link['toDecoration'] = "arrow";
link['fillColor'] = "rgba(236,46,46,0.8)";
link['direction'] = "R";
}
},
nodeFocused: {
fillColor: 'rgba(232,189,43,1)'
}
}
});
Expectations: Is there any way that I can send to link id with URL. With that way, I can remove the same node from the link.
This chart should create nodes like this:-
1) You can use multiLinkProcessor to combine multiple links if they are not unique
2) If you add unique id to links, then you can update, remove or manipulate them individually (in fact it's recommended to always add id for links and nodes and that will prevent duplicates). Not having ids will prompt notice in console log as well.

AngularJS select default option according to url

I have a dropdown menu that contains some links for various section of the page. The application is written with AngularJS version 1.4, the dropdown menu does works, but when I enter the page directly through the url in the dropdown menu is always selected the empty voice instead of the correct one. Here' the code:
HTML
<select ng-options="menu_voice.name for menu_voice in menu_voices track by menu_voice.url" ng-model='selectedOption' ng-change="changeLink()">
</select>
JS:
$scope.changeLink = function(){
$state.go($scope.selectedOption.url);
};
$scope.menu_voices = [
{
"url": 'account.company',
"name": 'Company'
},
{
"url": 'account.billing',
"name": 'Billing'
},
{
"url": 'account.password',
"name": 'Password'
},
{
"url": 'account.design',
"name": 'Design'
},
{
"url": 'account.social',
"name": 'Social'
},
{
"url": 'account.notifications',
"name": 'Notifications'
}
];
If I select a voice in the dropdown menu, I go to the correct link with the correct voice selected. But if in the url bar I enter something like:
www.myapp.com/account/billing
I go to the correct page but in the dropdown menu the selected voice is empty.
How can I solve this?
EDIT after first reply:
I added this:
var name = $window.location.pathname;
name = name.substring(9);
name = name.charAt(0).toUpperCase() + name.slice(1);
var url = $window.location.pathname.substring(1).replace(/\//g, '.');
$scope.getSelectedFromUrl = function(){
$scope.selectedOption = {"name": name, "url": url};
};
If I print in the console
console.log($scope.selectedOption);
I get the correct object, e.g:
Object {name: "Design", url: "account.design"}
In the html I simply added the ng-init:
<select ng-options="menu_voice.name for menu_voice in menu_voices track by menu_voice.url" ng-model='selectedOption' ng-change="changeLink()" ng-init="selectedOption = getSelectedFromUrl()">
</select>
But nothing changed.
You could use the ng-init directive to call a function that parses the route and matches it to an item from the voices array. Then set the selectedOption model to that array item, which will set the select option.
ng-init="selectedOption = getSelectedFromURL()"

Swapping data in Angular UI-Grid, new columns not visible when changing dataset externally

I've got a query tool I've been working on, which has an angular form that is filled out, and then when it's submitted it uses AJAX which returns JSON, which is then rendered into ui-grid, that JSON response looks like
{
"success": true,
"message": "",
"columns": ["first_name", "last_name", "company", "employed"]
"results": [
{first_name: "John", last_name: "Smith", company: "Abc Inc", employed: true},
{first_name: "Johnny", last_name: "Rocket", company: "Abc Inc", employed: true}]
}
I'm working on both the PHP and angular so I have full control over this JSON response if need be. I'm running into an issue when my JSON response from a first AJAX call is rendered, and then I run another, seperate AJAX call on the same page and get a new data set: this new data set does not render any of the columns that were not in the original data set. This is hugely problematic as the table is essentially cleared when none of the columns are the same, and I often need to load completely different data into ui-grid in this single page app.
When the JSON is recieved I simply bind the jsonResult.results to the old $scope.myData variable that ui-grid is bound to.
I've made a plunker isolating this issue. A dataset with a "punk" column is loaded, and then clicking "swap data" will try to load a dataset with "employee" column instead of "punk". I've so far looked into directives that will refresh or reload when the $scope.myData variable changes using $watch, and looked at finding something like $scope.columnDefs to let ui-grid know. Relatively new to angular and javascript so directives are still a bit over my head.
I have updated your plunker slightly:
$scope.swapData = function() {
if ($scope.gridOpts.data === data1) {
$scope.gridOpts.columnDefs = [
{ name:'firstName' },
{ name:'lastName' },
{ name:'company' },
{ name:'employee' }
];
$scope.gridOpts.data = data2;
//punk column changes to employee
}
else {
$scope.gridOpts.columnDefs = [
{ name:'firstName' },
{ name:'lastName' },
{ name:'company' },
{ name:'punk' }
];
$scope.gridOpts.data = data1;
//employee column changes to punk
}
};
http://plnkr.co/edit/OFt86knctJxcbtf2MwYI?p=preview
Since you have the columns in your json, it should be fairly easy to do.
One additional piece that I figured out with the help of Kevin Sage's answer and the plunker example... If you are using the backward-compatible "field" attribute the swapping does not work properly when there are field name overlaps between the two sets of column definitions. The column headers and the column widths are not rendered properly in this case. Using the "name" attribute of the column definition corrects this.
$scope.swapData = function() {
if ($scope.gridOpts.data === data1) {
$scope.gridOpts.columnDefs = [
{ field:'firstName' },
{ field:'lastName' },
{ field:'company' },
{ field:'employee' }
];
$scope.gridOpts.data = data2;
//punk column changes to employee
}
else {
$scope.gridOpts.columnDefs = [
{ field:'firstName' },
{ field:'lastName' },
{ field:'company' },
{ field:'punk' }
];
$scope.gridOpts.data = data1;
//employee column changes to punk
}
};
Example here: Plunker
My solution:
$http.get('url').success(function(res) {
// clear data
gridOptions.data.length = 0;
// update data in next digest
$timeout(function() {
gridOptions.data = res;
});
});

How to create complex javascript object for JSON API

Below is the structure of JSON which I use to query an API
"order_items": [
{
"menu_item_id": "VD1PIEBIIG",
"menu_item_name": "Create Your Own",
"modifiers": [
{
"modifier_id": "6HEK9TXSBQ",
"modifier_name": "Shrimp"
}
],
"quantity": "1",
"total": 15.99,
"variant_id": "TXDOR7S83E",
"variant_name": "X-Lg 18\""
}
]
Now I want to call this API from an HTML page using Javascript(Using HTML elements like forms and drop down menus etc). I want to create a Javascript object with proper structure and then convert it to JSON using "stringify" function. But I am not able to create the Javascript object. Can anyone help with this?
Like i want to have the following structure
obj.order_items[0].menu_item_id="VD1PIEBIIG";
obj.order_items[0].menu_item_name="Create Your Own";
obj.order_items[0].modifiers[0].modifier_id="6HEK9TXSBQ";
and so on.
var jsonToSend = { "order_items": [ ] };
// then for each order item
var orderItem = { "menu_item_id": <whatever>,
"menu_item_name": <whatever>,
"quantity": <whatever>,
"total": <whatever>,
"variant_id": <whatever>,
"variant_name": <whatever>,
"modifiers": []
};
// then for each modifier
var modifier = { "modifier_id": <whatever>, "modifier_name": <whatever> };
orderItem.modifiers.push(modifier);
jsonToSend.order_items.push(orderItem);
JSON.stringify(jsonToSend);
Well there are a couple of ways to do this.
Manually create the Json object to send from the HTML elements:
$.ajax({
type: "POST",
url: "some.php",
data: new {"order_items": [
{
"total": $('total').Val(),
"variant_id": $('variant_id').Val(),
"variant_name": $('variant_name').Val()
}
]})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
You could use a great framework like KnockoutJs, this will keep your JSON object up to date with your form, so that you don't have to do it manually. When you are ready you just submit your original json back to the server.
See this basic example on JsFiddle
var ClickCounterViewModel = function() {
this.numberOfClicks = ko.observable(0);
this.registerClick = function() {
this.numberOfClicks(this.numberOfClicks() + 1);
};
this.resetClicks = function() {
this.numberOfClicks(0);
};
this.hasClickedTooManyTimes = ko.computed(function() {
return this.numberOfClicks() >= 3;
}, this);
};
ko.applyBindings(new ClickCounterViewModel());
You can use any number of plugins to Serialize the form, but the problem is getting the JSON structure just right.
See SerializeArray
$( "form" ).submit(function( event ) {
console.log( $( this ).serializeArray() );
event.preventDefault();
});

Create dynamic pages from Json, in Dojo

I have a json file
{
Introduction:
[
{
title: "Introduction",
toolbar: "Page 1",
content: "cont, aabitant morbi tristique..."
},
{
title: "about",
toolbar: "Page 2",
content: "contesent vel nisi ipsum..."
},
{
title: "services",
toolbar: "Page 3",
content: "Cras adipiscing sapien nec..."
}
]
}
I want to create dynamic pages in Dojo mobile. From the above Json three pages will be created with moving back and forward. I am getting problems. I am reading Json as:
dojo.xhrPost({
url: "start.json",
handleAs: "json",
var viewContainer = new dojox.mobile.ScrollableView({id:"viewContainer"});
load: function(response) {
for (key in response){
// creating each view heading and content here.........
//can you give some hint what should be here?
}
}
How can I read above json and create dynamic views. What could be replace with this line in code //can you give some hint what should be here?
First, you're reading json in the wrong way.
dojo.xhrPost will send data to the url you specify in the url parameter : not retrieve the file in the url parameter. If you do it the way you're doing, you'll end up with an error such as "Unable to load start.json status:500"
So, in your case, to read the file, you should do a dojo.xhrGet instead.
Next, your viewContainer variable should not be placed like that, in the middle of the arguments (you are writing code mixed in the middle of object properties (!!!)).
So... you should be able to accomplish what you want by doing something like this :
require(["dojo/dom-construct",
"dojo/_base/xhr",
"dojox/mobile/parser",
"dojox/mobile",
"dojox/mobile/ScrollableView",
"dojox/mobile/Heading"],
function(domConstruct) {
dojo.xhrGet({
url : 'start.json',
handleAs : "json",
load : function(response) {
dojo.forEach(response.Introduction, function(page){
var node = domConstruct.create("div", {id : page.title}, "viewsContainer", "last");
var view = new dojox.mobile.ScrollableView({
id : page.title
}, node);
view.addChild(new dojox.mobile.Heading({label : page.title}));
view.startup();
});
},
error : function(err) {
console.debug("Error : ", err);
}
});
}
);
load: function(response) {
for (key in response.Introduction){
// creating each view heading and content here.........
}
and try to debug data for key it should be any object that you pass 3 obj in json...
here each key has three property that you define in json,now u can inject values to html view
by accessing property like this key.title,key.toolbar....,ex:- $('<p>' + key.title + '</p>');

Categories

Resources