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

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.

Related

Add the ability to render comments when the comment-list elements should be filled with text "Loading..." and show results one by one

I'm trying to render results one by one with some text like "Loading..." and show results one by one. I found answers at one, two and tried to solve this but it shows only one loading text and renders, shows all results at a time. The results should appear one after the other, with the order preserved. If any error occurs during the loading, the tag should be left empty. How to solve this challenge? For full question please refer here
HTML
<!DOCTYPE html>
<html>
<head>
<title>Render Comments</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<div class="comment-list" data-count=1></div>
<script type="text/javascript" src="./app.js"></script>
</body>
</html>
JS
"use-strict";
var commentList = $(".comment-list");
var count = $(".comment-list").data("count");
var url = "https://jsonplaceholder.typicode.com/comments?postId=" + count;
$.ajax({
url: url,
method: "GET",
beforeSend: function () {
commentList.html("Loading...");
},
success: function (data) {
commentList.empty();
data.forEach(function (comment) {
commentList.append(`
<div class="comment-item">
<div class="comment-item__username">${comment.id}</div>
<div class="comment-item__message">${comment.name}</div>
</div>`);
});
},
error: function () {
// commentList.empty();
data.forEach(function () {
commentList.append(`
<div class="comment-item">
<div>Oops! Error occured to show the results</div>
</div>`);
});
},
});
You might consider doing this with CSS instead of with javascript. There are many examples including link. If you insist on doing this with javascript you need to break up the code adding the elements to the page using setInterval or setTimeout.

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>

Pass data from client side to server side

I'm writing a ASP.NET application.
I have a page, where user will select or deselect some elements. This happens client-side: when user clicks on a div, javascript function is called and some classes are changed, so the div is "grayed out".
There is also a Save button (asp:Button), that will save data.
What is the best way to pass information about selected elements back to server-side?
I have tried to put that info in cookies. Each div has ID, so I would create cookie with that ID and boolean value. This is a bad idea, because:
- when user (de-)selects some elements, and then navigates away from page without saving
- then navigates back, and without selecting anything clicks "Save", cookies have previous values and that gets saved.
What you have tried is good except Cookies. I can understand the problem you are facing.
So I would suggest to use Hidden Field instead of Cookies.
When your div is get selected call the javascript function and store the value (in specific format) in hidden field. and In the same way when your div is deselected remove the value from the HiddenField.
You can store value in HiddenField in below format (ID:value) :
div1:true;div2:true;div3:true
Now on the click event of the button you can first split the values by semicolon (';') and you will get the array like this :
div1:true,
div2:true,
div3:false
for each value again split the value by colon (':') and you will get the div id at the 0th index and its value on first index.
So basically your code to get the values from hidden field and perform an action on it would be as mentioned below :
foreach (var selectedDiv in this.hfSelected.Value.Split(';'))
{
var divId = selectedDiv.Split(':')[0];
var divValue = selectedDiv.Split(':')[1];
// Perform action on divId and divValue
}
Update :
To store the value in HiddenField, instead of div click, you can use the OnClientClick event of the button and get the value of selected and deselected div. See my below code sample :
ASPX Page :
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="Scripts/jquery-1.8.2.js" language="javascript"></script>
<script type="text/javascript" src="Scripts/jquery-1.8.2.min.js" language="javascript"></script>
<script type="text/javascript" src="Scripts/jquery-ui-1.9.1.custom.js" language="javascript"></script>
<script type="text/javascript" src="Scripts/jquery-ui-1.9.1.custom.min.js" language="javascript"></script>
<style type="text/css">
.selectedDiv {
background-color: #333;
color: #fff;
height: 30px;
width: 100%;
}
.deselectedDiv {
background-color: #bababa;
color: #000;
height: 30px;
width: 100%;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div class="selectedDiv" id="div1">I am Div 1</div>
<div class="selectedDiv" id="div2">I am Div 2</div>
<div class="selectedDiv" id="div3">I am Div 3</div>
<div class="selectedDiv" id="div4">I am Div 4</div>
<div class="selectedDiv" id="div5">I am Div 5</div>
<input type="hidden" id="hfDivSelection" runat="server" />
<asp:Button runat="server" ID="buttonSave" OnClick="buttonSave_OnClick" Text ="Save" OnClientClick="GetSelection()"/>
</form>
<script type="text/javascript">
$('div').click(function () {
var css = $(this).attr('class');
if (css == 'selectedDiv') {
$(this).attr('class', 'deselectedDiv');
} else {
$(this).attr('class', 'selectedDiv');
}
});
function GetSelection() {
$('div').each(function() {
var values = $('#<%=hfDivSelection.ClientID%>').val();
var css = $(this).attr('class');
var divId = $(this).attr('id');
if (css == 'selectedDiv') {
$('#<%=hfDivSelection.ClientID%>').val(values + divId + ':true;');
} else if (css == 'deselectedDiv') {
$('#<%=hfDivSelection.ClientID%>').val(values + divId + ':false;');
}
});
}
</script>
</body>
</html>
Code Behind :
protected void buttonSave_OnClick(object sender, EventArgs e)
{
foreach (var selectedDiv in this.hfDivSelection.Value.Split(';'))
{
var divId = selectedDiv.Split(':')[0];
var divValue = selectedDiv.Split(':')[1];
// Perform action on divId and divValue
}
}
I recommend the $.ajax function of jquery. It is very convenient.
Here is an example.
Javascript + jquery code:
//this $.ajaxSetup step is optional, but will save you a bunch of caching and asynchrony problems.
$.ajaxSetup({
cache: false,
async: false
});
$.ajax({
type: "POST",
url: 'submit.aspx',
data: {"field1": "value1", "field2": "value2"},
dataType: 'json',
success: function(response){console.log('Data submit worked. Response was:\n' + response)}
});
(More info on this function at http://api.jquery.com/jQuery.ajax/.)
Then, in submit.aspx, place your code to get the info, this SO article may help.
You can then save the data to an xml file via asp.net. When you want to reload the user's settings, you can use the GET command of the $.ajax function:
$.ajax({
type: "GET",
url: '/data/userfields.xml',
dataType: "xml",
success: function(xml) {
var fieldvalue = $(xml).find('a_node').attr('an_attrib');
//...
},
error: function(xml) { console.log ('failed to get xml file on import of file: /data/userfields.xml');}
});
In my opinion the best thing would be to use checkboxes (placed in a form that will be submited on button click) and use CSS to stile the div's accordig to the checkbox statuses.
I suggest using ajax callbacks. Using cookies on this approach is a bit messy. Create "on click" events on each div and if you really want to use a best practice approach to save data on the client side I suggest using Local Storage:
http://www.w3schools.com/html/html5_webstorage.asp
Hope this helps

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.

How to code one jquery function for all AJAX links

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');
}

Categories

Resources