I need to do a fetch using ajax. I need to use this: ajax/get_item_list/group_id/offset/limit/true (return true as JSON) where id comes from a link that user clicks. And when user clicks that link, it should call(?) that "ajax/get_item_list/group_id/offset/limit/tru" to get content to a div. And when user clicks another link (in navigation), it should do that again, but ofcourse it should get new content.
I am using drupal if that info is needed.
//Mario
Have you tried some jquery?
<div id="display"></div>
Click me
And then some javascript:
$(document).ready(function(){
$('a.ajaxToDisplay').click(function(){
$('#display').load(this.href);
return false;
});
});
I get this kind of error on firebug: $(this).href is undefined
[Break on this error] var group_id = $(this).href.replace(/.*#/, '');
this is when i use jcubic's proposal.
//mario
You can use JQuery.
$('a.link_class').click(function() {
var group_id = $(this).href.replace(/.*#/, '');
$.get("ajax/get_item_list/" + group_id + "/offset/" + limit "/true", null, function(data, status, xhr) {
$('#your_div_id').html(data);
});
});
and in html use links:
link
<div id="your_div_id"></div>
Related
I have a form with a drop-down to select a time for scheduling
I didn't use a selector input, instead I used the following html to make the menu for styling reasons.
<div class="tabs">
<div class="apt-time">
<h3>#Time</h3>
<ul class="time-list">
<li class="available">8:00am</li>
<li class="available">9:00am</li>
<li class="available">10:00am</li>
<li class="available">11:00am</li>
<li class="available">12:00am</li>
<li class="available">1:00pm</li>
<li class="available">2:00pm</li>
<li class="available">3:00pm</li>
<li class="available">4:00pm</li>
<li class="available">5:00pm</li>
</ul>
</div>
</div>
Because of this I can't use the POST method to get the data the user clicked on in the menu. So I tried to come up with a solution that could pass a string variable with events to my php page with the GET method in the code below. The if statements are going to be used so the client can't submit the form without clicking on an option in the menu. Is there a way around this without using a selector input?
$('.available').click(function() {
return clockTime = $(event.target).text()
})
$('.btn').click(function() {
if ($('.available').click) {
window.location.href = "textsms.php?"+clockTime
} else {
// warn client that they need to chose a time
}
})
Added AJAX functionality below. The script passes POST values to PHP script named textsms.php without refreshing browser.
Updated Code:
<script>
$('.available').click(function() {
var clockTime = $(this).text();
$.ajax({
url:"textsms.php",
method:"POST",
data:{'clockTime':clockTime,var2:'2',}, // modify fields
success: function(data){
alert(data); // Do something with data received
},
});
});</script>
For testing..
textsms.php:
<?php
print_r( $_POST );
?>
You're not defining the get variable in the redirection:
window.location.href = "textsms.php?"+clockTime
The following will store the "clockTime" in the $_GET['time']
window.location.href = "textsms.php?time="+clockTime
Edit: Anyway your JS is not correct.
var clockTime;
$('.available').click(function(e) {
clockTime = $(this).text();
})
$('.btn').click(function() {
if(typeof clockTime !== "undefined"){
window.location.href = "textsms.php?time="+clockTime
}else{
// warn client that they need to chose a time
}
});
You can use a control variable for this (also defining a css class that show the selected option):
var selectedTime = '';
$('.available').click(function() {
$('.available').removeClass('clicked');
$(this).addClass('clicked');
selectedTime = $(this).text();
})
$('.btn').click(function() {
if (selectedTime != '') {
window.location.href = "textsms.php?time="+selectedTime;
} else {
// warn client that they need to chose a time
}
})
You need to get the value and pass it to your location properly:
$("ul.time-list").on("click","li.available",function(){
var selectedTime = $(this).text();
window.location.href = "textsms.php?varname="+selectedTime;
});
I like using jquery's on event as it allows you to use load content dynamically so long as you target an external static element.
http://api.jquery.com/on/
I know we can use hasClass() but in my case my ajax is returning html.
I can append then check the class exist or not but there'll be a flick. Is it possible to check what's inside the html before render it somewhere?
$.ajax({
url:'some_url',
success: function(html) {
// I can do this:
$('body').append(html);
if ($('my_selector').length > 0) {
// but I don't want to do this because I don't want that the html will show to the user
}
}
});
Yes, Possible
var yourReturnedHtml = getHtml();
return $(yourReturnedHtml).find('.someClass').length > 0;
Further #Mohammad Adil answer:
var html = '<div class="test">This is the response from the ajax call.</div>';
function simulateAjax(selector) {
var exist = $('<div />').html(html).find(selector).length > 0;
$('#result').append('The element "' + selector + '" ' + (exist ? '' : 'not ') + 'exist<br />');
}
simulateAjax('.test');
simulateAjax('.test1');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>
The difference between the answers, and I think that the reason it didn't work for you, that for example: If your response is <div class="test"></div>, the #Mohammad's script will return false because there is no element with the class .test in the main element in the response.
So, you should wrap the response with element, then you can use .find() to check.
Sure working method, used many time into my projects, This will help you find any elements, elements with some class or id.
You can append your ajax response to some hidden html element e.g div
e.g.
<div id="responseDiv" style="display: none"></div>
//Now write a function to save ajax response to div
//from this div, you can find out whether class or any element is there
$.ajax({
url: 'some url',
success: function(data){
//save response to div
$('#responseDiv').html(data);
//now to check whether some class exists in the div
if($('#responseDiv .class-to-find').length > 0){
//since class is found into ajax response, write your code here
}
}
});
i got your point now. Use the same approach of hasClass() in success function of ajax and using async parameter. To remove the flick, place your ajax code is seTimeOut with time 0 like
setTimeout(function(){ //Your ajax code here }, 0);
I have a rate button on my page, created using PHP and jQuery.
When the button is clicked, a message is shown and hidden after a while "#num voted including you"
HTML:
div class="voting_wrapper" id="1001">
<div class="voting_btn">
<div class="up_button"> </div>
<span class="up_votes"></span>
</div>
</div>
jQuery:
$(document).ready(function() {
//####### on page load, retrive votes for each content
$.each( $('.voting_wrapper'), function(){
//retrive unique id from this voting_wrapper element
var unique_id = $(this).attr("id");
//prepare post content
post_data = {'unique_id':unique_id, 'vote':'fetch'};
//send our data to "vote_process.php" using jQuery $.post()
$.post('vote_process.php', post_data, function(response) {
//retrive votes from server, replace each vote count text
$('#'+unique_id+' .up_votes').text(response.vote_up +' user has voted');
},'json');
});
//####### on button click, get user vote and send it to vote_process.php using jQuery $.post().
$(".voting_wrapper .voting_btn").click(function (e) {
//get class name (down_button / up_button) of clicked element
var clicked_button = $(this).children().attr('class');
//get unique ID from voted parent element
var unique_id = $(this).parent().attr("id");
if(clicked_button==='up_button') { //user liked the content
//prepare post content
post_data = {'unique_id':unique_id, 'vote':'up'};
//send our data to "vote_process.php" using jQuery $.post()
$.post('vote_process.php', post_data, function(data) {
//replace vote up count text with new values
$('#'+unique_id+' .up_votes').text(data);
//thank user for liking the content
dataModified = data+' users has voting including you';
$('#message-status').hide().html(dataModified).fadeIn('slow').delay(5000).hide(1);
}).fail(function(err) {
//alert user about the HTTP server error
alert(err.statusText);
});
}
});
//end
});
It works fine, but placement of the message is incorrect. When I click the button, that message status shows up at the top of the page, while I need it to be shown below the rate button.
May I know how to add the code to achieve this? I think I could use append(); but I am struggling where and how to add the script. Can anyone help me?
Thanks in advance.
The reason why is that, is probably because the #message-status element is initially placed outside of the voting_wrapper element. You could move #message-status inside that wrapper, below the .voting_btn button using .insertAfter()
$('#message-status').hide().html(dataModified).insertAfter('#'+unique_id+' .voting_btn').fadeIn('slow').delay(5000).hide(1);
So that after AJAX call, your HTML becomes:
<div class="voting_wrapper" id="1001">
<div class="voting_btn">
<div class="up_button"> ddd</div>
<span class="up_votes">X</span>
</div>
<div id="message-status">X users has voting including you</div>
</div>
[EDIT]
If you need the message below the whole voting_wrapper, use this:
$('#message-status').hide().html(dataModified).insertAfter('#'+unique_id).fadeIn('slow').delay(5000).hide(1);
try replacing your code,
$('#message-status').hide().html(dataModified).fadeIn('slow').delay(5000).hide(1);
with this
$('#message-status').css({
'position': 'absolute',
'left': $(this).offset().left,
'top': $(this).offset().top + $(this).height() + 5
}).hide().html(dataModified).show("slow").delay(3000).hide("slow");
I have a select box with a list of books. The user can select a book and hit the submit button to view the chapters on a separate page.
However, when the user changes the select box, I would like a partial page refresh to display the past notes the user entered on the book, and allow the user to write a new note for that book. I do not want the review and creation of notes for a particular book done on the next page with the chapters, as it will clutter it up.
I'm using Python/Bottle on the backend and its SimpleTemplate engine for the front end.
Currently, when the select box is changed, an ajax call receives a Json string containing the book information and all the notes. This json string is then converted into a json object via jQuery.parseJson().
What I would like to be able to do is then loop over the notes and render a table with several cells and rows.
Would I have to do this in jQuery/js (instead of bottle/template framework) ? I assume so as I only want a partial refresh, not a full one.
I'm looking for a piece of code which can render a table with variable numbers of rows via jQuery/js from a json object that was retrieved with ajax.
<head>
<title>Book Notes Application - Subjects</title>
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<script>
$(document).ready(function(){
$('#subject_id').change(function(){
var subject_id = $(this).val();
$.ajax({
url : "subject_ajax?subject_id=" + subject_id,
success : function(data) {
alert(data)
json = jQuery.parseJSON(data);
},
error : function() {
alert("Error");
}
});
})
})
</script>
</head>
<body>
<!-- CHOOSE SUBJECT -->
<FORM action="/books" id="choose_subject" name="choose_subject" method="POST">
Choose a Subject:
<select name="subject_id" id="subject_id">
% for subject in subjects:
<option value="{{subject.id}}">{{subject.name}}</option>
% end
</select><input type="submit" name="sub" value="Choose Subject"/>
<BR />
</FORM>
This greatly depends on how your JSON and HTML are formatted. But with a table somewhere like:
<table id="books">
<tr>
<th>Chapter</th>
<th>Summary</th>
</tr>
</table>
You could do something like:
$(function(){
$('#choose_subject').submit(function () {
var subject_id = $(this).val();
$.getJSON("subject_ajax?subject_id=" + subject_id, function(data) {
console.log(data);
$.each(data.chapters, function (index, chapter) {
$('#books').append('<tr><td>' + chapter.title + '</td><td>' + chapter.summary + '</td></tr>');
})
});
return false;
})
})
This supposes JSON like:
{
"notes": [
"Note 1",
"Note 2"
],
"chapters": [
{
"title": "First chapter",
"summary": "Some content"
},
{
"title": "Second chapter",
"summary": "More content"
}
]
}
Other notes:
If you use HTML 4 or earlier, keep all your tags in upper case. If you're using XHTML or HTML5, keep all your tags in lower case.
You don't need $(document).ready(function () {...}), with recent versions of jQuery $(function () {...} ) works the same and it's easier to read.
You can use $.get instead of $.json if you're only using the success state (as you are here). And if you're confident that the data you'll get is valid JSON, you can use getJSON instead of get. It will parse the JSON for you deliver it to you as a JavaScript object automatically.
It's usually more convenient to use console.log rather than alert when you're testing. Actually, it's usually a bad idea in general to ever use alert.
I'm not familiar with Python/Bottle or its SimpleTemplate engine, but you could consider generating the html for the table on the server side and returning it in the ajax response, rather than returning JSON.
var subject_id = $(this).val();
$.ajax('subject_ajax', {
type: 'get',
data: { subject_id: subject_id },
dataType: 'html',
success : function(html) {
// Insert the html into the page here using ".html(html)"
// or a similar method.
},
error: function() {
alert("Error");
}
});
When calling .ajax():
The "type" setting defaults to "get", but I prefer to explicitly set it.
Use the "data" setting for the ajax call to specify the URL parameter.
Always specify the "dataType" setting.
I also recommend you perform the ajax call in an on-submit handler for the form, and add an on-change handler for the select that submits the form.
$(document).ready(function(){
$('#subject_id').change(function() {
$(this.form).submit();
});
$('#choose_subject').submit(function(event) {
event.preventDefault();
var subject_id = $('#subject_id').val();
if (subject_id) {
$.ajax(...);
}
});
});
This way your submit button should work in case it is clicked.
There are a few things you need to look at:
1) Is your SimpleTemplate library included?
2) Have you compiled your template via compileTemplate()?
Once you know your library is included (check console for errors), pass your data returned to your success handler method, compile your template, that update whichever element you are trying to update.
I'm not sure that you want to update the same element that you're defining your template in.
$(document).ready(function(){
$('#subject_id').change(function(){
var subject_id = $(this).val();
$.ajax({
url : "subject_ajax?subject_id=" + subject_id,
success : function(data) {
var template_data = JSON.parse(data);
var template = $('#subject_id').toString(); // reference to your template
var precompiledTemplate = compileTemplate(template);
var result = precompiledTemplate(template_data);
$('#subject_id').append(result);
},
error : function() {
alert("Error");
}
});
})
})
You might also try moving your template out of the element you're trying to update like this:
<script type="text/template" id="subject-select-template">
% for subject in subjects:
<option value="{{subject.id}}">{{subject.name}}</option>
% end
</script>
Then just create a blank select element like so:
<select id="select_id"></select>
Update references. Anyway, hope this is helpful. It should work but I can't test without your specific code ;)
Also, check out this demo example if you haven't yet:
https://rawgithub.com/snoguchi/simple-template.js/master/test/test.html
i have a little script which fetches the likes and tweets count about a url via jquery. Now it works great, but when a certain page has 0 like/shares, then jquery returns 'undefined' because the 'shares' part is not shown in the output.
$(document).ready(function() {
url = "http://awebsitehere.com/";
beforecounter = " <b>";
aftercounter = "</b>";
// Get Number of Facebook Shares
$.getJSON('http://graph.facebook.com/'+url+'&callback=?',
function(data) {
$('#facebook').append(beforecounter + data.shares + aftercounter);
});
// Get Number of Tweet Count
$.getJSON('http://urls.api.twitter.com/1/urls/count.json?url='+url+'&callback=?',
function(data) {
$('#twitter').append(beforecounter + data.count + aftercounter);
});
})
How would I have to edit this script to display 0 instead of undefined when facebook has got 0 shares/likes for a certain url?
try this:
$('#facebook').append(beforecounter + (data.shares || 0) + aftercounter);
and likewise for the twitter value.
At first you have to create a username of your page(see under your page name #username. Just click it...)
Then goto https://developers.facebook.com/tools/explorer/ and get an access token key
Then script something like that
function facebookLikesCount(access_token, pageusername)
{
var url = "https://graph.facebook.com/"+pageusername+"?fields=likes&access_token="+access_token+"";
$.getJSON(url,function(json){
alert(json.likes);
});
}
facebookLikesCount('your accesstoken', 'pageusername');
its work for me.