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.
Related
function createPost(){
$('#body').append("<p>Welcome to calmspace.</p>");
}
How would I utilize user input so the user can create a post with their own message? I am a newbie with jQuery so if this is a stupid question please forgive me. Possible duplicate but I couldn't find another post like this.
First things first - you should not have added '#' in front of body, it'd mean that the body element is of id 'body', assigning id to an element that is unique does not bear that much sense, instead you should just target the tag - $('body').
In order to provide some sort of message you first have to capture it, for instance using some sort of input. Here is a working demo.
$('#submit').click(function(){
createPost($('#text').val());
})
You read it as follows, grab element of id 'submit', assign it a click event, grab the value of input box of id 'text' and pass it to a function named create post which accepts a string parameter and then prints it in a <p> tag.
#Simion Benderschii a working example of a post which appends to the document or sends via ajax. Hope this helps
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<title>JS Bin</title>
</head>
<body>
<div>
<h2>Enter your post here</h2>
<form>
<textarea id='user-input-post'></textarea>
<div>
<button id=user-post-button>Post</button>
</div>
</form>
</div>
<div>
<h2>Below are your posts</h2>
<ul id='user-post-display'>
</ul>
</div>
</body>
<script>
/*possible options can be
'display' - which shows the post in the UI in a unordered list
'ajax' - which send the post to the server via ajax
*/
var post_type = 'display';
//the id of the list where the post will be appended
var list_id = '#user-post-display';
//the id where the post will be entered
var post_id = '#user-input-post';
//the id of the button which triggers some action
var button_id = '#user-post-button';
//this gets the post from the textarea
var get_post = function() {
var post = $(post_id).val();
return encodeURIComponent(post);
};
//this appends the post to the list
var append_post = function() {
var post = get_post();
var html_string = '';
if (post) {
html_string = '<li>' + post + '</li>';
$(list_id).append(html_string);
}
};
//this sends the post via ajax and triggers callbacks
var send_post = function() {
var post = get_post();
var post_created_on = Date.now();
var url = 'dummy_url_for_posting';
$.ajax({
method: 'POST',
url: url,
data: { data: {
post: post,
post_created_on: post_created_on
}}
})
.done(function() {
window.alert('post success');
})
.fail(function() {
window.alert('post fail');
})
.always(function() {
window.alert('post triggered');
});
}
//main function which is the entry point
var main = function() {
$(button_id).on('click', function() {
event.preventDefault();
debugger;
if (post_type === 'display') {
append_post();
} else if (post_type === 'ajax') {
send_post();
}
});
};
//triggers the main function
main();
</script>
</html>
I am not exactly sure what you want to do from your question. In future questions you will find it helpful to provide more detail on exactly what you want to do with your application or function.
The basic idea here is to use a button or any action you can capture with jQuery (like pressing enter or checking $(element).on('click',... and then putting that info where you want using $(element).html(...) or .append(...).
Here is a fiddle I made with the rough idea. Try to use this fiddle tool a lot, and you can also post the link to what you have tried in future questions. Good luck :-)
JSFiddle example of submitting a post
I am trying to access JavaScript variable in the href attribute of anchor tag.
JavaScript Function:
<script type="text/javascript">
function fun(ReqTextbox)
{
var queueData =document.getElementById(ResTextbox).value;
//some more code
}
</script>
HTML code:
<body>
<input type="text" value="<%=dynamicValue%>" id="<%=dynamicId%>"/>
<a href="servlet?variablename="<%Eval(queueData)%>" onclick=fun('<%=dynamicvalue%>');>LINK</a>
</body>
I know that I am going to wrong at variablename="<%Eval(queueData)%>".
Can someone please help me how to access and pass JavaScript variable as a query string parameter?
First, I think you made a typo :
function fun(ReqTextbox) {
var queueData = document.getElementById(ResTextbox).value;
//some more code
}
You get ReqTextbox parameter but you use ResTextbox. Then, since Javascript is client-sided, you have to manually update the href tag using href attribute. So your function would be like :
function fun(ReqTextbox) {
var queueData = document.getElementById(ReqTextbox).value;
document.getElementById('myAnchor').href = "servlet?variablename=" + queueData;
//some more code
}
And give your anchor tag an id, myAnchor in my example.
Modify HTML code as given below -
<body>
<input type="text" value="<%=dynamicValue%>" id="<%=dynamicId%>"/>
<div id="example2">
<a href="servlet?variablename="<%Eval(queueData)%>" onclick=fun('<%=dynamicvalue%>');>LINK</a> </div>
</body>
Use this to pass query string -
$("#example2 a").attr("href", url + "?variablename=" + queueData);
If I understand you correctly inside fun() function try to use:
var queueData = this.getAttribute('id');
That way you will get id value when runnning onclick() function.
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.
I want to POST form values and display them on another html page using Javascript. No server-side technology should be used. I have a function that posts the values but to read the values to another html page, I think I am missing something. Below is the code.
Any help? Thanks in advance.
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Untitled Page</title>
<script type="text/javascript">
function post_to_page(path, params, method) {
method = method || "post"; // Set method to post by default, if not specified.
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);
form.setAttribute("target", "formresult");
for (var key in params) {
if (params.hasOwnProperty(key)) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", params[key]);
form.appendChild(hiddenField);
}
}
document.body.appendChild(form);
// creating the 'formresult' window with custom features prior to submitting the form
window.open('target.htm', 'formresult', 'scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,status=no');
form.submit();
}
</script>
</head>
<body>
<form id="form1" action="target.htm" method="post">
<div>
USB No: <input name="usbnum" id="usbnum" type="text"/><br />
USB Code: <input name="usbcode" id="usbcode" type="text"/>
</div>
<button onclick="post_to_page()">Try it</button>
</div>
</form>
</body>
</html>
Here is a simple example of moving data from one Window to another
<!-- HTML -->
<textarea id="foo"></textarea><br/>
<input id="bar" value="click" type="button"/>
and the real code to make it work, which assumes you pass the same origin policy
// JavaScript
var whatever = 'yay I can share information';
// in following functions `wnd` is the reference to target window
function generateWhatever(wnd, whatever) { // create the function actually doing the work
return function () {wnd.document.getElementById('foo').innerHTML = whatever};
} // why am I using a generator? You don't have to, it's a choice
function callWhenReady(wnd, fn) { // make sure you only invoke when things exist
if (wnd.loaded) fn(); // already loaded flag (see penultimate line)
else wnd.addEventListener('load', fn); // else wait for load
}
function makeButtonDoStuff() { // seperated button JS from HTML
document
.getElementById('bar')
.addEventListener('click', function () {
var wnd = window.open(window.location); // open new window, keep reference
callWhenReady(wnd, generateWhatever(wnd, whatever)); // set up function to be called
});
}
window.addEventListener('load', function () {window.loaded = true;}); // set loaded flag (do this on your target, this example uses same page)
window.addEventListener('load', makeButtonDoStuff); // link button's JavaScript to HTML when button exists
You can't get POST values using JavaScript. You can use GET method to pass values.
If you are using html5 you can use localStorage. Otherwise a query string or cookies are your other options.
You said you didn't want the server involved...why are you calling submit?
[Edit]
#Paul S's comment/answer looks very helpful. But you might look at something like the jQuery PostMessage plugin if you need it to be cross browser compatible.
http://benalman.com/projects/jquery-postmessage-plugin/
You don't require a POST request to send data from one page to another. Simply use LocalStorage to do the trick. Just call a Javascript function on form submission. This may help:
HTML:
<form id="form1" action="target.htm" method="post">
<div>
USB No: <input name="usbnum" id="usbnum" type="text"/><br />
USB Code: <input name="usbcode" id="usbcode" type="text"/>
</div>
<button onclick="post_to_page()">Try it</button>
</form>
Javascript:
function post_to_page() {
localStorage.value = "Your content here";
window.location = "nextpage.html";
}
This will save the data locally and go to the next page. In the next page, simply call this function to retrieve the stored data:
function get_stored_data() {
alert(localStorage.value);
}
You can simply assign it to a div, textbox other Javascript variable.
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');
}