jQuery/JavaScript parse AJAX response - javascript

I am retrieving an AJAX response from a server (the server processed an update of a shoppingcart) that contains various elements. Here is an example of how it looks like:
<div id="blockcart-wrapper">
<div class="shoppingcart-background" id="bg-div"></div>
<div class="blockcart cart-preview" data-refresh-url="//localhost/backend/index.php?fc=module&module=shoppingcart&controller=ajax">
<div class="header">
<a rel="nofollow" href="#">
<img class="cart-icon" src="someImage"
onclick="toggleClass()">
</a>
</div>
<div class="body" id="shopping-cart-body">
<div class="close">
<a href="#" onclick="toggleClass()">
<img class="icon" height="20px" width="20px" src="someImage">
</a>
</div>
<h1 class="shopping-cart-header">Shoppingcart</h1>
<div class="products-container">
<div class="product">
<span class="product-image"><img src="someImage"></span>
<div class="product-details">
<h2 class="name-header">Name</h2>
<div class="product-quantity-details">
<span class="quantity">19</span>
-
<a id="link1" href="https://backend/decrease" class="js-increase-product-quantity" data-link-action="update-quantity">+</a>
<span class="color-circle">
</span>
</div>
<div class="price-open">
<span class="product-price">14,16 €</span>
<span class="product-link">öffnen</span>
</div>
<a
class="remove-from-cart"
data-link-action="remove-from-cart"
data-id-product="6"
data-id-product-attribute="0"
href="http://backend/remove"
rel="nofollow"
>
Remove
</a>
</div>
</div>
</div>
<div class="checkout">
<div class="meta-data-wrap">
<div class="cart-total label-row">
<span class="label">Total</span>
<span class="value">269,06 €</span>
</div>
</div>
<a href="/index.php?controller=order" class="checkout-step">
<button type="button" class="dark">Checkout</button>
</a>
</div>
</div>
The problem is, that the respone contains about 25000 LOC which are mostly irrelevant. So I want to parse this part of the response and insert it into the actual HTML. What I did so far:
document.getElementById('link1').addEventListener('click', function(ev){
ev.preventDefault();
console.log(ev);
$.ajax({
url: this.href,
type: "GET",
dataType: "html",
success: function(data) {
console.log($(data).text());
}
});
});
This gives me the complete response. So from this on, I tried to find the div with the id blockcart-wrapper, which is my 'entry point' for replacing the old HTML, so I did:
document.getElementById('link1').addEventListener('click', function(ev){
ev.preventDefault();
console.log(ev);
$.ajax({
url: this.href,
type: "GET",
dataType: "html",
success: function(data) {
console.log($(data).find('#blockcart-wrapper'));
}
});
});
But this gives me a jQuery object and not The HTML content within this div.
Could someone help me to parse the mentioned div and replace the 'old' with the new parsed?

But this gives me a jQuery object and not the HTML content within this div.
You must use .html() to return the HTML code inside the div like :
console.log( $(data).find('#blockcart-wrapper').html() );

If you cannot get a smaller response, try getting a partial:
Note the space before the selector
url: this.href + ' #blockcart-wrapper'
or
$("#container").load(location.href + ' #blockcart-wrapper')

Related

How to call a multiple html pages one by one on clicking the respective content in nav bar?

