Getting ajax data from html link - html

I bought a template and have asked to the writer but still no respond so far. Actually, I need a quick answer. Any body here can help to fix?
It's about to show Quick View of a single product detail to show in a window popup when a link is clicked. I have no idea how to put any data and get the data when popup appear, no browser refresh. Please don't ask me what have I done, I have no idea at all. I usually used ajax in a form.
The html link is like this :
<div class="quick-view">
<a title="Quick view" class="search" href="#"></a>
</div>
and the ajax call :
$(document).on('click','.quick-view .search,a.quick-view',function(){
var data = {
// data here....
}
$.post('quick_view.php', data, function(response){
$.fancybox(response, {
// fancybox API options
fitToView: false,
autoSize: false,
closeClick: false,
openEffect: 'none',
closeEffect: 'none'
}); // fancybox
// OWL Product thumb
$('.product-img-thumb .owl-carousel').owlCarousel(
{
dots:false,
nav:true,
navText:['<i class="fa fa-angle-left"></i>','<i class="fa fa-angle-right"></i>'],
margin:21,
responsive : {
// breakpoint from 0 up
0 : {
items : 2,
},
// breakpoint from 480 up
480 : {
items : 2,
},
// breakpoint from 768 up
768 : {
items : 2,
},
1000 : {
items : 3,
}
}
}
);
})
return false;
})
any answers is appreciated.

If you add an ID to your elements that fire the event you can access and use it's ID or other Attribute to send it as data in your AJAX-call. To do this you use the event.target which points to the element that triggerred the event. In this way you can use the same call for a whole bunch of elements on the same page:
$(document).on('click','.quick-view .search,a.quick-view',function(event){
// Get the id of the element and add it to the data sent with call
var data = {
elementId: event.target.id
}
// Rest of your Ajax call
}

Related

How can I find the place in my code or page where the location is set?

I tried global event listeners pane in Chrome DevTools, I tried to put a debugger; inside document/window.addEventListener("unload", ...) and it is not working.
I tried to step over the statements in the file main.ts and nothing is breaking the code in there when I click on a link that should open another page than the one it is opening. I checked its HTML attributes and the correct URL is set in its href attribute. The link has a single class which is not used to open another page in the page's code as far as I know.
I also searched for all the places in my code where the (window.)location is changed.
I also updated npm packages using npm update.
I use KnockOut.js and I have this static HTML for the links that go to wrong pages:
<ul class="main-nav" data-bind="foreach: mainMenuItems">
<li>
<a data-bind="attr: { href: url, title: text }, text: text, css: { active: $data == $root.activeMenuItem() }"></a>
<div class="bg"></div>
</li>
</ul>
And this is a part of the TypeScript code (sorry for the ugly code, it is WIP):
let vm = new PageViewModel(null, "home", () => {
sammyApp = $.sammy(function () {
// big article URLs w/ date and slug
this.get(/\/(.+)\/(.+)\/(.+)\/(.+)\/(.*)[\/]?/, function() {
vm.language("ro");
vm.isShowingPage(false);
vm.isShowingHomePage(false);
let slug : string = this.params['splat'][3];
vm.slug(slug);
console.log('logging', { language: vm.language(), slug: vm.slug() });
vm.fetch();
vm.isShowingContactPage(false);
vm.activeMenuItem(vm.getMenuItemBySlug(slug));
});
// any other page
this.get(/\/ro\/(.+)\//, function () {
console.log('pseudo-navigating to /ro/etc.');
vm.language("ro");
vm.isShowingPage(true);
vm.isShowingHomePage(false);
let slug : string = this.params["splat"][0];
//slug = slug.substr(0, slug.length - 1);
if (slug !== 'contact') { // this page is in the default HTML, just hidden
vm.slug(slug);
vm.fetch();
vm.isShowingContactPage(false);
} else {
vm.isShowingContactPage(true);
window.scrollTo(0, 0);
}
vm.activeMenuItem(vm.getMenuItemBySlug(slug));
});
this.get(/\/en\/(.+)\//, function () {
console.log('pseudo-navigating to /en/etc.');
vm.language("en");
vm.isShowingPage(true);
vm.isShowingHomePage(false);
let slug : string = this.params["splat"][0];
//slug = slug.substr(0, slug.length - 1);
if (slug !== 'contact') { // this page is in the default HTML, just hidden
vm.slug(slug);
vm.fetch();
vm.isShowingContactPage(false);
} else {
vm.isShowingContactPage(true);
, () => {
uuuuucons
}9 function
window.scrollTo(0, 0);
}
vm.activeMenuItem(vm.getMenuItemBySlug(slug));
});
// the home page
this.get("/", function () {
console.log(`pseudo-navigating to /${vm.language()}/home`);
sammyApp.setLocation(`/${vm.language()}/home`);
});
});
sammyApp.run();
});
I have this code that catches the click event:
$("a").on("click", () => {
debugger;
});
But after this finding I do not know what I can do to find the source of the problem.
When the click is catched by the 3 LOCs above, I get this:
What could be the issue?
Thank you.
Update 1
After seeing these questions and their answers (the only thing I did not try was using an iframe):
How can I find the place in my code or page where the location is set?
Breakpoint right before page refresh?
Break javascript before an inline javascript redirect in Chrome
If I have a page for which I check the beforeunload and unload event checkboxes in the Event Listener Breakpoints pane in Chrome DevTools' tab Sources, and I click on a link which should not reload the page but it does, and the two breakpoints (beforeunload and unload) are not triggered in this process, what should I do next?
Is this a known bug? If so, can someone give me an URL?
Thank you.

