Ajax call inside class attribute - javascript

I'm moving a php / js / ajax script to wordpress
I encountered something that i've never seen before, I understand what it does, but i'm trying to figure out how to make this work for wordpress.
the code:
<a id="a" class="tab block sel {content:'cont_1', ajaxContent:'php/templates.php',ajaxData:'type=pistols'}">Pistols</a>
<a id="b" class="tab block {content:'cont_2', ajaxContent:'php/templates.php',ajaxData:'type=rifles'}">Rifles</a>
<a id="c" class="tab block {content:'cont_3', ajaxContent:'php/templates.php',ajaxData:'type=shotguns'}">Shotguns</a>
<a id="d" class="tab block {content:'cont_4', ajaxContent:'php/templates.php',ajaxData:'type=cameras'}" >Cameras</a>
<a id="e" class="tab block {content:'cont_4', ajaxContent:'php/templates.php',ajaxData:'type=audios'}" >Audio</a>
Templates PHP:
if(isset($_POST['type'])) {
//The div for the manufacturer tabs, uniquely identified by the $_POST['type']
echo "<ul id=\"".$_POST['type']."\" class=\"shadetabs\" style=\"position:relative; top:-12px; width:905px;\">";
if ($_POST['type'] === 'pistols') {
$manufacturers = .. and so on
From what i can understand, we are calling Templates.php and passing $_POST['type']. When this is compoleted, the script replaces the content of a <div id="cont_1"
in wordpress, i can't call random php files, since ajax will not work. I need to turn this into a function and hook it to wordpress.
Does anyone know how this type of code works?
As alternative, I'm planning to do the following, but I would prefer to keep it similar to the original code and this will need lots of extra lines of code.
var tab = jQuery("#a").type;
jQuery.ajax({
url: custom_designer.ajax_url,
type: 'post',
data: {
action: 'php_template_function'
type: tab
},
success: function (response) {
document.getElementById('caseclub_response').innerHTML = response;
document.getElementById("buy_case_foam_added").submit();
}
});

Does anyone know how this type of code works?
It looks like there is some JavaScript that extracts the object string from the class attribute, then fetches the HTML from template.php and writes it somewhere.
For example:
function fetchList(element) {
var settings = element.className.match(/\{.+\}/);
settings = eval('(' + settings[0] + ')') // eww
fetch(settings.ajaxContent, {
method: 'post',
body: settings.ajaxData
}).then((response) => {
// Error handling...
response.text().then(() => {
// Now writes the HTML somewhere...
});
});
}
If you want to copy what they did, see if you can find the original code using the Inspector.

Related

Data update without page reload jinja2

The data has to be refreshed without page reload. Originally data is appeared on html with jinja2.
#app.route('/personal_account', methods=['POST'])
def welcome():
login = request.form['login']
data = get_default_user_data(login)
# ... processing
return render_sidebar_template("personal_account.html", data=data)
According to these data graph is building with chartist.js.
personal_account.html
<div id="data">
<ul id="consumed_values">
{% set count = 0 %}
{% for i in data.consumed_values %}
<li>{{ data.consumed_values[count] }}</li>
{% set count = count + 1 %}
{% endfor %}
</ul>
</div>
<canvas width="800" height="600" id="canvas"></canvas>
<button id="button">Update</button>
I need to update data. I am using ajax.
The function "request" make a post request to the server to the function get_selected_values in Python.
This function gives new data. But new data doesn't display in jinja2 on page. The data is still old.
personal_account.js
window.onload = draw();
function draw() {
var consumed_values = document.querySelectorAll('ul#consumed_values li');
var values = new Array();
for (var i = 0; i < consumed_values.length; i++) {
console.log(consumed_values[i].innerHTML);
values[i] = consumed_values[i].innerHTML;
}
var numbers = new Array();
for(var i=0; i<consumed_values.length; i++)
{
numbers[i]=i+1;
console.log(numbers[i]);
}
var ctx = document.getElementById('canvas').getContext('2d');
var grapf = {
labels : numbers,
datasets : [
{
strokeColor : "#6181B4",
data : values
}
]
}
new Chart(ctx).Line(grapf);
}
document.getElementById('button').onclick=function () {
request();
}
function reques() {
var first = selected[0];
var second = selected[1];
first.month = first.month+1;
second.month = second.month+1;
$.ajax({
type: 'POST',
url: '/get_selected_values',
success: function(response) {
alert('Ok');
draw();
},
error: function() {
alert('Error');
}
});
}
Function get_selected_values()
#app.route('/get_selected_values', methods=['POST'])
def get_selected_values():
# ...
data = fetch_selected_date(start_date=start_date, end_date=end_date, login=current_user.get_id())
if data:
# return jsonify({'result': True, 'data': data}) # does not work this way
# return jsonify({'result': False, 'data': []})
return render_sidebar_template("personal_account.html", data=data, result=1)
How to succeed in data's update and graph's rebuild?
EDIT 1
I am using the first version of get_selected_values function.
The request function look like this:
...
success: function(response) {
alert('Успешно получен ответ:!'+ response.data);
document.getElementById('consumed_values').innerHTML = response.data;
draw();
},
...
Data is updating successfully, but graph looks the same. How to fix?
OK here's my outlook on this. You're on the right track and there is a way to update the element without the need to re-draw the page in this instance. What's happening is that you are returning data from your get_selected_values() method but not doing anything with it once it's returned to your AJAX request.
So firstly, I'm going to draw your attention to your AJAX request:
$.ajax({
type: 'POST',
url: '/get_selected_values',
success: function(response) {
alert('Ok');
draw();
},
error: function() {
alert('Error');
}
});
When you're getting a successful response from this, you're seeing your "OK" alert in the UI, right? However nothing updates in the UI despite you calling on the draw() method?
You won't want to return a render_template from your Flask function in this case. You were already on the right track with returning JSON from your function:
if data:
# return jsonify({'result': True, 'data': data}) # does not work this way
When you return your JSON data, it will be stored in the response variable in your success function. If you're unsure of exactly what's going into that response variable then output its contents with something like alert(JSON.stringify(response)) in the success function of your AJAX request. From here you will see your data returned to your method.
Now you need to decide how you want to use that data to update your <div id="data"> element in your UI. You can do this just using JavaScript with a series of document.getElementById('element_id').innerHTML statements or such-like so that your element is populated with all of the updated data from your response.
This will auto-update the data you wish to have displayed without the need to refresh the page.
Now that you've done that, invoke your draw() function again and it should now use the updated data.
I hope this helps set you down the right path with this one!
AFTER EDIT 1
When you're originally populating <div id="data"> you are using a loop to populate a series of <li> tags in the element with your data.
When you are updating this element with your new data, you are just using .innerHTML to re-populate the parent <ul> element.
Your draw() method is looking to the data stored in the <li> elements.
Are you absolutely certain that, after you perform your update, your <div id="data"> element is in exactly the same (ie. expected) format to work with your draw() method? In that it's still in the structure:
<div id="data">
<ul id="consumed_values">
<li>Your updated data here...</li>
<li>More updated data...</li>
</ul>
</div>
This is the element structure that your draw() method is expecting to find. It's pulling its data in from each individual <li> element in the list. So these are the elements which need to store your updated values.

How to receive AJAX (json) response in a divs with same class name individually?

I've been getting crazier day after day with this, I can't find an answer, I've spent like 100h+ with this... I hope someone could help me out!
UPDATE:
So to make myself more clear on this issue and be able to get help from others, I basically have 3 containers named "main-container" they all have 3 containers as childs all with the same class name, and when I submit the button, I trigger an ajax function to load the JSON strings comming from php into the child divs, the problem is that I get the 3 "main_containers" to load the ajax at the same time, I only want to load the ajax if I press the button of each "main_container" individually.
I've been using jquery and vanilla JS as well but seems I just can't get it done!
This is how I currently trigger the button with jquery:
$('.trigger_button_inside_divs').click(my_ajax_function);
And this is how my ajax looks like:
function my_ajax_function(){
$.ajax({
dataType: "JSON",
type: 'POST',
url: test.php,
success: function(data) {
$('.div_to_render_JSON_1').html(data.PHP_JSON_1_RECEIVED);
$('.div_to_render_JSON_2').html(data.PHP_JSON_2_RECEIVED);
$('.div_to_render_JSON_3').html(data.PHP_JSON_3_RECEIVED);
}
});
}
HTML looks like this:
<div class="main_container">
<div class="my_div">
//div_to_render_JSON_1
</div>
<div class="my_div">
//div_to_render_JSON_2
</div>
<div class="my_div">
//div_to_render_JSON_3
</div>
<button class="trigger_ajax_function_btn">Click to load ajax</button> //this btn loads ajax into the div class "my_div"
</div>
<div class="main_container">
<div class="my_div">
//div_to_render_JSON_1
</div>
<div class="my_div">
//div_to_render_JSON_2
</div>
<div class="my_div">
//div_to_render_JSON_3
</div>
<button class="trigger_ajax_function_btn">Click to load ajax</button> //this btn loads ajax into the div class "my_div"
</div>
<div class="main_container">
<div class="my_div">
//div_to_render_JSON_1
</div>
<div class="my_div">
//div_to_render_JSON_2
</div>
<div class="my_div">
//div_to_render_JSON_3
</div>
<button class="trigger_ajax_function_btn">Click to load ajax</button> //this btn loads ajax into the div class "my_div"
</div>
So in conclusion, each of those 6 "divs" has a button that triggers an function containing my ajax to render inside that particular div. But what I get is that every time I click that triggering button, I get the ajax to render in all of the 6 divs, instead of render on each particular div only when I click its particular button.
Thanks a lot people, I really hope to get this done!
Cheers.
PD:
This is something a programmer did to achieve what I'm trying to achieve but I just can't figure out what in this code is that is making possible clicking 1 button and affect THAT html element , even though they all have the same class.
(function(){
$("form input[type=submit]").click(function() {
$("input[type=submit]", $(this).parents("form")).removeAttr("clicked");
$(this).attr("clicked", "true");
});
var xhr = new XMLHttpRequest();
var el;
function SetDataInTheForm()
{
var resp = JSON.parse(xhr.response)
var pt=0
var ct=0
var gt=0
Array.prototype.forEach.call(el.querySelectorAll(".test"),function(e,i){
e.innerHTML=resp[i].name
})
Array.prototype.forEach.call(el.querySelectorAll(".p"),function(e,i){
e.innerHTML=parseFloat(resp[i].p).toFixed(0)
pt+=parseFloat(resp[i].p)
})
Array.prototype.forEach.call(el.querySelectorAll(".c"),function(e,i){
e.innerHTML=parseFloat(resp[i].c).toFixed(0)
ct+=parseFloat(resp[i].c)
})
Array.prototype.forEach.call(el.querySelectorAll(".g"),function(e,i){
e.innerHTML=parseFloat(resp[i].g).toFixed(0)
gt+=parseFloat(resp[i].g)
})
el.querySelector(".wtp").innerHTML=parseFloat(resp[0].total).toFixed(0)+" "+resp[0].unit
el.querySelector(".wtc").innerHTML=parseFloat(resp[1].total).toFixed(0)+" "+resp[1].unit
el.querySelector(".wtg").innerHTML=parseFloat(resp[2].total).toFixed(0)+" "+resp[2].unit
el.querySelector(".pt").innerHTML=pt.toFixed(0)
el.querySelector(".ct").innerHTML=ct.toFixed(0)
el.querySelector(".gt").innerHTML=gt.toFixed(0)
}
function HandleSubmit(e)
{
el=e.currentTarget
e.preventDefault();
xhr.open("POST","/url_here.php",true)
xhr.setRequestHeader("content-type","application/x-www-form-urlencoded")
xhr.onload=SetDataInTheForm
var button=e.currentTarget.querySelector("input[type=submit][clicked=true]")
button.removeAttribute("clicked")
xhr.send($("#"+e.currentTarget.id).serialize()+"&"+button.getAttribute("name")+"=on")
}
[].forEach.call(document.querySelectorAll("._form_"),function(form){
form.addEventListener("submit",HandleSubmit,false);
})
})()
Remember that $('.div_container_to_render_JSON') is a new selector that selects all elements with a class div_container_to_render_JSON. What you want to happen is figuring out where that click came from, and find the corresponding div_container_to_render_JSON.
Luckily for you, a jQuery click handler sets the this keyword to the HTMLElement where the click was captured. You can use this to get the parent element.
$('.your-button').on('click', function () {
const myButton = $(this);
$.ajax({
// ...
success (data) {
myButton.parent().html(data.PHP_JSON_RECEIVED);
// or if you need to find a parent further up in the chain
// myButton.parents('.div_container_to_render_JSON').html(data.PHP_JSON_RECEIVED);
}
});
});
The problem is that your class selector is indeed selecting all your divs at the same time.
Solution, set identifiers for your divs as such:
<div class="my_div" id="my_div_1">
and then you can use those id's to fill in the data:
$('#my_div_1').html(data.PHP_JSON_1_RECEIVED);
and repeat for your 6 divs (notice the change from class selector '.' to identifier selector '#')
Thanks for the replies people. I finally figured it out after days of hard work, it was something really simple.. here's the answer:
$('.trigger_button_inside_divs').click(my_ajax_function);
var thisButton = $(this);
var thisDiv = thisButton.closest(".main_container");
function my_ajax_function(){
$.ajax({
dataType: "JSON",
type: 'POST',
url: test.php,
success: function(data) {
thisDiv.find('.div_to_render_JSON_1').html(data.PHP_JSON_1_RECEIVED);
thisDiv.find('.div_to_render_JSON_2').html(data.PHP_JSON_2_RECEIVED);
thisDiv.find('.div_to_render_JSON_3').html(data.PHP_JSON_3_RECEIVED);
}
});
}

Anchor text falling outside of <a> tag after Ajax append

I am loading content from a URL through Ajax and appending the content to a container. When the content is appended, the anchor text falls outside of the <a></a> tag.
Everything is appending correctly, and the code on the URL requested is absolutely fine with no issues.
// url: https://example.com/index.html
<div class="data-row__classes data-row__item">
<img src="http://localhost/wp-content/uploads/2017/10/english.png" alt="icon">
<span>English</span>
</div>
// appended HTML after ajax request to https://example.com/index.html
<div class="data-row__classes data-row__item">
<img src="http://localhost/wp-content/uploads/2017/10/english.png" alt="icon">
<span>English</span>
</div>
// note the malformed anchor tag 2 lines above
I am not sure exactly how to describe this; but I can't find any other instances of this problem online. The HTML markup is absolutely fine on the requested page; does anyone know what may be scrambling it? Specifically the link and nothing else?
Full Ajax
$('.class-table__nav__favorites').on('click', function(e) {
var class_table_height = $('.class-table__results').outerHeight();
if ( $(this).hasClass('selected') ) {
$(this).removeClass('selected');
$.ajax({
url: cml_theme.ajaxurl,
type: 'get',
data: {
action: 'favorites_only_off',
paged: $('.class-table__foot__nav').data('page')
},
beforeSend: function(result) {
$('.class-table__results').css('height', class_table_height);
$('.class-table__results').empty();
$('.class-table__results').append('<div class="class-table__loading"></div>');
},
success: function(result) {
$('.class-table__results').css('height', 'auto');
$('.class-table__loading').remove();
$('.class-table__results').append(result);
$('.class-table__foot').show();
}
});
}
});
The code which it takes from the WordPress action: 'favorites_only_off' is exactly as described above with the example url (example.com/index.html).
Malformed HTML in a previous <a> that closed the opening tag with <a href="" ... /> instead of <a href="" ... >

How can I improve my Ajax?

I'm trying to figure out if what I'm doing is the right way. I have a comment form and when it gets clicked I'm appending the comment into a div element through Ajax. When the page is refreshed then of course that would disappear and instead of it I have a foreach loop that runs and echos the comments. Since they both have the same CSS attributes they look the same to the user. The reason I'm doing it this way is because the foreach loop gets updated only after a refresh. Is there a better way? Can I update the page directly from the database without refresh? I basically need that every time a user clicks on the comment button that the foreach loop will run again but I couldn't find how to do it. I feel like I'm covering a gun shot with bandage the way I do it at the moment.
Loop:
#foreach($comment as $comments)
#if($comments->image_id == $image->id)
<div id="{{$comments->id}}" class="col-md-5 ajaxrules">
<div class="deletecomment">
<i class="fa fa-trash-o"></i>
</div>
<div class="col-md-2">
<img src="{{$comments->user_avatar}}" class="img-circle buddy">
</div>
<div class="hello col-md-10">
<h4>{!! $image->user_name !!}</h4>
<p class="left">{!!$comments->body!!} </p>
</div>
</div>
#endif
#endforeach
//Where I append the comments through Ajax until the refresh that replaces it with the loop
<div class="man">
</div>
Ajax:
<script>
$(document).ready(function(){
$('.send-form').click(function(e){
e.preventDefault();
var username = "{{ $username }}";
var one = $('textarea[id="{{$image->id}}"]').val();
var value = "{{$image->id}}";
var begin = '<div class="col-md-5 addavatar">'+'<div class="deletecomment">'+'<i class="fa fa-trash-o">'+'</i>'+'</div>'+'<div class="col-md-2">'+'<img src="{{$profile}}" class="img-circle">'+'</div>'+'<div class="hello col-md-10">'+'<h4>' + username +'</h4>'+'<p>'+one+'</p>'+'</div>'+'</div>';
if(one.length > 0){
console.log(username);
$('textarea[id="{{$image->id}}"]').val('');
$.ajax({
url: 'comment',
type: "post",
beforeSend: function (xhr) {
var token = $('meta[name="csrf_token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
data: {'id': value, 'comment': one},
success:function(data){
$( ".man" ).append([begin]);
},error:function(){
console.log("error!!!!");
}
});
}
});
});
</script>
You are killing yourself.
Manipulate the DOM via javascript code like you do it's really hard work!
You are not suppose to write html inside javascript strings, there must be another way!
And there is... Welcome to AngularJS!
In angular you can write your html and assign a javascript controller to it, perform ajax request and after the ajax complete you can bind the returned data to the html automatically! That means the angular refresh your html and do all the work for you. Even perform loop of let's say, row in a table, etc...

too much HTML in an ajax script?

I read from this page that appending a lot of elements is bad practice and I should build up a string during each iteration of the loop and then set the HTML of the DOM element to that string. Does the same go for using too much HTML in the loop?
I have an AJAX script that parses JSON data. It requires adding data to different existing elements, like this:
$.ajax({
url: "url",
success: function (data) {
$(data.query.results.json.json).each(function (index, item) {
var title = item.title, // A,B,C or D
age = item.age,
background = item.background,
ingredient = item.Ingredient;
$('.'+ title+'_ingredient').html(''+ingredient+'')
$('.'+ title+'_age').html(''+age+'')
$('.'+ title+'_background').html(''+background+'')
});
},
error: function () {}
});
HTML:
<div class="A_ingredient"></div>
<div class="B_ingredient"></div>
<div class="C_ingredient"></div>
<div class="D_ingredient"></div>
<div class="A_age"></div>
<div class="B_age"></div>
<div class="C_age"></div>
<div class="D_age"></div>
<div class="A_background"></div>
<div class="B_background"></div>
<div class="C_background"></div>
<div class="D_background"></div>
Is it necessary to build up a string first? If so, can you show me how to do that?
It is purely about the time it takes to process calls to html() so they simply recommend you reduce the number of calls. In this case you could build them once in a loop then sets the div html once for each.
Update:
Based on your update, aside from all the extra trailing quotes you don't need to add (a string is a string is a string), your code is fine as is. You only hit each item once.
e.g.
$.ajax({
url: "url",
success: function (data) {
$(data.query.results.json.json).each(function (index, item) {
var title = item.title, // A,B,C or D
age = item.age,
background = item.background,
ingredient = item.Ingredient;
$('.'+ title+'_ingredient').html(ingredient);
$('.'+ title+'_age').html(age);
$('.'+ title+'_background').html(background);
});
},
error: function () {}
});
Note: If your item properties (Age, Background, Ingredient) are simple values (not objects or arrays), yo do not need the leading ''+s either.
Previous
Assuming you actually want to concatenate the results (you are only keeping the last ingredient at the moment), you could do something like this:
e.g.
$.ajax({
url: "url",
success: function (data) {
var ingredients = '';
$(data.query.results.json.json).each(function (index, item) {
var title = item.title;
var ingredient = item.Ingredient;
ingredients += ingredient;
});
$('.aclass').html(ingredients);
$('.bclass').html(ingredients);
$('.cclass').html(ingredients);
$('.dclass').html(ingredients);
},
error: function () {}
});
Which can be reduced to:
$('.aclass,.bclass,.cclass,.dclass').html(ingredients);
The contents of each div are identical in your example, so you only need a single string.
In this instance you would probably need some form of delimiter between ingredients, but your example is too vague.
e.g.
ingredients += ingredient + '<br/>';
In your example, you're setting the HTML on many different document elements.
If they're grouped in some way, for example all in a Div with ID #Container, you could build a string of the HTML and set the content of the whole Div at the end of it, something like this:
$.ajax({
url: "url",
success: function (data) {
var sHTML="";
$(data.query.results.json.json).each(function (index, item) {
var title = item.title,
background = item.background,
ingredient = item.Ingredient;
// not sure what your actual HTML is (div/span/td etc) but somethign like this?
sHTML+="<div>"; // an opening container for this item
sHTML+='<div class="'+title+'_ingredient">'+ingredient+'</div>')
sHTML+='<div class="'+title+'_age">'+title+'</div>')
sHTML+='<div class="'+title+'_background">'+background+'</div>')
sHTML+="</div>";
});
$("#Container").html(sHTML);
},
error: function () {}
});
Note I haven't tested this code, but you see the principal hopefully.
That is, build a string of the HTML then set one element at the end with the content.
I have done this a lot in a recent project and haven't seen any speed issues (maybe 50 'items' to set in my case).
HTML will initially look like this :
<div id="container">
</div>
Then end up like this (2 x items in this example) :
<div id="container">
<div>
<div class="<sometitle1>_ingredient">ingredient 1</div>
<div class="<sometitle1>_age">age 1</div>
<div class="<sometitle1>_background">background 1</div>
</div>
<div>
<div class="<sometitle2>_ingredient">ingredient 2</div>
<div class="<sometitle2>_age">age 2</div>
<div class="<sometitle2>_background">background 2</div>
</div>
</div>
subsequent calls will replace the element's content with new values, replacing the old items.
Building a string is, I would imagine, less processor-heavy than setting the html() on lots of elements individually. Each time you use html() I'm guessing that the browser has to go some way towards working out any knock-on effects like expanding the width of an element to accomodate it or whether events will still work as they did, etc - even if actual rendering is only run at the end of the process. This way you use html() once, although what you're setting is more complex.
Hope this helps.

Categories