I have an Ajax code like this:
$j(document).ready(function () {
function loading_show() {
$j('#loading').html("<img src='images/loading.gif'/>").fadeIn('fast');
}
function loading_hide() {
$j('#loading').fadeOut();
}
function loadData(page) {
loading_show();
$j.ajax({
type: "POST",
url: "load_data.php",
data: "page=" + page,
success: function (msg) {
var $response = $j(msg);
// Query the jQuery object for the values
oGlobal = $response.filter('#Z').text();
$j("#container").ajaxComplete(function(event, request, settings) {
loading_hide();
$j("#container").html(msg);
});
}
});
}
loadData(1); // For first time page load default results
$j('#container .pagination li.active').live('click', function () {
var page = $j(this).attr('p');
loadData(page);
});
});
Im getting this response:
<div id="container">
<div id="Z">JuanFernando</div>
<div id="q">
<div class="pagination">
<ul>
<li p="1" class="inactive">First</li>
<li class="inactive">Previous</li>
<li p="1" style="color:#fff;background-color:#006699;" class="active">1</li>
<li p="2" class="active">2</li>
<li p="2" class="active">Next</li>
<li p="2" class="active">Last</li>
</ul>
<input class="goto" size="1" style="margin-top:-1px;margin-left:60px;"
type="text">
<input id="go_btn" class="go_button" value="Go" type="button"><span class="total" a="2">Page <b>1</b> of <b>2</b></span>
</div>
</div>
</div>
I want to extract "JuanFernando" in order to show in div container but alone and I want that the rest of the response could be show in other different div for example: container2.
ajaxComplete is not what you want to use here, especially inside your success function. You want your success function to look something like this:
success: function (msg) {
loading_hide();
var $response = $j(msg);
// Query the jQuery object for the values
oGlobal = $response.find('#Z').text();
$j("#container").html(oGlobal);
$response.find('#Z').remove();
$j('<div id="container2"></div>').html($response.html()).appendTo('body');
}
We're just taking the oGlobal (which should be JuanFernando in this case) and sticking it in the #container. After that, remove the #Z div from the response, and stick the rest inside of a new #container2, and append it to the body, or wherever you'd like it.
Here's an "adapted" fiddle.
Basically the only thing that changes with you code is
replace
oGlobal = $response.filter('#Z').text();
with
oGlobal = $response.find('#Z').text();
also, see MattDiamant's answer concerning ajaxComplete.
Related
So here's whats going on, I have a couple scenarios where I can't seem to apply any styles to content coming from a get request, and on one of them I managed to be able to but it wouldn't be considered best practice.
Premise:
I have an empty Ul to which Li's will be attached from a GET request to an API.
Scenarios
1) I create DOM objects using JQuery and append LI <-- SPAN <-- string to the empty UL and then state that all the children of the UL will be colored green.
(this does not work & yes I could target the UL and have everything inherit the styles but that wont work for what I have in mind)
2) I append a string which contains HTML markup within it to then add styles and concat them with what the GET request spits out. ( for some reason it seems to work this way but I really don't want to be creating LI's and SPANS + classes all in one string)
//scenario 1
var $orders = $("#orders");
$.ajax({
type: 'GET',
url: 'http://rest.learncode.academy/api/johnbob/friends',
success: function (data) {
$.each(data, function (i, item) {
if (item.name && item.drink) {
var $spn = $("<span></span>");
var $lli = $("<li></li>");
// $spn.append(String(item.name));
$spn.css({width: "20px"});
$orders.append($lli).append($spn).append("name: "+item.name+", Order: " + item.drink);
$orders.children().css({ color: "green" });
console.log($spn);
}
})
}
});
/* scenario 2
var $orders = $("#orders");
$.ajax({
type: 'GET',
url: 'http://rest.learncode.academy/api/johnbob/friends',
success: function (data) {
$.each(data, function (i, item) {
if (item.name && item.drink) {
var $spn = $("<span>hell</span>");
var $lli = $("<li></li>")
// $spn.append(String(item.name));
$spn.css({width: "20px"});
$orders.append("<li>Name: <span class='tato'>" + item.name + ",</span> Order: " + item.drink + "</li>");
$orders.children().css({ color: "green" });
console.log($spn);
}
})
}
});
*/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Coffee Orders</h2>
<br />
<ul id="orders">
<li>control group</li>
</ul>
<br />
<h4>Add a coffee order</h4>
<p>name: <input type="text" id="name"></p>
<p>drink: <input type="text" id="drink"></p>
<button id="add_order">Add!</button>
I haven't been able to find a reliable answer as to why this is happening, eventually I'll want to line up the orders regardless of the name length using a span.
edit:
What was happening (as stated in the answer) was I was appending empty LI's SPANs and Strings to the original UL. When using append() keep in mind anything you add (in a chain form) will be appended to the original stated element and not the previous one.
Side note:
For more information on better practice of templating incoming GET stuff check out this vid I found.
https://www.youtube.com/watch?v=GbNWPn8vodo&index=9&list=PLoYCgNOIyGABdI2V8I_SWo22tFpgh2s6_
As noted by #Taplar the issue is use of .append(). You are appending <span> elements and #text nodes to <ul> at
$orders.append($lli).append($spn).append("name: "+item.name+", Order: " + item.drink);
which are not valid child elements of <ul>
Permitted content zero or more <li> elements, which in turn often
contain nested <ol> or <ul> elements.
To correct issue, set #text node as .innerHTML of <span> element, and span element as .innerHTML of <li> element using html of jQuery(html, attributes) function attributes property.
Also set span css display property to block for width property to be applied to the element.
//scenario 1
var $orders = $("#orders");
$.ajax({
type: 'GET',
url: 'http://rest.learncode.academy/api/johnbob/friends',
success: function(data) {
$.each(data, function(i, item) {
if (item.name && item.drink) {
var $spn = $("<span></span>", {
html: "name: "
+ item.name
+ ", Order: "
+ item.drink,
css: {
width: "20px",
display: "block",
position: "relative"
}
});
var $lli = $("<li></li>", {
html: $spn
});
$orders.append($lli)
.children().css("color", "green");
}
})
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Coffee Orders</h2>
<br />
<ul id="orders">
<li>control group</li>
</ul>
<br />
<h4>Add a coffee order</h4>
<p>name:
<input type="text" id="name">
</p>
<p>drink:
<input type="text" id="drink">
</p>
<button id="add_order">Add!</button>
I am designing a social network that has timeline and there is like button. I use AJAX to apply the like button on the server side. the problem is that I want to change the number of like for each post immediately after they have liked successfully. Because my elements are generated by for-each, I want to change the number of like for the exact element, I really have a problem with it.I am using thymeleaf.
I am looking for an idea that how to do this.
here is my html code:
<div class="col-sm-4">
<div class="row" >
<div class="col-sm-12">
<img th:if="${tweet.isFavorited()}" src="../static/images/like.png" th:src="#{/images/like.png}" th:class="like-img" th:id="${tweet.getId()}" width="35" height="35"/>
<img th:if="${!tweet.isFavorited()}" src="../static/images/dislike.png" th:src="#{/images/dislike.png}" th:class="like-img" th:id="${tweet.getId()}" width="35" height="35"/>
</div>
</div>
<div class="row">
<div class="col-sm-12" >
<h6 th:if="${tweet.isRetweet()}" th:class="like-count" th:id="${tweet.getId()}" th:text="${tweet.getRetweetedStatus().getFavoriteCount()}"></h6>
<h6 th:if="${!tweet.isRetweet()}" th:class="like-count" th:id="${tweet.getId()}" th:text="${tweet.getFavoriteCount()}"></h6>
</div>
</div>
and it is my script code:
$(function () {
$(".like-img").click(function () {
event.preventDefault();
var $post = $(this);
var toSend = {
"tweetId": this.getAttribute("id")
}
$.ajax({
type : "POST",
contentType: "application/json; charset=utf-8",
url : "like",
data : JSON.stringify(toSend),
dataType : 'json'
}).done(function (data) {
if(data.status == "success") {
if ($($post).attr("src") == "/images/dislike.png") {
$($post).attr('src','/images/like.png');
}
else {
$($post).attr('src','/images/dislike.png');
}
return false;
}
});
});
})
Okay so to make this work you will need to assign unique ids to the like-count elements, something like so:
<h6 th:if="${tweet.isRetweet()}" th:class="like-count" th:id="${tweet.getId()}_like_count" th:text="${tweet.getRetweetedStatus().getFavoriteCount()}"></h6>
Then you can retrieve the current count, increment it, and set the text of the count element. Something like so:
var currentCount = parseInt($('#'+toSend.tweetId+'_like_count').innerHtml)
var newCount = currentCount++;
$('#'+toSend.tweetId+'_like_count').text(newCount);
Here's the function I'm trying to use
$('body').on('click', '.up-vote', function(event) {
event.preventDefault();
var data = {"action": "voteKarma", "id": $(this).data("id"), "value": $(this).data("val")}
$.post(window.apiURL, data, function(result) {
switch(result['status']) {
case 1:
var vote_sum_text = $(this).next(".sum").text();
if (!isNaN(parseInt(vote_sum_text, 10))) {
var vote_sum_text = $(this).next(".sum").text();
} else { alert("isNaN Variable") }
break;
}, 'json');
});
When the Ajax result returns 0 It's returning an alert with isNaN Variable which is my fallback to debug with problem.
Here's my HTML layout which is grabbed dynamically using another Ajax request there are multiple of these divs listed in <li> format :
<div class="votes pull-left">
<a class="up-vote" href="#" data-id="20" data-val="1"><span class="fa fa-arrow-circle-o-up"></span></a>
<span class="sum" style="font-weight:400;color:#666;">
0
</span>
<a class="down-vote" href="#" data-id="20" data-val="0"><span class="fa fa-arrow-circle-o-down"></span></a>
</div>
In simple terms; when you click .up-vote or .down-vote it'll send an AJAX request that'll then grab the text() of the .sum value.
Try use
$(event.currentTarget).next(".sum").text();
Because this in .post does not refer to element
You can also use the following:
$('body').on('click', '.up-vote', function(event) {
event.preventDefault();
var up_vote_this = $(this);
....
....
//now you can use the variable in the success function...
var vote_sum_text = up_vote_this.next(".sum").text();
Hello i have the following code with problems, i'm trying to make it when you click on the output to insert it into the input field. Can you help me please, been trying for hours without any luck.
<script type="text/javascript">
var input = $('#CompanyName');
var output = $('#output');
var timer;
input.on('keyup', function() {
delaySearch(this.value);
});
function delaySearch(keywords) {
clearTimeout(timer);
timer = setTimeout(function() {
performSearch(keywords);
}, 1000);
}
function performSearch(keywords) {
$.ajax({
type: "POST",
url: "/print/order/search",
data: { query: keywords },
cache: false,
dataType: "json",
async: true,
success: function(data) {
for(var key in data) {
output.append('<li onclick="fill('+ data[key].ClientName +')">' + data[key].ClientName) + '</li>';
}
}
});
}
function fill(thisValue) {
input.val(thisValue);
clearTimeout(timer);
}
</script>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="CompanyName">Firma</label>
<div class="col-md-5">
<input id="CompanyName" onblur="fill();" name="CompanyName" type="text" placeholder="Firma" class="form-control input-md">
<ul id="output"></ul>
<span class="help-block"></span>
</div>
</div>
Uncaught ReferenceError: somevalue is not defined
Update:
After adding jquery ready function i noticed some errors around and fixed them here is an update on the code
<div class="form-group">
<label class="col-md-4 control-label" for="CompanyName">Firma</label>
<div class="col-md-5">
<input id="CompanyName" name="CompanyName" type="text" placeholder="Firma" class="form-control input-md">
<ul id="output"><li onclick="fill(Ionut)">Ionut</li></ul>
<span class="help-block">Nume Firma</span>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
var input = $('#CompanyName');
var output = $('#output');
var timer;
input.on('keyup', function() {
delaySearch(this.value);
});
function delaySearch(keywords) {
clearTimeout(timer);
timer = setTimeout(function() {
performSearch(keywords);
}, 1000);
}
function fill(thisValue) {
input.val(thisValue);
}
function performSearch(keywords) {
$.ajax({
type: "POST",
url: "/print/order/search",
data: { query: keywords },
cache: false,
dataType: "json",
async: true,
success: function(data) {
for(var key in data) {
output.append('<li onclick="fill(' + data[key].ClientName + ')">' + data[key].ClientName) + '</li>';
}
}
});
}
});
</script>
onclick the error persists
Uncaught ReferenceError: fill is not defined
realseanp is onto the correct answer. I'll try to explain it a little better for you. When a browser starts processing and rendering a page, it loads top down. So your javascript scripts are being ran and evaluated before the DOM is created.
So your jquery selectors: var input = $('#CompanyName'); if you were to inspect them are going to be an empty array. They cannot find the #CompanyName element because it has not yet been rendered.
If you use jQuery's $(document).ready() function, then you can be assured that your code will not run until the dom is finished rendering, and therefore will find the elements as you intend them to. So in the end, your code will need to change to this:
$(document).ready(function(){
//Put your code in here.
//It will then fire once the dom is ready.
});
UPDATE:
Additionally, with your update. I'm noticing that the error is that 'fill' is not defined. fill being your onclick method. You have your js script evaluating after the dom is rendered. So at the time that the dom is rendered, and the tag with the onclick is rendered, no fill method yet exists. Two solutions:
Move the script above the dom, and place a var fill; outside of the $(document).ready so essentially this:
var fill;
$(document.ready(function(){
//your code
});
Don't use the onclick dom attribute, and instead use jquery to bind the event. So change
Ionut
to this:
<ul id="output"><li>Ionut</li></ul>
and inside the document.ready, add:
$('#output li').click(function(e) {
fill(/*your value/*)
});
You need to put your script below your HTML. That or wrap it in the jQuery Document ready function. And make sure you have jQuery loaded on the page, before your script
I`m kind of novice in jquery and want to make a sliding table.
The orinal table has 3 levels:
<ul class="categories">
<li id="category1">1 element</li> //parentid=0
<li id="category2">2 element</li> //parentid=0
<ul>
<li id="category3">1 element of element id2</li> //parentid=2
<ul>
<li id="category4">1 element id3</li> //parentid=3
</ul>
</li>
</ul>
</li>
</ul>
The first level elements have parentid = 0, id=1++, the next level have nested parentid and there own id and so on.
Page loads with only 1 level with parentid = 0.
<ul class="categories">
<li id="category1">1 element</li> //parentid=0
<li id="category2">2 element</li> //parentid=0
</ul>
Then I want to click the li, take id ID - go to file, execute mysql, get the new table in variable, bring it back and slideToggle it under LI.
php side
if(isset($_POST['subcategory'])){
$subcategory = str_replace('category', '', $_POST['subcategory']);
echo build_category_tree($subcategory); // builds the UL tree
}
this returns me id, i need to return the list and toggle it.
NOW the new UL is connected BUT i jquery cant work with it, updated the script with the one below but still cant.
UPDATED JQuery
$(".tablecategoryname").on('click', function(){
var $a = $(this).closest('li').attr('id');
var $c = $(this).closest('li');
$.ajax({
type: "POST",
url: "functions.php",
data: {subcategory:$a},
cache: false,
success: function(data)
{
$(data).hide().insertAfter($c).slideDown(400);
}
});
});
ID's should not contain just a number (or start with a number), you should probably use #a1 or something similar. In the data parameter you're sending an object, and equalsigns does'nt really work.
$(".table li").on('click', function(){
var self = this;
$.ajax({
type: "POST",
url: "functions.php",
data: {id : self.id},
cache: false
}).done(function(data) {
//guessing you're returning valid HTML
$(data).hide().insertAfter(self).slideDown(400);
});
});
EDIT:
Your build_category_tree() function needs to return the HTML so you can echo it back to the ajax request:
if(isset($_POST['subcategory'])){
echo $subcategory = str_replace('category', '', $_POST['subcategory']);
$ULtree = build_category_tree($subcategory); // builds the UL tree
echo $ULtree; //echo back to Ajax
}
You should put an id in your main ul to catch his parent and them toggle the list inside the main ul.
$("ul.umenu > li).click(function (e) {
e.preventDefault();
var element = $(this);
if (element.parent().find("ul").is(":visible")) {
} else {
$("ul.umain> li > ul").slideUp();
element.parent().find("ul").slideToggle("fast");
}
});