Load content in Div through rest and load page - javascript

I am using rest to get some data and populate two divs with the content I am getting. This rest ajax call is on index.html.
These divs I am populating with content from the rest call are on page1.html which I am loading using the document.on ready inside the index.html at the end of the page.
The problem I am facing is sometimes when index.html loads, the divs are populated and sometimes they are not. I have to refresh the page for the divs to be populated. Any ideas or help will be appreciated. It may be code order or maybe I have to load the content on the success of the call?
<!--check if ID is passed-->
if ($.isNumeric(id)) {
formPath = "forms/EditForm.html";
getItemDetails(id);
$("#form").load(formPath);
}
<!--make rest call-->
function getItemDetails(itemID) {
console.log(itemID);
var url = siteURL;
$.ajax({
url: url,
type: "GET",
async: true,
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
var items = data.d.results;
$.each(items, function (index, item) {
step1AcknowledgementValue = item.Acknowledgement;
});
//**Populate Request Data**
//Request#
$("#requestNumberSpan").html(requestNumber);
//Step1
$('#step1Acknowledgement').html(step1AcknowledgementValue);
}
},
error: function (error) {
console.log(JSON.stringify(error));
}
});
}

Related

How to get nested JSON data values with a "data-" attribute?

I'm trying to create an elegant way of binding json data to html using data-attributes without having to write a bunch of custom code or using an external library/framework.
I can get this to work just fine without nested data and re-writing my function a little.
The problem is that it's reading my data-api-value as a string..so I'm trying to find the correct way to convert it. I'm open to other suggestions/ work-arounds though.
Here's the code in a (codepen)
Here's a dumb'd down version of the code
function getApiData(apiUrl, callback) {
apiData = $.ajax({
type: 'GET',
url: apiUrl,
dataType: 'json',
success: function(json) {
callback(json.data);
},
error: function(req, err) {
console.log(err);
},
contentType: "application/json; charset=utf-8"
});
}
function dataAPIrealtime() {
const url = 'https://someapi/v1/exchange/getinstrument/bitmex/XBTUSD';
getApiData(url, function(apidata){
$('[data-api]').each(function() {
let api = $(this).data("api");
let value = $(this).data("apiValue");
let data = apidata + value;
if (data || data != data) {
$(this).html(data);
}
});
});
}
/* Run Functions
*********************************/
$(document).ready(function() {
dataAPIrealtime();
setInterval(dataAPIrealtime, 1000); // Refresh data every 1 second
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span data-api="exchange/getinstrument" data-api-value="[instrument][symbol]"></span>

Initialize jquery again after replacing list with ajax call

I have a Prestashop module to display a list of latest products from different product categories. On top of the list of products are menu links like: ALL, CATEGORY 1, CATEGORY 2, CATEGORY 3, etc. When page opens, it displays "All" the latest products. But when I click on Category 1 for instance, it uses Ajax to load only products belonging to the category I clicked.
I implemented this jquery plugin on the module - https://tympanus.net/codrops/2013/03/19/thumbnail-grid-with-expanding-preview/.
The main jquery file grid.js is loaded before the end of the </body> and initialize by adding the code below before the end of the </body> too:
<script>
$(function() {
Grid.init();
});
</script>
This works well when the page is just opened. But when any of the category links are clicked. The products for that category are loaded but the grid jquery expanding grid does not work again.
In the js file for the module loaded within the <head> of the page, I noticed that the ajax call for the categories are made with the code below:
$(document).on('click','#list-category-new-product li a',function(e){
$('#blocknewproducts1_reload').addClass('active').prepend($('.newproduct_ajax_loader').html());
$('#blocknewproducts1').css('opacity', '0.7');
e.preventDefault();
$.ajax({
type: 'POST',
headers: { "cache-control": "no-cache" },
url: baseDir + 'modules/blocknewproducts1/newproduct_ajax.php',
async: true,
cache: false,
dataType : "json",
data: 'ajax_new_product=1&p=1&id_category='+$(this).attr('data-id'),
success: function(jsonData,textStatus,jqXHR)
{
$('#blocknewproducts1').html('');
$('#blocknewproducts1').html(jsonData.blocknewproduct);
$('#blocknewproducts1').css('opacity', '1');
}
});
});
I don't know much about jquery so I am wondering how I can get the expanding preview to work when the various categories are clicked and products loaded via ajax.
the
<script>
$(function() {
Grid.init();
});
</script>
is a one off function, you need to call it again in your success call like so
$(document).on('click','#list-category-new-product li a',function(e){
$('#blocknewproducts1_reload').addClass('active').prepend($('.newproduct_ajax_loader').html());
$('#blocknewproducts1').css('opacity', '0.7');
e.preventDefault();
$.ajax({
type: 'POST',
headers: { "cache-control": "no-cache" },
url: baseDir + 'modules/blocknewproducts1/newproduct_ajax.php',
async: true,
cache: false,
dataType : "json",
data: 'ajax_new_product=1&p=1&id_category='+$(this).attr('data-id'),
success: function(jsonData,textStatus,jqXHR)
{
$('#blocknewproducts1').html('');
$('#blocknewproducts1').html(jsonData.blocknewproduct);
$('#blocknewproducts1').css('opacity', '1');
$(function() {
Grid.init();
});
}
});
});

ajax requesting sending in second click in knockout js

i have the below knockout js code..
Design Code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/2.3.0/knockout-min.js"></script>
<div class="acmenu">
<ul id="accordion" data-bind="foreach: CategoryList">
<li data-bind="click$parent.categorySelected),attr: {iddata.CategoryId},htmldata.CategoryName">
</li>
</ul>
</div>
self.categorySelected = function (selectedCategory, event) {
$('#newproducttitle').hide();
event.preventDefault();
selectCategoryId = selectedCategory.CategoryId();
var refurbishedUrl = "/services/ShopService.asmx/XGetRefurbishedproducts";
$.ajax({
url: refurbishedUrl,
data: JSON.stringify({ ItemID: itemid, categoryid: selectCategoryId, language: lang }),
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
/******Lines of code**********/
}});
}
This function is calling for every click but ajax requesting is sending for second click only. i need to send ajax request for first click, is there any solution for that....
here i am proving one drive link for js file https://onedrive.live.com/redir?resid=143242b617ba6be2!6684&authkey=!AAJQbpV8ZQ7fnGI&ithint=file%2ctxt
Though we don't have enough to work on still I think it is calling on first request as well (unless you have verified in developer tools etc.). The reason it seems to work on second click is that ajax call has not returned and on second click it appears to work.
Try this to disable button until ajax returns:
$.ajax({
url: refurbishedUrl,
data: ...,
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
beforeSend:function(){ $(event.target).prop('disabled', true);},
}).done(function(data){
/*USE THIS INSTEAD OF success*/
}).fail(function(data){
/*USE THIS INSTEAD OF error*/
}).always(function(){
$(event.target).prop('disabled', false);
});
You are using knockout against its design.
The viewmodel manages data and state - and nothing else. It is not supposed to contain any code that does HTML or DOM manipulation, at all.
In this case your data is a list of category objects. You want to inform the server when one of them becomes the selected category. Additionally you want to keep track of whether the viewmodel is busy talking with the server.
Therefore we need categoryList, selectedCategory and busy observables, as well as a subscription to changes in the selected category:
function ViewModel() {
var self = this;
self.categoryList = ko.observableArray([/* category objects ... */]);
self.selectedCategory = ko.observable();
self.busy = ko.observable(false);
self.selectedCategory.subscribe(function (newCategory) {
self.busy(true);
API.post("XGetRefurbishedproducts", {
ItemID: itemid, // wherever that comes from
categoryid: newCategory.CategoryId(),
language: lang // wherever that comes from
}).done(function (data) {
/******** Lines of code ********/
}).always(function () {
self.busy(false);
});
});
}
The view displays the category list, provides a way of changing the selected category, and reacts to whether the viewmodel is busy.
Therefore we need foreach, text, click and disable bindings:
<div class="acmenu">
<ul id="accordion" data-bind="foreach: categoryList">
<li>
<span data-bind="text: CategoryName"></span>
<button data-bind="
click: $parent.selectedCategory,
disable: $parent.busy
">Select</button>
</li>
</ul>
</div>
Note that you can use an observable as a click handler.
Finally, to keep the viewmodel tidy, here's a helper that concentrates all Ajax handling in a central spot.
var API = {
ajax: function (httpMethod, apiMethod, data) {
return $.ajax({
type: httpMethod,
url: "/services/ShopService.asmx/" + apiMethod,
data: data,
dataType: "json"
}).fail(function (jqXhr, status, error) {
console.error("Could not call " + method + ", error: " + error, data);
});
},
get: function (apiMethod, data) {
return this.ajax("get", apiMethod, data);
},
post: function (apiMethod, data) {
return this.ajax("post", apiMethod, data);
}
};

Ajax call to delete and refresh list not working

I am implementing an Ajax call to the server to delete a post from a li. The delete is working fine, but I need to manually get out from the list page and when I get back the list is updated. What I am trying to achieve, is that when the button that deletes the item, also refreshes the list. I added the following code but is not refreshing :(.
function deleteThisPost() {
//alert($('#myPostIDStorage').val())
$.ajax({
type: 'GET',
data: 'myPostIDValue=' + $('#myPostIDStorage').val(),
url: 'http://wander-app.org/deletePosts.php',
timeout: 5000,
success: function (data) {
alert('Post Deleted!');
},
error: function () {
alert('Error Deleting Post');
}
});
return false;
$('#myPost').listview("refresh");
};
Your ajax call works fine as you can see there. You should take a notice that if you return anything from a function it is no longer executed. The code that you provided below $( '#myPost' ).listview( "refresh" ); will be never examined.
What you probably want to do is
function deleteThisPost() {
//alert($('#myPostIDStorage').val())
$.ajax({
type: 'GET',
data: 'myPostIDValue=' + $('#myPostIDStorage').val(),
url: 'http://wander-app.org/deletePosts.php',
timeout: 5000,
success: function (data) {
alert('Post Deleted!');
},
error: function () {
alert('Error Deleting Post');
}
});
$('#myPost').listview("refresh");
return false;
};
According to your question if you want a dialog box with cancel and confirm button you can do
if(confirm('Do you want to delete?') == true) {
alert('Deleted');
}

How to retain an injected partial view after page refresh in asp.net mvc

I am using ASP.NET MVC 4 and jQuery. I have a button control on my view. When it is clicked it "injects" a partial view into my view. When I refresh the page then the partial view is gone.
My HTML markup:
<button id="RetrieveButton" type="button">Retrieve</button>
<div id="RuleDetails">
<div class="main-content">
<p>Some text.</p>
</div>
</div>
My jQuery to return the partial view with an AJAX call to return the HTML:
$('#RetrieveButton').click(function () {
$.ajax(
{
type: 'POST',
url: '#Url.Action("GetRuleDetails")',
data: {
systemCode: $('#SystemCodes').val()
},
dataType: "html",
success: function (result) {
alert('success');
var domElement = $(result);
$("#RuleDetails").html(domElement);
},
error: function (result) {
alert('error');
}
});
});
My action method:
public ActionResult GetRuleDetails()
{
RuleViewModel viewModel = new RuleViewModel();
return PartialView("_RuleInformation", viewModel);
}
My partial view:
#model MyProject.ViewModels.Rules.RuleViewModel
<div class="main-content">
<h2>Rule Details</h2>
</div>
I need this "injected" partial view to remain there if I were to refresh the page. Currently it "resets" if I were to refresh it, and the partial that was injected is gone.
It will not render that partial view again as it is does not remembers clicked state of button.
One of the ways to achieve what you are looking for is by using sammy.js
On click of button you can set the hashurl using sammy.js (e.g.: '#/partialview') and on page refresh hashurl part stays intact (but does not go to server). And then you can manipulate the client code accordingly
Take sammy.js reference in your page.
Intialize sammy like below
var app = $.sammy('body', function (context){
this.get('#/PartialView1', function () {
fnLoadPartialView();
});
});
change Retrieve to with href='PartialView1'
function fnLoadPartialView (){
$.ajax(
{
type: 'POST',
url: '#Url.Action("GetRuleDetails")',
data: {
systemCode: $('#SystemCodes').val()
},
dataType: "html",
success: function (result) {
alert('success');
var domElement = $(result);
$("#RuleDetails").html(domElement);
},
error: function (result) {
alert('error');
}
});
}
5.
$('#RetrieveButton').click(function () {
fnLoadPartialView ();
});

Categories

Resources