I am displaying table of content in nav bar and while clicking on that item i want to display the HTML which is already linked to that item.In my case while clicking on that item new page is opening in other tab I want to open new HTML in same page.
This is my code.
<div id="mySidenav" class="sidenav" style="width: 250px;background: beige;">
×
<h2 class="fm_title" id="toc" style="font-size: 18px;">TABLE OF CONTENTS</h2>
<p class="toc_noindent" id="fm_2">Sections Affected by 2017 Legislation</p>
<p class="toc_noindent" id="fm_3">California Legal Guidelines</p>
<p class="toc_center" id="ma_1"><span class="bold">VEHICLE CODE</span></p>
<p class="toc_noindent" id="ma_2"><span class="bold">General Provisions, §§ 1–95</span></p>
</div>
<span style="font-size:30px;cursor:pointer;float: right;" onclick="openNav()">☰</span>
<i style="font-size:30px;cursor:pointer;float: left;font-size:24px;" href="" class="fa"></i>
<div style="padding-top: 44px;">
<div id="nav-placeholder"></div>
</div>
<script>
$(function(){
$("#nav-placeholder").load("pub21749_data_02_chapter~01.html");
});
</script>
Please help me to sort this out.
Try including all the HTML files in the same file of the navbar. Enclose each of them in a <a></a> tag with an id.
Now if an id is as id="link1" use <a href="#link1"> in your navbar.
Try this;
HTML
<div id="mySidenav" class="sidenav" style="width: 250px;background: beige;">
×
<h2 class="fm_title" id="toc" style="font-size: 18px;">TABLE OF CONTENTS</h2>
<p class="toc_noindent" id="fm_2">Sections Affected by 2017 Legislation</p>
<p class="toc_noindent" id="fm_3">California Legal Guidelines</p>
<p class="toc_center" id="ma_1"><span class="bold">VEHICLE CODE</span></p>
<p class="toc_noindent" id="ma_2"> <span class="bold">General Provisions, §§ 1–95</span></p>
</div>
<span style="font-size:30px;cursor:pointer;float: right;" onclick="openNav()">☰ </span>
<i style="font-size:30px;cursor:pointer;float: left;font-size:24px;" href="" class="fa"></i>
<div style="padding-top: 44px;">
<div id="nav-placeholder"></div>
</div>
JS
$('#mySidenav p a').on('click', function(e) {
e.preventDefault();
$.ajax({
type: "GET",
url: $(this).attr('href'),
success: function (data) {$('#nav-placeholder').html(data);},
error: function (e) {console.log(e);}
});
});
https://jsfiddle.net/xpvt214o/328968/
The AJAX function looks for a click event on the link, stops it from switching page, then requests the page via AJAX and loads it into the nav-placeholder element.

jquery each selector and ajax not producing the right results

I am trying to simplify my code but running into issues where it is not working when it place in an each loop.
Here is what I am trying to do:
- html has n parent DIV that generates a report via an AJAX call to pull data
- each div respective to report utilizes a data attribute to define which report to pull
- based no the results of the report, it should populate the html with the respective results.
HTML Code (to simplify, using n = 2):
<div class="widget-box widget-hits card no-border bg-white no-margin" data-widget-report="widget-hits">
<div class="container-xs-height full-height">
<div class="row-xs-height">
<div class="col-xs-height col-top">
<div class="card-header top-left top-right">
<div class="card-title text-black hint-text">
<span class="font-montserrat fs-11 all-caps">Weekly Hits
<i class="far fa-chevron-right p-l-5"></i>
</span>
</div>
<div class="card-controls">
<ul>
<li>
<a data-toggle="refresh" class="card-refresh text-black" href="#">
<i class="far fa-circle fa-xs"></i>
</a>
</li>
</ul>
</div>
</div>
</div>
</div>
<div class="row-xs-height ">
<div class="col-xs-height col-top relative">
<div class="row">
<div class="col-sm-6">
<div class="p-l-20 widget-total">
<h3 class="no-margin p-b-5"></h3>
<p class="small hint-text m-t-5">
<span class="label m-r-5">%</span>
</p>
</div>
</div>
<div class="col-sm-6">
</div>
</div>
<div class="widget-chart"></div>
</div>
</div>
</div>
</div>
<div class="widget-box widget-sales card no-border bg-white no-margin" data-widget-report="widget-sales">
<div class="container-xs-height full-height">
<div class="row-xs-height">
<div class="col-xs-height col-top">
<div class="card-header top-left top-right">
<div class="card-title text-black hint-text">
<span class="font-montserrat fs-11 all-caps">Weekly Sales
<i class="far fa-chevron-right p-l-5"></i>
</span>
</div>
<div class="card-controls">
<ul>
<li>
<a data-toggle="refresh" class="card-refresh text-black" href="#">
<i class="far fa-circle fa-xs"></i>
</a>
</li>
</ul>
</div>
</div>
</div>
</div>
<div class="row-xs-height ">
<div class="col-xs-height col-top relative">
<div class="row">
<div class="col-sm-6">
<div class="p-l-20 widget-total">
<h3 class="no-margin p-b-5"></h3>
<p class="small hint-text m-t-5">
<span class="label m-r-5">%</span>
</p>
</div>
</div>
<div class="col-sm-6">
</div>
</div>
<div class="widget-chart"></div>
</div>
</div>
</div>
</div>
JS:
$('.widget-box').each(function() {
$widget_report = $(this).data('widget-report');
if ($widget_report !== undefined) {
$.ajax({
type: 'get',
url: '/admin/reports/' + $widget_report,
dataType: 'json',
success:
function(data) {
if (data.success) {
var labelsData = [];
var seriesData = [];
var trend = data.trend * 100;
widget_class = '.' + $widget_report + ' .widget-chart';
console.log(widget_class);
$(this).find('.widget-total h3').text(data.total);
$(this).find('.widget-total p span').text(trend + '%');
trend_span = $(this).find('.widget-total p').children('span');
if(data.trend > 0) {
$(this).find('.widget-total p span.label').addClass('label-success');
$(this).find('.widget-total p').text('Higher');
}
else {
$(this).find('.widget-total p span.label').addClass('label-important');
$(this).find('.widget-total p').text('Lower');
}
$(this).find('.widget-total p').prepend(trend_span);
$.each(data.values, function(key, value){
date = new Date(value.label + 'T00:00:00');
labelsData.push(date.getMonth() + 1 + '/' + date.getDate());
seriesData.push(value.value);
});
chartData = {
labels: labelsData,
series: [seriesData]
}
alert(widget_class);
new Chartist.Bar(widget_class, chartData, {
axisX: {
showGrid: false
},
axisY: {
showGrid: false,
showLabel: false
}
});
}
}
});
}
});
Here are the problems I've encountered:
$(this).find('.widget-total h3').text is not updating the respective DIV group
widget_class for some reason is always returning the last DIV group... even if the last DIV group was returning data.success = false. Ex: above would return widget-sales twice and not widget-hits and then widget-sales.
I am scratching my head on this one... I am able to get this to work without the .each loop and distinctively create one for each... but was hoping to make this universal and allow the control rely on the data-widget-report attribute on the html.
Is this the proper approach?
Any help / direction is appreciated...
Add var in front of widget_class and $widget_report so they are scoped to the function instead of global. I think that will fix your problem. Right now $widget_report gets replaced by the last widget even before the ajax calls are completed.
As for the $(this) not working, you have to assign it to a variable before you make the ajax call.
$('.widget-box').each(function() {
var widgetBoxElement = $(this);
var $widget_report = $(this).data('widget-report');
if ($widget_report !== undefined) {
$.ajax({
type: 'get',
url: '/admin/reports/' + $widget_report,
dataType: 'json',
success:
function(data) {
if (data.success) {
// use widgetBoxElement here instead of $(this)
}
}
});
}
});