Kendo ui Grid with large data loads incorrectly with pageable Go to Last Page

I am NOT using serverPaging and Virtual Paging.
Scenario : I have a dropdownlist when get changed it loads the grid.First time I load 100 data items & everything works correctly.
When I change the dropdownlist which will fetch large data like 20,000 total data items it get loaded & works correctly if the navigation is through clicking page number at bottom of grid.
Problem : when I click 'Go to the Last Page' button it shows the Previous POST request's last part of dataItems(90-100 previous date items )showing 100 as total dataitems wrongly.When I click previous page number it loads 80-90 items of correct data updating total size 20,000.
I find if I refresh the grid using pageable refresh button and navigate to the last page it works correctly..After grid's initialisation I tried of calling datasource read() and grid's refresh() but still problem persist.
Kindly help. I am using Kendo UI v2013.1.226.
Thanks in Advance.
FYI: I cant use serverPaging and Virtual Paging due to some restriction .
var myDataSrc = new kendo.data.DataSource({
pageSize : 20,
batch: true,
transport:
{
read: {
url: "../../api/getList",
dataType: 'json',
complete: function(e) {}
},
parameterMap: function(options, operation) {
if (operation == 'read') {
return {
dropdDownId : selectedDD.id
};
}
}
},
schema :
{ model :
{
id : "id",
fields :{
id : {type : "number"},
name:{type:"string"}
}
}
}
});
$("#myGrid").kendoGrid({
dataSource : myDataSrc,
selectable : true,
navigatable : true,
resizable : true,
sortable : true,
pageable:{refresh:true},
scrollable : true,
autoBind : true,
filterable:true,
columns : [ {
field : "name",
title : "name",
width : 150
} ],...
});
};

How to refresh only <div> content in a web page?

