How to code one jquery function for all AJAX links - javascript

I am using zend framework on windows. I want to implement ajax in my project first time. I searched for help and created a very simple ajax functionality.
IndexController.php
public function indexAction() {
}
public function oneAction() {
}
public function twoAction() {
}
index.phtml
<script type="text/javascript" src="js/jquery-1.4.2.js"></script>
<script type="text/javascript" src="js/AJAX.js"></script>
<a href='http://practice.dev/index/one' class='one'>One</a>
<a href='http://practice.dev/index/two' class='two'>Two</a>
<br /><br />
<div id="one">one.phtml content comes here</div>
<div id="two">two.phtml content comes here</div>
AJAX.js
jQuery(document).ready(function(){
jQuery('.one').click(loadOne);
jQuery('.two').click(loadTwo);
});
function loadOne(event) {
event.preventDefault();
jQuery.ajax({
url: '/index/one',
success: function( data ) {
jQuery('#one').html(data);
}
});
}
function loadTwo(event) {
event.preventDefault();
jQuery.ajax({
url: '/index/two',
success: function( data ){
jQuery('#two').html(data);
}
});
}
Above code is working and loading data of one.phtml and two.phtml in 'one' and 'two' DIVs respectively when its link is clicked. You can see that I have to create separate jquery function for each link and also have to add new class for each link tag.
What I want to do ?:
I want to use only one jquery function for all AJAX requests and don't want to hard code url and success attributes in that function.
When I add "AJAX" class to any link tag then it should load content using AJAX.
Thanks.

for simple loading of data in divs i would use the load method
HTML
<script type="text/javascript" src="js/jquery-1.4.2.js"></script>
<script type="text/javascript" src="js/AJAX.js"></script>
One
Two
<br /><br />
<div id="one">one.phtml content comes here</div>
<div id="two">two.phtml content comes here</div>
JS
jQuery(document).ready(function(){
jQuery('.ajax').click(function(event){
event.preventDefault();
var target = '#' + jQuery(this).attr('rel');
var href = jQuery(this).attr('href');
jQuery( target ).load( href );
});
});
Use a single class to identify all links that should use ajax calls instead of their normal use. And add a rel attribute to those links that will contain the id of the container div..

Simple and Nice. No Jquery required. Check this out:
Bjax
Usage:
<script src="bjax.min.js" type="text/javascript"></script>
<link href="bjax.min.css" rel="stylesheet" type="text/css" />
Finally, include this in the HEAD of your html:
$('a').bjax();
For more settings, checkout demo here:
Bjax Demo

Maybe this:
function loadData(url, callback) {
jQuery.ajax({url: url, success: callback});
}
loadData('/index/one', function( data ) {
jQuery('#one').html(data);
})
loadData('/index/two', function( data ) {
jQuery('#two').html(data);
})
To make this even more compact you could define the same callback for both and then have the handler decide which element the response data should be written to.

Compact version:
$(function(){
$('.one').click(loadOne);
$('.two').click(loadTwo);
});
function loadOne(event) {
event.preventDefault();
$('#one').load('/index/one');
}
function loadTwo(event) {
event.preventDefault();
$('#two').load('/index/two');
}

Related

Jquery fill in content of div

I have the following code:
<div class=“phpversion”></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$.ajax({
url:"/core/components/seo/templates/default/functions/generic/php-version.php",
success:function(result){
$( "div.phpversion” ).html(result);
}
});
});
</script>
The aim is to fill in the div with class phpversion with the result obtained.
When I use "alert(result);" instead of "$( "div.phpversion” ).html(result);", the popup box with the expected value displays on load of the page.
Can you please help :) ?
It's because you're using wrong double-quote symbol. You're using the “ symbol instead of " symbol (3 times in your snippet)
Use ID for that div and update the JavaScript code accordingly:
<div id="phpversion"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$.ajax({
url:"/core/components/seo/templates/default/functions/generic/php-version.php",
success:function(result){
$( "#phpversion" ).text(result);
}
});
});
</script>

Load ajax item when click on jquery mobile tabs

