I am trying to build dynamically accordion from ajax(JSON) data.
I need to generate the following html tags, but i can't find convenient way.
<h3></h3>
<div>
<p> </p>
</div>
The accordion works with the < li > tag I've used to append to, but it's dirty solution and I don't like it. There should be a way to do it in more beautiful way.
Please help to a noob, thank you!
$.ajax({
url: '/getCar',
type: 'GET',
success: function(res) {
var delCarPost = $('<form>').attr('method', 'post').append($('<input>').attr({
type: "hidden",
name: "carid",
id: "carid"
}),
$('<input>').attr({
type: "submit",
value: "delete"})
);
// var div = $('<h4>').before($('<div>').append($('<p>')));
var div = $('<div>').append($('<p>'))
div = $("<li>").append($('<h4>'),$(div))
// var div = $("<li>").append($('<h4>'),$('<div>').append($('<p>')));
var carObj = JSON.parse(res);
var car = '';
$.each(carObj,function(index, value){
car = $(div).clone();
$(car).find('h4').text(value.make + " from " + value.year + " at price " + value.price);
$(car).find('p').text(value.info);
$('#accordion').append(car);
$("#accordion").accordion("refresh");
console.log(div);
});
$('#accordion').on( 'click', 'button', function () {
post('/delCar', {postMake: value.make}, "post");
});
},
error: function(error) {
console.log(error);
}
});
Here is an answer that may help you. I left some comments inside:
$.ajax({
url: '/getCar',
type: 'GET',
"dataType": "json", //no need to JSON.parse
success: function(cars) {
//you should specify where you append those nodes ...
var delCarPost = $('<form>').attr('method', 'post').append(
$('<input>').attr({
type: "hidden",
name: "carid",
id: "carid"
}),
$('<input>').attr({
type: "submit",
value: "delete"
})
);
//bellow a simplified version
var html = '';
$.each(cars,function(index, car){
html += [
'<li>',
'<h3>' + car.make + ' from ' + car.year + ' at price ' + car.price + '</h3>',
'<div>',
'<p>' + car.info + '</p>',
'</div>',
'<li>'
].join('');
});
//cache your access to jQuery
var accordion = $('#accordion');
accordion.html(html);//innerHTML everything above in one time (only one DOM access)
accordion.accordion("refresh");
accordion.on( 'click', 'button', function () {
post('/delCar', {postMake: value.make}, "post");
});
},
error: function(error) {
console.log(error);
}
});
I've found better solution using Mustache.js templates.
Since I use Jinja templates + Mustache the template looks like this:
{% raw %}
<script id="CarAccTemplate" type="x-tmpl-mustache">
<h3 id='{{ id }}'> {{ make }} from {{ year }} at price {{ price }}
<div class="pull-right action-buttons">
<a id='delcar-{{ id }}' onclick="ConfirmDelete(this)">
<span class="glyphicon glyphicon-trash"></span>
</a>
</div>
</h3>
<div>
<p>{{info}}</p>
</div>
</script>
{% endraw %}
and in js
$.ajax({
url: '/getCar',
type: 'GET',
"dataType": "json", //no need to JSON.parse
success: function(cars) {
//bellow a simplified version
var html = '';
$.each(cars,function(index, car){
var template = $('#CarAccTemplate').html();
Mustache.parse(template)
var rendered = Mustache.render(template, car);
html += rendered;
});
//cache your access to jQuery
var accordion = $('#accordion');
accordion.html(html);//innerHTML everything above in one time (only one DOM access)
$( "#accordion" ).accordion({heightStyle: "content"});
accordion.accordion("refresh");
//feed the form on click event
$('#accordion h3').on("click select focus", function(e){
//parse the text
carid = $(this).attr('id');
text = $(this).text();
make = text.split("from",1)[0].trim();
year = text.match(/from (.*)/)[1].match(/^\d+/)[0].trim();
price = text.match(/price (.*)/)[1].trim();
info = $('div[aria-labelledby=' + carid + "]").children('p').text();
// console.log($('form[id="addCar"] fieldset div'));
// feed form with values from accordion
$('.form-group #inputYear:text').val(year);
$('.form-group #inputMake:text').val(make);
$('.form-group #inputPrice:text').val(price);
$('.form-group #inputInfo').val(info);
$('.form-group #carId').val(carid);
});
// accordion.on( 'click', 'button', function () {
// post('/delCar', {postMake: value.make}, "post");
// });
},
error: function(error) {
console.log(error);
}
});
Related
I want send arrays of data to back-end at once but i can't.
issue
1.
this is what i send currently
array:5 [
"_token" => "S5s5ZTTnnP93MyXgCql0l9vhHsiqt5VWaFyEedXj"
"product_id" => "21"
"specification_id" => "6"
"text_dec" => "1"
"longtext_dec" => null
]
It should be like:
Array [
0 = [
data
]
1 = [
data
]
2 = [
data
]
]
I always get same ID as specification_id while each row in my blade has different ID
Code
appending script
<script defer>
$(document).ready(function() {
//select the category
$('select[name="selectset"]').on('change', function() {
var id = $(this).val();
if(id) {
$.ajax({
url: '{{ url('admin/selectset') }}/'+encodeURI(id),
type: "GET",
dataType: "json",
success:function(result) {
//sort the results
result.sort(function(a,b) {
return (a.position > b.position) ? 1 : ((b.position > a.position) ? -1 : 0);
});
$.each(result, function(key1, value1) {
var vvvid = value1.id;
//textfield and textareafield are part of my issue (appended rows)
if(value1['type'] == 'textfield'){
var my_row = $('<div class="row mt-20 ccin">');
$('div#dataaa').append(my_row);
}else{
var my_row = $('<div class="row mt-20 ccin">');
$('div#dataaa').append(my_row);
}
// second data (get values)
$.ajax({
url: '{{ url('admin/findsubspecification') }}/'+value1['id'],
type: "GET",
dataType: "json",
success:function(data) {
// Check result isnt empty
var helpers = '';
$.each(data, function(key, value) {
helpers += '<option value="'+value.id+'">'+value.title+'</option>';
});
//this is the part of my issue
if(value1['type'] == 'textfield'){
var my_html = '{{ Form::open() }}<input name="product_id" id="product_id" type="hidden" value="{{$product->id}}"><input name="specification_idd" class="specification_idd" id="specification_idd" type="hidden" value="'+vvvid+'"><div class="col-md-4">'+value1.title+'</div>';
my_html += '<div class="col-md-6"><input id="text_decc" name="text_decc" placeholder="text field" class="text_decc form-control"></div>';
my_html += '<div class="col-md-2"><button type="button" id="custmodalsaveee" class="custmodalsaveee btn btn-xs btn-success">Save</button>{{Form::close()}}</div>';
my_row.html(my_html);
}else{ //second part of my issue
var my_html = '{{ Form::open() }}<input name="product_id" id="product_id" type="hidden" value="{{$product->id}}"><input name="specification_idd" class="specification_idd" id="specification_idd" type="hidden" value="'+vvvid+'"><div class="col-md-4">'+value1.title+'</div>';
my_html += '<div class="col-md-6"><textarea id="longtext_decc" name="longtext_decc" placeholder="text area field" class="longtext_decc form-control"></textarea></div>';
my_html += '<div class="col-md-2"><button type="button" id="custmodalsaveee" class="custmodalsaveee btn btn-xs btn-success">Save</button>{{Form::close()}}</div>';
my_row.html(my_html);
}
}
});
// second data
});
}
});
}
});
});
</script>
result of code above is like:
saving script the part that should be fixed
<script>
$(document).ready(function() {
$("body").on("click", ".custmodalsaveee", function(e){
var id = $('input[name="product_id"]').val();
$.ajax({
type: "post",
url: "{{ url('admin/addnewcustomsubspecifications') }}",
data: {
'_token': $('input[name=_token]').val(),
'product_id': id,
'specification_id': $('.specification_idd').val(),
'text_dec': $('.text_decc').val(),
'longtext_dec': $('.longtext_decc').val(),
},
success: function (data) {
alert('Specification added successfully in your product!');
},
error: function (data) {
console.log('Error!', data);
}
});
});
});
</script>
controller
public function addnewcustomsubspecifications(Request $reqss){
dd($reqss->all());
// $this->validate($reqss, array(
// 'product_id' => 'required',
// 'specification_id' => 'required',
// 'text_dec' => 'nullable',
// 'longtext_dec' => 'nullable',
// ));
// $add = CustomProductSpecification::create([
// 'product_id' => $reqss->product_id,
// 'specification_id' => $reqss->specification_id,
// 'text_dec' => $reqss->text_dec,
// 'longtext_dec' => $reqss->longtext_dec,
// ]);
// $parent = Specification::where('id', '=', $reqss->specification_id)->first();
// return response()->json(array('data'=>$add,'parent'=>$parent));
}
Any idea?
Update
html output
Update2
So based on suggestions i've used .map() here is my code and the results
script
$(document).ready(function() {
$("body").on("click", ".custmodalsaveee", function(e){
var id = $('input[name="product_id"]').val();
var specification_idd = $( ".ccin" ).map(function() {
return $( this ).find('.specification_idd').val();
return $( this ).find('.text_decc').val();
return $( this ).find('.longtext_decc').val();
}).get();
var text_decc = $( ".ccin" ).map(function() {
return $( this ).find('.text_decc').val();
}).get();
var longtext_decc = $( ".ccin" ).map(function() {
return $( this ).find('.longtext_decc').val();
}).get();
console.log(specification_idd);
console.log(text_decc);
console.log(longtext_decc);
$.ajax({
//rest of it as it was...
and the console results
Question
How do i get related results together? specification_id and text fields as 1 array
how I avoid of empty values? if text_dec and longtext_dec are empty for each specification_id doesn't need to be send example specification 40 doesn't have any value in longtext_dec or text_dec no need to be send
Robert, you should directly return view from your Ajax call in your laravel method and just bind html response from the view with your new data.
That is pretty easy way of doing it.
I'm working at a comment system for a website.
I am using jquery to update the view after comment under post is posted.
The element I am pushing the comment after post is like this:
<p class="card-text new_comment_{{$i->id}}" style="display:none"></p>
So what I do is
//Manages post in view
jQuery(function ($) {
$(document).ready(function () {
$("body").on("submit", ".dynamic-form", function (e) {
var form_id = '#' + $(this).attr('id');
//removes the 'post_' part from id
var id = this.id.replace('post_', '');
var new_comment_class = '.new_comment_' + id;
var new_comment_class_removal = 'new_comment_' + id;
var comments_id = '#comments_' + id;
var form = $(this);
$.ajax({
url: form.prop('action'),
type: 'post',
dataType: 'json',
data: $(this).serialize(),
success: function (data) {
var resultStr = "";
resultStr = resultStr + "<a href=\"#\">" + data.user_name + " <\/a>" + data.body ;
$(comments_id).find(new_comment_class).html(resultStr).slideToggle(150).promise().done(function () {
$(new_comment_class).fadeIn("fast").toggleClass(new_comment_class_removal);
});
$(form_id).slideToggle(150).promise().done(function () {
$(form_id).fadeOut("fast");
});
}
});
e.preventDefault();
});
});
});
so after the javascript gets executed the element loses the class that permits me to find it in the view so that if the user posts again the body of the post doesn't get appended to that element. But now how do I put a new target element as the original one just above the newly creatded one? like this:
<p class="card-text new_comment_{{$i->id}}" style="display:none"></p>
<p class="card-text">This is the body of the comment</p>
solved using http://api.jquery.com/before/ and some temp variables
I am using PHPstorm IDE and i'm trying to render the following JSON and it gets stuck showing only the <ul></ul> without spitting the <li>'s into HTML the each function. Any idea what could be the issue?
thanks.
Script.js:
$(function(){
$('#clickme').click(function (){
//fetch json file
$.ajax({
url:'data.json',
dataType: 'json',
success: function(data){
var items = [];
$.each(data, function (key, val) {
items.push('<li id=" ' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'tasks',
html: items.join('')
}).appendTo('body');
},
statusCode: {
404: function(){
alert('there was a problem with the server. try again in a few secs');
}
}
});
});
});
And the JSON:
{"id":"1","mesi":"mesima 0","done_bool":"1"},{"id":"2","mesi":"mesima 1","done_bool":"0"},{"id":"3","mesi":"mesima 2 ","done_bool":"1"},{"id":"4","mesi":"mesima 3","done_bool":"1"}
My HTML is just an a href that spits out the click ID:
Get JSON
<script>
$(document).ready(function(){
$("button").click(function(){
$.getJSON("demo_ajax_json.js", function(result){
$.each(result, function(i, field){
$("div").append(field + " ");
});
});
});
});
</script>
<button>Get JSON data</button>
By Using this Method You can Easily get Your JSON value In HTML
Try this one :)
$.ajax({
url: 'data.json',
dataType: 'json',
success: function(data){
var html = "<ul>";
items = data.map(function(obj){
html += "<li id='" + obj.id + "'>" + obj.mesi + "</li";
});
html += "</ul>";
$('body').append(html);
I would try with some like this
$(function(){
$('#clickme').click(function (){
//fetch json file
$.ajax({
url:'data.json',
dataType: 'json',
success: function(data){
// uncomment line below if data is a single JSON
// data = [data]
var items = [];
// we create a list where we will append the items
var list = document.createElement("ul");
data.forEach(function(item){
// we create a list item
var listItem = document.createElement("li");
// we set the attributes
listItem.setAttribute("id", item.id ); // item.id or the property that you need
// we add text to the item
listItem.textContent = item.mesi;
// We append the list item to the list
list.appendChild(listItem);
});
// we append the list to the body
$("body").html(list);
},
statusCode: {
404: function(){
alert('there was a problem with the server. try again in a few secs');
}
}
});
});
});
Try like this:
success: function(data){
var items = '';
$.each(data, function (key, val) {
items += '<li id=" ' + key + '">' + val + '</li>';
});
ul = $('<ul/>').html(items);
$('body').append(ul);
}
for multiple objects
success: function(datas){
var items = '';
$.each(datas, function (i,data) {
$.each(data, function (key, val) {
items += '<li id=" ' + key + '">' + val + '</li>';
});
});
ul = $('<ul/>').html(items);
$('body').append(ul);
}
output
<ul>
<li id=" id">1</li>
<li id=" mesi">mesima 0</li>
<li id=" done_bool">1</li>
<li id=" id">2</li>
<li id=" mesi">mesima 1</li>
.
.
</ul>
Try like this:
$(function() {
$('#clickme').click(function() {
// fetch json file
$.ajax({
url : 'data.json',
dataType : 'json',
// please confirm request type is GET/POST
type : 'GET',
success : function(data) {
// please check logs in browser console
console.log(data);
var ulHtml = "<ul>";
$.each(data, function(key, obj) {
ulHtml += '<li id="' + obj.id + '">' + obj.mesi + '</li>';
});
ulHtml += "</ul>";
// please check logs in browser console
console.log(ulHtml);
$('body').append(ulHtml);
},
error : function(jqXhr, textStatus, errorThrown) {
console.log(errorThrown);
alert(textStatus);
}
});
});
});
<button id="clickme">Get JSON data</button>
I log json data and created ul html, Please check logs in browser console
I'm not sure how you want to output each item, so I made a simple suggestion, you can easily change the HTML to what you need. Here is working code:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
<body>
Get JSON
<script>
$(function() {
$('#clickme').click(function() {
//fetch json file
$.ajax({
url: 'data.json',
dataType: 'json',
success: function(data) {
var items = [];
$.each(data, function(key, val) {
// the HTML output for each item
var done = (val.done_bool === '1') ? 'true' : 'false';
items.push('<li id=" ' + val.id + '">' + val.mesi + ': ' + done + '</li>');
});
$('<ul/>', {
'class': 'tasks',
html: items.join('')
}).appendTo('body');
},
statusCode: {
404: function() {
alert('there was a problem with the server. try again in a few secs');
}
}
});
});
});
</script>
</body>
</html>
data.json
[{"id":"1","mesi":"mesima 0","done_bool":"1"},{"id":"2","mesi":"mesima 1","done_bool":"0"},{"id":"3","mesi":"mesima 2 ","done_bool":"1"},{"id":"4","mesi":"mesima 3","done_bool":"1"}]
I also created a __jsfiddle__ so you can test it directly. (The AJAX call is simulated with the Mockjax library): https://jsfiddle.net/dh60nn5g/
Good to know:
If you are trying to load the JSON from another domain, you may need to configure CORS (Cross-origin resource sharing):
https://en.wikipedia.org/wiki/Cross-origin_resource_sharing
Isn't this supposed to be a GET request? i think you are missing the method on your Ajax request. You should add
method: 'GET'
to your ajax request. I think this is a big deal in making ajax request.
I've following HTML code :
<select id="student" name="student" class="form-control"></select>
The jQuery-AJAX function I've written for adding the options to the above HTML select control is as follows :
var mod_url = $('#mod_url').val();
$.ajax({
url : mod_url,
cache: false,
dataType: "json",
type: "GET",
async: false,
data: {
'request_type':'ajax',
},
success: function(result, success) {
$('#student').html(result);
},
error: function() {
alert("Error is occured");
}
});
From PHP file I've received a big array encoded into JSON format(i.e. the result variable from jQuery-AJAX function). For your reference I'm showing below only the first four records from that array. In HTML select control actually I want to show all the elements from this array.
[{"id":2,"stud_name":"John Dpalma","stud_address1":"277 Eisenhower Pkwy","stud_address2":"","stud_city":"Edison","stud_state":"New Jersey","stud_country":"USA","stud_zipcode":"07039","stud_email":"abc#gmail.com","created_at":1409739580,"updated_at":1410253832},
{"id":3,"stud_name":"Anthony Gonsalvis","stud_address1":"520 Division St","stud_address2":"","stud_city":"Piscataway","stud_state":"NJ","stud_country":"USA","stud_zipcode":"07201","stud_email":"pqr#gmail.com","created_at":1409740530,"updated_at":1410255590},
{"id":4,"stud_name":"James Bond","stud_address1":"6 Harrison Street, 6th Floor","stud_address2":"Ste-2324","stud_city":"New York","stud_state":"NY","stud_country":"USA","stud_zipcode":"10013","stud_email":"xyz#gmail.com","created_at":1409757637,"updated_at":1412263107},
{"id":9,"stud_name":"Mary Jane","stud_address1":"2112 Zeno Place","stud_address2":"CA","stud_city":"Venice","stud_state":"CA","stud_country":"","stud_zipcode":"90291","stud_email":"utp#gmail.com","created_at":1409908569,"updated_at":1410254282}]
In HTML select control I want to set the values in following manner(consider first two records from above array)
<select id="student" name="student" class="form-control">
<option value="">Select Store</option>
<option value="2">John Dpalma, 277 Eisenhower Pkwy, Edison</option>
<option value="3">Anthony Gonsalvis, 520 Division St, Piscataway</option>
</select>
You might have observed from the expected output above that I want to set the value of option as a id from array and the text that I want to display is comprising of stud_name+stud_address1+stud_city
How should I manage this for all the elements from the JSON data in my code?
Also please guide me in showing the loading option into the select control until the response from PHP comes.
Please provide me some help.
success: function(result, success) {
var $select = $('#student');
$.each(result, function (i, option) {
var txt = [option.stud_name, option.stud_address1, option.stud_city];
if (option.stud_address2)
txt.splice(2, 0, option.stud_address2);
$('<option>', {
value: option.id,
text: txt.join(', ')
}).appendTo($select);
});
},
or with $.map (slightly more efficient):
success: function(result, success) {
var options = $.map(result, function (option) {
var txt = [option.stud_name, option.stud_address1, option.stud_city];
if (option.stud_address2)
txt.splice(2, 0, option.stud_address2);
return $('<option>', {
value: option.id,
text: txt.join(', ')
});
});
$('#student').append(options);
},
In PHP file echo the following in a loop:
echo '<option value="">'.$stud_name.', '.$stud_address1.', '.$stud_address2.', '.$stud_city.', '.$stud_state.', '.$stud_country.'</option>';
Then attach this result to the select dropdown with jQuery through the ajax success.
Here is my solution. This checks address 2 and adds it to the options accordingly.
JS code:
for(var i=0;i<result.length;i++){
if(result[i]["stud_address2"]==""){
$('#student').append('<option value="' + result[i]["id"] + '">' + result[i]["stud_name"] + ', ' + result[i]["stud_address1"]+ ', ' +result[i]["stud_city"] +'</option>');}
else{
$('#student').append('<option value="' + result[i]["id"] + '">' + result[i]["stud_name"] + ', ' + result[i]["stud_address1"]+ ', '+ result[i]["stud_address2"]+ ', ' +result[i]["stud_city"] +'</option>');
}
}
Here is a working DEMO
This is exactly what you need!
$(document).ready(function(){
var mod_url = $('#mod_url').val();
$.ajax({
url : mod_url,
cache: false,
dataType: "json",
type: "GET",
async: false,
data: {
'request_type':'ajax',
},
success: function(result, success) {
$.each(result,function(index,item){
$label = item.stud_name +', ' + item.stud_address1 +', ' + item.stud_city;
$('#student').append('<option value="'+ item.id +'">'+ $label +'</option>');
});
},
error: function() {
alert("Error is occured");
}
});
});
It's a matter of iterating over the JSON you receive from the server, creating option tags for each record, then appending them to the select element:
var response = [{"id":2,"stud_name":"John Dpalma" ... }]
$.each(response, function (index, record) {
if (!record.stud_address2){
var stud_address2 = "";
} else {
var stud_address2 = record.stud_address2;
}
$('<option>', {
value: record.id,
text: record.stud_name + ", " + record.stud_address1 + ", " + record.stud_city + ", " + stud_address2
}).appendTo("#student");
});
Demo
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<script>
function __highlight(s, t) {
var matcher = new RegExp("(" + $.ui.autocomplete.escapeRegex(t) + ")", "ig");
return s.replace(matcher, "<strong>$1</strong>");
}
$(document).ready(
function() {
$("#suggest").autocomplete(
{
source : function(request, response)
{
$.ajax({
url : 'URL',
dataType : 'json',
data : { term : request.term },
success : function(data)
{
//alert(data[0].title);
response($.map(data, function(item) {
//alert(item);
return {
label : __highlight(item.title, request.term),
value : item.title
};
}));
}
});
},
minLength : 3,
select : function(event, ui)
{
if(ui.item){
$(event.target).val(ui.item.value);
}
//submit the form
$(event.target.form).submit();
}
}).keydown(function(e) {
if (e.keyCode === 13)
{
$("#search_form").trigger('submit');
}
}).data("autocomplete")._renderItem = function(ul, item)
{
return $("<li></li>").data("item.autocomplete", item).append(
$("<a></a>").html(item.label)).appendTo(ul);
};
});
</script>
Shopify has a max display limit of 50 products per page.
To get around this limitation I've made a jquery code snippet. The script grabs the url from each pagination link, and performs an ajax load - adding the result to the main content area.
It worked perfectly for me - but not for my friend. He was missing a page each time. So I thought it may be an async issue with his connection being slower than mine. So I rewrote the script a few times to be more explicit. But it still didn't work for him.
After much trouble shooting, it appears that if logged in as admin - everything works. If not logged in, then the middle page fails to load.
Here is my most recent code:
{% if template contains 'collection' %}
<script>
$(document).ready(function() {
$('#viewFewerProducts').hide();
// when viewAllProducts is clicked
$("#viewAllProducts").click( function (e) {
e.preventDefault();
$("#viewAllProducts , #paginationMagic").hide(); // hide pagination buttons
// and clear out collectionThumbs - but add the ViewAllRow back in.
$("#collectionThumbs").empty().html('<div class="row" id="viewAllRow"></div>');
// see how many pagination links there are. Add 1 because of index 0
var numberOfPages = $('#paginateNumbers .item').length + 1
var path = window.location.pathname;
var pageURL;
// this bit adapted from blog post... but cant remember url
for (var i=1;i<numberOfPages;i++) {
$.ajax(
{
type: 'GET',
url: pageURL = path + "?page=" + i, // build pagination page url
ajaxI: i, // Capture the current value of 'i'.
success: function(data)
{
i = this.ajaxI; // Reinstate the correct value for 'i'.
$(data).find('#collectionThumbs').each(function()
{
// Read data... and stick it in the page
var importedCollection = $(data).find("#collectionThumbs a").unwrap();
importedCollection.appendTo("#viewAllRow");
});
},
error: function(data)
{
// Handle errors here.
}
});
}
///
$("#viewFewerProducts").show();
});
// reload the window
$("#viewFewerProducts").click( function (e) {
e.preventDefault();
$("#viewFewerProducts").text('loading...').removeAttr('id');
location.reload();
});
});
</script>
{% endif %}
and I've written it several other different ways. It just doesn't work if not logged in? I've checked - and dont get any errors in the console either.
So my question is - does anyone know why it would work if logged in, but not if not logged in to admin? Its really bizzarre - as this is not running on any admin pages.
Edit:
{% if template contains 'collection' %}
<script>
$(document).ready(function() {
$('#viewFewerProducts').hide();
$("#viewAllProducts").click( function (e) {
e.preventDefault();
$("#viewAllProducts , #paginationMagic").hide();
var numberOfPages = $('#paginateNumbers .item').length + 1
var path = window.location.pathname;
// console.log(path);
var pageURL;
//
for (var i=1;i<numberOfPages;i++) {
// console.log(i + 'a')
$.ajax(
{
type: 'GET',
url: pageURL = path + "?page=" + i,
beforeSend: function() {
$("#collectionThumbs").empty();
},
ajaxI: i, // Capture the current value of 'i'.
success: function(data)
{
i = this.ajaxI; // Reinstate the correct value for 'i'.
$(data).find('#collectionThumbs').each(function() {
// Read data from XML...
$('<div class="row" id="viewAllRow' + i + '"></div>').appendTo("#collectionThumbs");
var importedCollection = $(data).find("#collectionThumbs a").unwrap();
importedCollection.appendTo("#viewAllRow" + i );
// alert("now showing " + ($("#viewAllRow" + i + " a").length) + " products" );
});
var numberOfRows = $('#collectionThumbs .row').length + 1
var viewAllRowItem = []
for (var x=1;x<numberOfRows;x++) {
//put each row into a variable
viewAllRowItem[x] = $("#viewAllRow" + x ).clone();
$("#viewAllRow" + x ).remove();
// console.log(viewAllRowItem[x])
}
for (var x=1;x<numberOfRows;x++) {
$(viewAllRowItem[x]).appendTo('#collectionThumbs');
}
},
dataType: "html",
error: function(data)
{
// Handle errors here.
}
});
}
$("#viewFewerProducts").show();
});
$("#viewFewerProducts").click( function (e) {
e.preventDefault();
$("#viewFewerProducts").text('loading...').removeAttr('id');
location.reload();
});
});
</script>
{% endif %}
The above code seems to work - not sure why... was a process of elimination. I did have to add a bit of code to reorder the elements once loaded (as some ajax responses came back more quickly than others - and appeared on the page in the wrong order).
$('[js-load-more]').on('click', function(){
var $this = $(this),totalPages = parseInt($('[data-total-pages]').val()),currentPage = parseInt($('[data-current-page]').val());
$this.attr('disabled', true);
$this.find('[load-more-text]').addClass('hide');
$this.find('[loader]').removeClass('hide');
currentPage = currentPage+1;
var nextUrl = $('[data-next-url]').val().replace(/page=[0-9]+/,'page='+currentPage);
$('[data-current-page]').val(currentPage);
$.ajax({
url: nextUrl,
type: 'GET',
dataType: 'html',
success: function(responseHTML){
$('.grid--view-items').append($(responseHTML).find('.grid--view-items').html());
},
complete: function() {
if(currentPage >= totalPages) {
$this.remove();
}
else {
$this.attr('disabled', false);
$this.find('[load-more-text]').removeClass('hide');
$this.find('[loader]').addClass('hide');
}
}
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<input type="hidden" value="{{ paginate.next.url }}" data-next-url>
<input type="hidden" value="{{ paginate.pages }}" data-total-pages>
<input type="hidden" value="{{ paginate.current_page }}" data-current-page>
<div class="load-more_wrap">
<button class="btn" js-load-more>
<span load-more-text>Load more</span>
<span class="hide" loader></span>
</button>
</div>