The div is:
<div>
<canvas id="chart-area2" width="300" height="300"/>
</div>
how to refresh the above div every 10 seconds without reloading the page?
following is the javascript:
<script>
var pieData2 = [
{
value: <?= $pfstatetext;?>,
color:"#F7464A",
highlight: "#FF5A5E",
label: "Red :"
},
{
value: <?= $cpuusage; ?>,
color: "#46BFBD",
highlight: "#5AD3D1",
label: "Green"
},
{
value: 100,
color: "#FDB45C",
highlight: "#FFC870",
label: "Yellow"
},
{
value: 40,
color: "#949FB1",
highlight: "#A8B3C5",
label: "Grey"
},
{
value: 120,
color: "#4D5360",
highlight: "#616774",
label: "Dark Grey"
}
];
window.onload = function(){
var ctx2 = document.getElementById("chart-area2").getContext("2d");
var myPie2 = new Chart(ctx2).Pie(pieData2);
};
</script>
how can i use setInterval in the above code?.....................................................................................................
You may use that code
function refreshTheDiv(){
// Your drawing code here
window.setTimeout(refreshTheDiv,10000);
}
And replace the line // Your drawing code here with your code referencing the canvas element.
In your specific case :
(function(){
var myPie2;
window.onload = function(){
var ctx2 = document.getElementById("chart-area2").getContext("2d");
myPie2 = new Chart(ctx2).Pie(pieData2);
updateChart();
};
function updateChart()
{
$.getJson('/data.php',function(data){
// Do the update here (Seems dead : https://github.com/nnnick/Chart.js/issues/13 )
// You may deal with chartjs methods or recreate the chart:
myPie2 = new Chart(ctx2).Pie(data); // Quick and dirty solution
setTimeout(updateChart,10000);
});
}
})();
The data.php contains something like:
<?php
echo json_encode(
array(
array(
'value'=> $pfstatetext,
'color'=>"#F7464A",
'highlight'=> "#FF5A5E",
'label'=> "Red :"
),
array(
'value'=>$cpuusage,
'color'=> "#46BFBD",
'highlight'=> "#5AD3D1",
'label'=> "Green"
),
array(
value: 100,
color: "#FDB45C",
highlight: "#FFC870",
label: "Yellow"
)
//...
)
);
You must include JQuery : http://code.jquery.com/jquery-1.11.1.js
for my solution to work
ChartJS update data
If you want to update the canvas painting and you're not working with the server, use js setTimeout or setInterval (You can read about these functions here: http://www.w3schools.com/js/js_timing.asp). In the callback function that you pass to these functions you work with the canvas' context object and paint whatever you want.
If you want to update the content, like text and HTML, or if the painting is related to the server, I think you should use AJAX. AJAX enables communication after the page was loaded, so you don't have to load the whole page again. There are many tutorials for ajax, one of them is on W3schools. Also, if you work with AJAX, you should use the timing functions that I've mentioned before in order to refresh it every 10 seconds.
Another solution is to use Server-Sent Events. If you want to refresh the div in order to UPDATE the content (according to the DB, the server, etc.) so the content will be always updated, you can use this technique that follows about differences and updates, and loads them. You can read about it here : http://www.w3schools.com/html/html5_serversentevents.asp. I'm not sure if this technique is what you're looking for, it depends on what is your purpose of reloading the page, so I think the AJAX would be a great solution if the content is from the server, and the first solution is the only one which is correct if you don't work with the server.
write one function to fetch content inside div trough ajax, and write a jquery code to call the function in every 10 seconds.
For example:
function fetch_content(){
$.ajax({
url: "url for ajax page",
type: "POST",
success: function(data){
$('div').html();
}
});
}
and code to call this function every 10 seconds
setInterval(fetch_content,10000);

How to populate a jQuery Mobile ListView with JSON data?