I want to load some contents via ajax when click on a tabbar item in jquery mobile.
How can i do this?
<div data-role="tabs" id="tabs">
<div data-role="navbar">
<ul>
<li>Discover</li>
<li>My-chats</li>
</ul>
</div>
<div id="one" class="ui-body-d ui-content">
<div data-role="fieldcontain">
<!--load data via ajax-->
</div>
</div>
<div id="two">
<!--load data via ajax-->
</div>
</div>
When click on discover tab i want to load some data through ajax to that tab.
How to do this?
please help me.
Hope helps you!
(function(window, $) {
function TabCtrl() {
var self = this;
self.loadData = function(url) {
return $
.get(url)
;
};
$('[data-ajax]').click(function(event) {
event.preventDefault();
var tab = $(this).attr('href').replace('#', '');
self
.loadData(tab)
.then(
function(success) {},
function(error) {}
);
});
}
$(document).ready(TabCtrl);
})(window, window.jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#my-custom-tab" data-ajax>Load Me</a>
Try this. If you already using jQuery then ignore the first line.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
// Make sure all DOM is loaded
$(document).ready(function(){
// Fired when you click the link
$('#discover-tab').click(function(e){
// Prevent the link from continuing it's normal action
e.preventDefault();
// Fetch the result of a URL
$.get( "ajax/test.html", function( data ) {
// Fill the DIV with ID of 'one' with that result
$( "#one" ).html( data );
});
});
});
</script>
bind it to a javascript function which executes the ajax call like this:
Discover
javascript function:
function ajaxcallfunction(){
window.location.href = window.location.href + "#one";
//Enter your ajax call here
}

pass javascript variables into grails params

So I need to pass javascript variables into grails parameters to build and download a file. So initially did this with ajax just to learn that ajax doesn't do downloads. Initially this worked like so:
<script type="text/javascript" charset="utf-8">
function myFunction() {
jQuery.ajax({
url: "Search/download",
type: "POST",
data: {facets: visualSearch.searchQuery.facets()}
});
}
</script>
<input type="button" onclick="myFunction()" value="download">
While this passed the mapping correctly, this didn't do downloads.
So now I am want to do something similar with a g:link
<g:link controller="Search" action="test" params="[facets: '\$(visualSearch.searchQuery.facets())']" >TEST GRAILS</g:link>
But all I get in the params in the controller are
facets=$(visualSearch.searchQuery.facets())
action=test
controller=search
How can I fix this to pass the facets (whether parsed or unparsed) into the controller. Thanks!
Adding your javascript variable in params will not work. The g:link is executed on the server side and has no knowledge of your javascript values. You can remove this params and instead add code on the `onclick' event of your link to set your javascript values in the params.
Something like:
In the gsp page,
<g:link name="searchLink" controller="Search" action="test">TEST GRAILS</g:link>
and then in javascript (in the same page),
$(function() {
$('a[name="searchLink"]').bind('click', function() {
$(this).attr('href', $(this).attr('href') + '?facets=' + visualSearch.searchQuery.facets());
})
})
Basically you are using Grails to generate the hyperlink and then using JQuery to append a query string with the parameters to that href
Hope that helps.
What I tend to do in these cases is use the g:link to generate the URL, but then override the default behavior with jQuery to make the ajax call:
<g:link class="searchLink" controller="Search" action="test" params="[facets: '\$(visualSearch.searchQuery.facets())']" >TEST GRAILS</g:link>
$('.searchLink').on('click', function(e) {
e.preventDefault(); // prevent default link behavior
var $element = $(this);
var url = $element.prop('href');
$.post(url, function(data) {
// callback if you need it
});
});
From what you have I think you should create a form and submit it in the click event:
<script type="text/javascript" charset="utf-8">
function myFunction() {
$('<form>', {
"html": '<input type="text" name="facets" value="' + visualSearch.searchQuery.facets() + '" />',
"action": '${createLink(controller: "Search", action: "test")}',
"method": 'POST'
}).appendTo(document.body).submit();
}
</script>
<input type="button" onclick="myFunction()" value="download">
Or refactor your code to have a real html form and prepare the data for it before submit.

Javascript not working when I change to Google JQuery Libraries?

Previously I am using JQuery library from here
http://jquery.com/download/
http://code.jquery.com/jquery-migrate-1.2.1.min.js
I try to include the following code, it work perfectly.
Javascript
$(document).ready(function(){
function loading_show(){
$('#loading').html("<img src='images/loading.gif'/>").fadeIn('fast');
}
function loading_hide(){
$('#loading').fadeOut('fast');
}
function loadData(page){
loading_show();
$.ajax
({
type: "POST",
url: "listcontact.php",
data: "page="+page,
success: function(msg)
{
$("#con").ajaxComplete(function(event, request, settings)
{
loading_hide();
$("#con").html(msg);
});
}
});
}
loadData(1); // For first time page load default results
$('#con .pagination li.active').live('click',function(){
var page = $(this).attr('p');
loadData(page);
});
$('#go_btn').live('click',function(){
var page = parseInt($('.goto').val());
var no_of_pages = parseInt($('.total').attr('a'));
if(page != 0 && page <= no_of_pages){
loadData(page);
}else{
alert('Enter a PAGE between 1 and '+no_of_pages);
$('.goto').val("").focus();
return false;
}
});
});
HTML
<div id="con">
<div class="data"></div>
<div class="pagination"></div>
</div>
And Then I try to use JQuery js from Google instead from JQuery.com
https://developers.google.com/speed/libraries/devguide#jquery
ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js
The Tab menu still can work, however I cannot get any data from listcontact.php
How can I make it work in Google JQuery?
this is all my script tag
<script src="jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script type="text/javascript" src="ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
This is my tab menu
<nav>
<div id="tabs">
<ul>
<li><b>More Details</b></li>
<li><b>Contact</b></li>
<li><b>Files</b></li>
<li><b>Sales pipeLine</b></li>
<li><b>Call report</b></li>
</ul>
<div id="tabs-1">
<?php //include('viewdetail.php') ;?>
</div>
<div id="tabs-2">
<?php
if( $view == 0)
{
include('contact.php');
}
else
{
include('newcontact.php') ;
}
?>
</div>
<div id="tabs-3">
<?php //include('filemanagement.php') ;?>
</div>
<div id="tabs-4">
Under Development
</div>
<div id="tabs-5">
<?php //include('callReport.php') ;?>
</div>
</div>
</nav>
The code is inside my contact page, when I try to include it inside my tab
Are you developing locally? Or remotely?
If you are local....you usually have to attach http:// to the google apis
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
If not then just....
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
Should work...
This should also be replaced...from .live() to .on() as .live() is now deprecated
$('body').on('click','#go_btn', function(){
var page = parseInt($('.goto').val());
var no_of_pages = parseInt($('.total').attr('a'));
if(page != 0 && page <= no_of_pages){
loadData(page);
}else{
EDIT / UPDATE
You posted this...
<script src="jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script type="text/javascript" src="ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
Change to this...
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
The jquery needs to be above the jquery-ui, as the ui has a dependancy on Jquery, and you can remove v1.9 no sense in loading jquery twice
EDIT 3
I would change this...you don't need that ajaxComplete call, since the success function is doing that anyway...
$.ajax
({
type: "POST",
url: "listcontact.php",
data: {page: page},
success: function(msg)
{
loading_hide();
$("#con").html(msg);
}
});
And you made sure to change both your live()'s???
You had two, the other one should look like this...
$('body').on('click','#con .pagination li.active' function(){
var page = $(this).attr('p');
loadData(page);
});
try to include the same version JQuery from google :
Number of version JQuery from google should be equal number of version JQuery from Jquery website
but if you want to use recent version, there are some changes , and you should modify something in your code, see log console for more info about problem and check documentation of JQuery here
Looks like live might not work with the latest version
Replace
.live('click'
with
.on('click'
If there are any dynamically added elements on the page replace your events with this syntax
$(staticContainer).on('click', 'selector' function(){
Where staticContainer is the closest static ancestor of the element.
selector is the element to which you want to attach the event.
I had experience with similar issue, it may deal with deprecated functions! check EACH piece of function, so that deprecated methods are corrected :) Hope this help you go to somewhere right :)
deprecated-ajax-or-jquery-command-cause-no-result-returned
Enjoy!

jQuery load(URL) not working when loading page-fragments?

I have this page, the first button is working good.
I want when press the second button to give me the link that is in the href, i tried like this , but i got the whole page , not just the value of the link , why please?
<html>
<head>
<script src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var url = "http://localhost/test/asdfasdf.php";
$("#button").on("click", function() {
$('body').load( url );
});
$("#button2").on('click',function(){
$('body').load( url +"#link" );
});
});
</script>
</head>
<body>
<input type="button" id="button" value="load" />
<input type="button" id="button2" value="search for a tag" />
</body>
</html>
I think you want a space:
$('body').load(url + " #link");
http://api.jquery.com/load/#loading-page-fragments
All you seem to want is the href of the a#link element at that URL. So instead of loading it into the <body>, just make the AJAX request, and look through the result:
$.ajax({
type: "GET",
url: "http://localhost/test/asdfasdf.php",
dataType: "html"
}).done(function (data) {
var the_link = $(data).find("#link");
alert(the_link.attr("href"));
});
And to put the href in the <body>, add this line in the .done() method:
$("body").html(the_link.attr("href"));
// or
$("body").append(the_link.attr("href"));
But if you actually want to load the a#link element into <body>, do what you had before, but then look for the a#link element and get its attribute:
$('body').load(url + " #link", function () {
var the_link = $("#link");
alert(the_link.attr("href"));
});
EDIT
You're trying to capture the href of the <a> on a different page. A try:
$.get(url+' #link', function(data) {
var $link = $(data).find('a').attr('href');
alert($link);
});
That is my very best guess, but its a shot in the dark.
Currently your code evaluates to .load('http://localhost/test/asdfasdf.php#link'), where #link is a useless fragment. You need a space to engender jQuery's special behavior of automatic DOM parsing and element loading.
$("body").load(url + " #link");
EDIT: to get the actual link value:
$.get(url).done(function (html) {
console.log($(html).find('#link').attr('href'));
});
You can also append to body inside of the .done callback.

Categories

Resources