how to get the href of a link when i press another href

i want to get the attr href of an above link beside the one i press wich is the last link from productinfo div class. I tryed with closest but it gets me the same link i press and i want the above one. The link i want to store in produs_href is the link from first href under productinfo class. Here is my code:
<div class="col-sm-4 produse"><!--PRODUS-->
<div class="product-image-wrapper">
<div class="single-products">
<div class="productinfo text-center">
<img src="/images/produse/'.$recomand['ID_Produs'].'/'.$recomand['Poza'].'" alt="" />
<h2 style="text-decoration: line-through;">'.$recomand['Pret'].' lei </h2><h2>'.$recomand['Pret_Nou'].' lei </h2>
<p>'.$recomand['Nume_Prod'].' '.$recomand['Gramaj'].' '.$tip.'</p>
<i class="fa fa-shopping-cart"></i>Adaugă în coș
</div>
</div>
</div>
</div>
jquery
<script>
$(".cos").click(function(e){
e.preventDefault();
var href = $(this).attr('href');
var produs_href = $(this).closest('a').attr('href');
$.getJSON(href, function(data) {
$.each(data, function(key, val) {
$("#cnt").empty();
$("#test").append('<li>' + val.nume + '</li>')
$("#cnt").append('' + val.cnt +'')
});
});
$(\'#detalii_prod\').modal('show');
alert(produs_href);
});
</script>
Use prev. This method gets the immediately preceding sibling.
$(this).prev().attr('href');
EDIT
From your comments, the code that would do the trick is
$(this).closest('.productinfo').find('a:first').attr('href');
You can use the .prev
var link = $(this).prev().attr('href');
and now you can use link.
you can use like this
$(this).prev("a").attr("href");
and more help:
Get the href value of a previous HTML anchoer, <a>, using jQuery
$(".cos").click(function(e){
e.preventDefault();
var text = $(this).parent().find('a:first').attr('href');
alert(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-4 produse">
<!--PRODUS-->
<div class="product-image-wrapper">
<div class="single-products">
<div class="productinfo text-center"> <img src="img/Penguins.jpg" height="50" width="50" alt="" />
<h2 style="text-decoration: line-through;">Hello there</h2>
<h2>Anto</h2>
<a href="link produs">
<p>Angeline</p>
</a> <i class="fa fa-shopping-cart"></i>Test </div>
</div>
</div>
</div>
try this
$(this).parent().find('a:first').attr('href');
Try with .eq() method.
$(this).parent().find('a').eq(0).attr('href');
Hope this helps you...

Access both html and json data returned from ajax

I have an ajax page to return some data which contains a mix of HTML and Json data.I dont know which data type to use to extract the contents returned from ajax. Currently I used ajax dataType: 'html'
Kindly help me to extract the HTML and Json data from ajax.
I returned the below content from ajax
'{"id" :"Test_p","label" :"Test Property"},{"id" :"29772_l","label" :"Test Locality"},{"id" :"Universal Infrastructure Development Company_c","label" :"Test Company"},{"id" :"Test_p","label" :"Vijay Property"},{"id" :"29772_l","label" :"Vijay Locality"},{"id" :"Universal Infrastructure Development Company_c","label" :"VJ Company"}'
Please find my HTML content
<div data-ride="carousel" class="carousel slide show-number-count featured-carousel" id="carousel-ready-to-move-in" data-interval="false">
<div role="listbox" class="carousel-inner col-max-10 col-center carousel-area" id="readytomovein"><div id="rtmicarousel" class="item active">
<div class="row" id="ready_to_move_in_row"><div class="col-sm-2 col-xs-2">
<div class="col-inner border prop-grid font-small bg-white">
<a href="apartment-for-sale-in-ambattur-chennai-by-loyal-housing-developments-pvt-ltd-3376939" target="_blank">
<img width="200" height="120" alt="" src="http://imgs.indiaproperty.com/images/ip-no-logo2.jpg" class="lazy-load display-block">
<div class="nbh-vtext">Aishwarryam</div>
<p class="color-primary">
<span class="font-semi-bold color-green-l show">₹35.46 Lacs-39.35 L..</span>
<span class="font-semi-bold show color-blue">by Loyal Housing D..</span>Ambattur
</p>
<div class="property-details clearfix font-x-small color-primary">
<span class="pull-left">2 BHK</span>
<span class="pull-right"> </span>
</div>
</a>
</div>
</div></div></div></div>
<a data-slide="prev" role="button" href="#carousel-ready-to-move-in" class="left carousel-nav color-primary">
<i class="icon-dir-left"></i>
</a>
<a data-slide="next" role="button" href="#carousel-ready-to-move-in" class="right carousel-nav color-primary" id="next_slide_id">
<i class="icon-dir-right"></i>
</a>
<div class="slide-number"></div>
</div>
I have to convert this data as javascript array object in ajax success function
Thanks.
Maybe this way: http://jsfiddle.net/IonDen/2L2gnxae/
// Some test ajax result
var result = '{"somejson", "value"}';
result += '<div>Some html</div>';
console.log(result);
// split result to json and html
var sl = result.indexOf("<");
var json = result.slice(0, sl);
var html = result.slice(sl);
console.log(json);
console.log(html);

Display next div on click

Say I have the following HTML layout:
<div class="main">
<div class="comment">
<div class="info">
<div class="data">
<img src="image.png" class="image-click" />
</div>
</div>
</div>
<div class="open-me"></div>
<div class="comment">
<div class="info">
<div class="data">
<img src="image.png" class="image-click" />
</div>
</div>
</div>
<div class="open-me"></div>
<div class="comment">
<div class="info">
<div class="data">
<img src="image.png" class="image-click" />
</div>
</div>
</div>
<div class="open-me"></div>
</div>
... etc ...
How would I make it so that if you click the image in one of the comment classes, it shows HTML in the next open-me class?
Here's what I have so far:
$(document).ready(function() {
$(document).on("click", ".image-click", function() {
$.ajax({
url: 'show_html.php',
type: "POST",
success: function() {
$(this).find(".open-me").html(); /* this is where I'm stuck */
}
});
});
});
this inside your AJAX success method isn't referring to the clicked element anymore. For that, we can set a context variable of this:
$(document).on("click", ".image-click", function() {
var self = $(this);
$.ajax({
url: 'show_html.php',
type: "POST",
success: function(data) {
self.parents(".comment").next(".open-me").html(data);
}
});
});
You can use this to access the sibling open-me. Also, you should save a reference to $(this) outside of the .ajax().
// outside the ajax function
var that = $(this);
// inside the ajax function
that.parent(".comment").next("open-me").html();
jQuery's documentation about next() is relevant.

Categories

Resources