I'm developing a webapp here using HTML and jQuery Mobile (JQM), so I'm pretty new at this.
What I'm trying to do here is to populate a JQM listview with a list of names.
Each of this names will link to a new page with personal data being displayed (Full name, address, date of birth, etc).
Currently, because of my lack of knowledge, I manually create a new .html file for EACH individual person (e.g. johnDoe.html for a fictional character Mr. John Doe). I then physically link the list elements to this html file via the function.
Problem is now I have 100 over individuals to populate that list view. I think that there's an easier way to do this rather than manually creating 100+ html files for all these individual persons right?
I heard of this JSON thing that might do the trick, but coming from a background of ZERO computing knowledge, I don't really understand how it works. Will someone please shed some light on how can I do this?
Thanks a lot!
EDIT:
I'm using Dreamweaver CS5.5 to do the coding. For this webapp that I'm tasked to develop, I was given a "template" or sorts that uses JQM and Backbone.js. As such, somehow the "multi-page" structure for a single HTML file doesn't seem to work. From what I see in the template, every HTML file has a corresponding JS file that has code that looks like this:
define(['jquery',
'underscore',
'backbone',
'helper',
'views/phr/list',
'text!templates/vpr2.html'
],
function ($,
_,
Backbone,
Helper,
phrListView,
tmpVpr2) {
var view = Backbone.View.extend({
transition: 'fade',
reverse: true,
initialize: function () {
this.phrlistview = new phrListView();
},
render: function () {
$(this.el).append(_.template(tmpVpr2, {}));
console.log("Rendering subelements...");
Helper.assign(this, {
'#phrListView': this.phrlistview
});
return this.el;
}
});
return view;
});
For the HTML pages, they all begin with a <div data-role=header> tag, then a <div data-role=content>, before ending with a <div data-role=footer>, all with their respective content within the opening and closing tags.
For my listview in question, the JQM code for the listview will be within the <div data-role=content> part of the HTML file. How can I populate this listview with JSON data then?
(Apologies if I sound extremely noob at this, because I really am >.< Really appreciate the help!)
Solution
Yes. Its possible to have two pages and use one for displaying your data and one to show up the details of the clicked item. I had to pull in some old stuff, a demo I made when jQM was in version 1.1 and change it to modern times. Anyway, considering I have an array like this :
[
{
"id": 0,
"age": 31,
"name": "Avis Greene",
"gender": "female",
"company": "Handshake",
"email": "avisgreene#handshake.com",
"phone": "+1 (845) 575-2978",
"address": "518 Forrest Street, Washington, New York, 3579"
},
{
"id": 1,
"age": 31,
"name": "Dunn Haynes",
"gender": "male",
"company": "Signity",
"email": "dunnhaynes#signity.com",
"phone": "+1 (829) 454-3806",
"address": "293 Dean Street, Dante, Oregon, 5864"
}
]
I randomly generated stuff and made it upto 100 elements, just like how you seem to have. I have two pages.
<!--first page -->
<div data-role="page" id="info-page">
<div data-role="header" data-theme="b">
<h1> Information</h1>
</div>
<div data-role="content">
<ul data-role="listview" id="prof-list" data-divider-theme="a" data-inset="true">
<li data-role="list-divider" data-theme="b" role="heading">Names</li>
</ul>
</div>
</div>
<!--second page -->
<div data-role="page" id="details-page">
<div data-role="header" data-theme="b">Go back
<h1>Employee Details</h1>
</div>
<div data-role="content"></div>
</div>
The first page, #info-page is for showing data in a listview. The second page, #details-page is for the info of the clicked item. Thats all you need. Only two pages, not more than that. So every time a click happens, you do the following through JavaScript
Get the current value of data from the array. Like if you click on the 4th li in the list, get the 4th object from the array which has all the data.
Store it in the data variable of the second page, so that it can be retrieved later. Something like this:
$("#details-page").data("info", info[this.id]);
Then, redirect to second page using changePage, like this :
$.mobile.changePage("#details-page");
When the second page opens, use the pagebeforeshow event to get the data from the page (which you stored into this page when the tag in the previous page was clicked.
Use some HTML layout to populate the data. I used jQM's grids.
That's all folks!
Full code
Ive attached the JS used with the HTML. Its self explanatory. Read the inline comments in the code and you'll be able to understand more. Assume info is the array in picture.
//pageinit event for first page
//triggers only once
//write all your on-load functions and event handlers pertaining to page1
$(document).on("pageinit", "#info-page", function () {
//set up string for adding <li/>
var li = "";
//container for $li to be added
$.each(info, function (i, name) {
//add the <li> to "li" variable
//note the use of += in the variable
//meaning I'm adding to the existing data. not replacing it.
//store index value in array as id of the <a> tag
li += '<li>' + name.name + '</li>';
});
//append list to ul
$("#prof-list").append(li).promise().done(function () {
//wait for append to finish - thats why you use a promise()
//done() will run after append is done
//add the click event for the redirection to happen to #details-page
$(this).on("click", ".info-go", function (e) {
e.preventDefault();
//store the information in the next page's data
$("#details-page").data("info", info[this.id]);
//change the page # to second page.
//Now the URL in the address bar will read index.html#details-page
//where #details-page is the "id" of the second page
//we're gonna redirect to that now using changePage() method
$.mobile.changePage("#details-page");
});
//refresh list to enhance its styling.
$(this).listview("refresh");
});
});
//use pagebeforeshow
//DONT USE PAGEINIT!
//the reason is you want this to happen every single time
//pageinit will happen only once
$(document).on("pagebeforeshow", "#details-page", function () {
//get from data - you put this here when the "a" wa clicked in the previous page
var info = $(this).data("info");
//string to put HTML in
var info_view = "";
//use for..in to iterate through object
for (var key in info) {
//Im using grid layout here.
//use any kind of layout you want.
//key is the key of the property in the object
//if obj = {name: 'k'}
//key = name, value = k
info_view += '<div class="ui-grid-a"><div class="ui-block-a"><div class="ui-bar field" style="font-weight : bold; text-align: left;">' + key + '</div></div><div class="ui-block-b"><div class="ui-bar value" style="width : 75%">' + info[key] + '</div></div></div>';
}
//add this to html
$(this).find("[data-role=content]").html(info_view);
});
Demo
I've also made a demo where you can read more about this at jsfiddle.net.
Here's the link : http://jsfiddle.net/hungerpain/52Haa/
you can try something like this
Updated
Html Page
<div data-role="page" id="testpage">
<div data-role="content">
<ul data-role="listview" id="listitem" data-divider-theme="a" data-inset="true">
</ul>
</div>
</div>
javascript
$(document).on("pageinit", "#testpage", function(){
$.getJSON("example.json", function(data){
var output = '';
$.each(data, function(index, value){
output += '<li>' +data+ '</li>';
});
$('#listitem').html(output);
});
});

Click event not registering on second page

I'm using tablesorter and tablesorter.pager. Here is my code:
$(document).ready(function() {
$("#peopletable")
.tablesorter({ widthFixed: true, widgets: ['zebra'] })
.tablesorterFilter({ filterContainer: $("#people-filter-box"),
filterClearContainer: $("#people-filter-clear-button"),
filterColumns: [1, 2, 3],
filterCaseSensitive: false
})
.tablesorterPager({ container: $("#peoplepager") });
$("#peopletable tr.data").click(function() {
var personid = $(this).attr('id');
$.ajax({
type: "POST",
url: "/Search/GetDocumentsByPerson",
data: { "id": personid },
datatype: "json",
success: function(data) {
var results = eval(data);
$("#documentstable > tbody tr").remove();
$.each(results, function(key, item) {
$("#documentstable > tbody:last").append(html);
});
$("#documentstable").trigger("update");
}
});
});
});
Everything works great except when I click on the next page my button click event doesn't fire. Is this a known issue with jQuery tablesorter?
It's because the elements are updated, the ones you bound the click handler to are gone, you can use .live() to resolve this, change this:
$("#peopletable tr.data").click(function() {
To this:
$("#peopletable tr.data").live('click', function() {
Alternatively, if #peopletable isn't destroyed you can use .delegate(), like this:
$("#peopletable").delegate('tr.data', 'click', function() {
I have also faced the same kind of problem with tablesorterPager second page after using Jeditable (edit in place) plugin for some element in the tablesorterPager used table.
I have tried editing the data bind function in Jeditable as follows
original code
$(this).bind(settings.event, function(e) {
here settings.event equals to the event parameter which we are defining with options eg: click
modified code
$(this).live(settings.event, function(e) {
But.. I found the error with tablesorterPager within pages other than the first page is not because of the binding of element event.
when we are calling tablesorterPager to any table with many rows, only the first page rows of
the table is affected on the page load. so only the first page rows are called with Jeditable plugin. other rows in the other pages are not assigned with the plugin. because of this reason, the events in other pages than first page will not work.
to prevent above situation, we can add Jeditable plugin calling inside updatePageDisplay function.
eg:
function updatePageDisplay(c) {
$(".tablerowdata").each(function(){
$(this).editable("ajax/save.php", {
tooltip : "click to edit...",
data : {"selectid1":"selectval1","selectid2":"selectval2","selectid3":"selectval3"},
type : "select",
submit : "ok",
event : "click",
select : "true",
});
});
Creating a new element won't duplicate the event created with the click method wheras the live method does it.