Ways to post query data to URL without a form? - javascript

I need to pass a couple bits of info through the URL just by clicking a link, rather than by using action="GET" with a form and input button. Is this possible? This is client-side only, there is no server, so suggestions regarding PHP etc. will not be useful in this circumstance.

In your anchor, change the href to include a querystring at the end.
e.g.
<a href="http://www.example.com/test.html?parameter=2">

Assuming you have access to the variables on the client, you can do something like this:
<script type="text/javascript">
navigateToPage = function(val){
window.location.href = "/somefolder/somefile.htm?id=" + val;
}
</script>
<input type="button" value="Navigate" onclick="navigateToPage(5);" />

You're gonna need to use JavaScript to get all the values, and then combine them into a URL.
Here's an example (using the jQuery library):
Click
<script>
$(function(){
// The data, from the page
var id = 1, name = 'test';
// Add event to link
$('#paramLink').click(function(e){
e.preventDefault(); // Stop the browser from following the link
location.href = $(this).attr('href')+'?id='+id+'&name='+name; // Build the URL
});
});
</script>

put your bit of info in anchor and post along with it
click!
how to get these values on redirected page; and in case you using PHP.
$id=intval($_REQUEST['id']);
$action=$_REQUEST['action'];

Related

AJAX call to differrent page in same domain works, but does not load everything

So, a little context: I'm trying to do an ajax call to a webpage in the same domain to get a telephone number to show up as soon as I specify the client on the first page. I do get the data but it seems like not the whole page is loaded in.
I need this:
<div id="1">
<div id="2">
<a id="ineedthis"></a>
</div>
</div>
but instead it's giving me this:
<div id="1">
</div>
This is a website that I'm writing a script for, since I can't edit the source code. This is managed from our ERP program and is pretty limited in customizability.
My best guess is that the target webpage is also still loading in the information from the database, but my ajax call returns the webpage before that happens.
Here is my js code:
function updateClasses(){
var link = $('a[href^="/organisatie-beknopt-prs?BcId="]');
var href = "https://52134.afasinsite.nl" + link.attr("href");
console.log(href);
if(href !== "https://52134.afasinsite.nlundefined"){
$.ajax({
url:href,
type:'GET',
success: function(data){
var tel = $(data).find("#P_C_W_Title_Content");
console.log(tel);
}
});
}
}
setInterval(updateClasses, 1000);
I'm running this once per second to check for a change in the input field on the first page, I don't know if there is a better way for this?
Firstly, you could try running the script/function once a change has been detected.
Something along the lines of :
$('input[name="{inputFieldName}"]').on('change',function(){
updateClasses();
});
//You can also use "keyup" instead of "change", depending on the type of action that you are looking for.
For the Ajax, you could try using Promises. Basically, set up the ajax call and then set a ".done" case for the ajax call has been completed and received some result. A ".fail" can also be used to catch non-code related issues.
function updateClasses(){
var link = $('a[href^="/organisatie-beknopt-prs?BcId="]');
var href = "https://52134.afasinsite.nl" + link.attr("href");
var getPhonePromise = $.ajax({
url: href
});
getPhonePromise.done(function(data) {
var tel = $(data).find("#P_C_W_Title_Content");
console.log(tel);
});
getPhonePromise.fail(function(errRes) { console.log(errRes);});
}

Save text from a href link threw javascript

I want to store a value to the cache using javascript when clicking an a href link. I'm setting up following code dynamicall
<a align="left" href="projectoverview.html">Test Manager</a>
So I want to save the text Test Manager to the cache, but I don't know how to catch this text when it's clicked. The code below is how that piece of code is setup. Do I need to add an onclick or something or is there a better way?
var text = '<a align=\"left\" href=\"projectoverview.html\">' + project['title']
+ '</a><p align=\"right\">';
If you want to pass data from page to page using javascript/jquery you can do so with sessionStorage. Below is just an example of how you would do it using jQuery.
$('a').each(function() {
$(this).on('click', function() {
var linkText = $(this).text();
// Save data to sessionStorage
sessionStorage.setItem('clickedLink', linkText);
});
});
Then on the next page you can call it by using the .getItem function like so.
$(function() {
var data = sessionStorage.getItem('clickedLink');
alert(data);
});
If implemented correctly the alert box will say "Test Manager".
You can read more about sessionStorage here.
EDIT:
I would add a special class to those links though because the code above will execute on any link you have on the page which may give you unwanted issues.

Inject GET parameter to target URL of a button, on click

I have multiple buttons with the class myButton. Each button has a value which is send to a server on click. The target URL of the button does look like this:
http://mysite/test/test.html?cid=15
After I click on the button, the following GET parameter should be added to the URL and then the button should be submitted:
mySessionVar=1
So the new URL should look like this:
http://mysite/test/test.html?cHash=d009eb3f9f4e1020435b96a8f7251ad5&mySessionVar=1
Why I have to inject it?
I am working with fluid. AFAIK it is not possible to manipulate fluid tags with JavaScript. However, I need to add a sessionStorage item value to the fluid tags arguments attribute.
My fluid code:
<f:link.action controller="Download" action="download" arguments="{cid: category.uid}" class="myButton">Download</f:link.action>
So my attempt is to append my sessionStorage item as GET parameter to the target URL of the button and then send it, e.g.:
$(".myButton").on
(
"click",
function(event)
{
//First prevent the default event
event.preventDefault();
...inject the sessionStorage item as GET parameter to the target URL of the button, then do whatever the button would do normally...
//Go to new URL
window.location.replace(NEW URL);
}
);
Is this possible?
EDIT: This is how the rendered HTML of the buttons looks like:
<a class="myButton" href="/de/mysite/test/test.html?tx_mydownloads_myfilelist%5Bcid%5D=15&&tx_mydownloads_myfilelist%5Baction%5D=download&tx_mydownloads_myfilelist%5Bcontroller%5D=Download&cHash=d009eb3f9f4e1020435b96a8f7150ad5">Download</a>
EDIT: I have another idea, maybe I could just read the target URL somehow, then add my new GET param to it and then load that URL with window.location.replace?
You can indeed just use the href from the button and use it to feed window.location.href, like so:
$('.myButton').on('click', function(e) {
e.preventDefault();
var href = $(this).attr('href'),
queryString = 'mySessionVar='+sessionStorage.getItem("myItem"),
newHref;
if (href.indexOf('?') !== -1) {
newHref = href + '&' + queryString;
} else {
newHref = href + '?' + queryString;
}
window.location.href = newHref;
});
This also handles the case when there is no previous query string present on the link and appends it with ? instead of &, but that part can be omitted if that won't happen in your app.
The following snippet should be enough to add your mySessionVar=1 parameter to the href attribute:
$('.myButton').on('click', function(e) {
$(this).attr('href', $(this).attr('href') + "&mySessionVar="+ sessionStorage.getItem('myVar');
});
You don't have to prevent the default, because your click handler function is called before the default event handler (who does roughly speaking: read the href attribute and load it).
You can use .serialize function in jquery which is simple and modern function to get all the selected buttons/filters into a url param format with amberson simple. I can't explain more clear than what is said in Jquery website. Please refer the link below to find how to use the function. https://api.jquery.com/serialize/#serialize

Javascript two weird problems: POST not working, window.location.href not working

I created an instant search similar to google search using JQuery. The highlighted code doesn't work. It is weird since they work fine by its own and everything else works fine. Any idea why this is happening?
Q1.
searchq() works fine, but the createq() function doesn't work, and the variable txt could be posted to other files(search.php). However, the function createq() can't POST. It does get the global variable txt after testing, but the php file(create_object.php) can't get it no matter what POST method I used. Could anyone helps to write a bit POST code which can work in my code.
Q2
I want to create a function that,when the enter is pressed, the user will be redirected to the first search result(which is anchored with an url) . To achieve this, I create a function that variable redirectUrl got the anchored url as string, however, the redirect function window.location.href doesn't work, the page simply refreshed. I tested window.location.href function by its own in another file, it works though. It is so weird that my page simply refreshed, It even refreshed when I direct to google. window.location.href("www.google.com").
Note that I didn't include the connect to database function here. Coz I think the database username and password setting would be different to yours.So please create your own if you want to test it. The mysql is set with a table is called "objects", and it has one column named "name".
Thanks in advance!
<html>
<!-- google API reference -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<!-- my own script for search function -->
<center>
<form method="POST">
<input type="text" name="search" id="search" style="width:400px " placeholder="Search box" onkeyup="searchq();">
<div id="search_output">
</div>
</form>
</center>
<!-- instant search function -->
<script type="text/javascript">
function searchq(){
// get the value
var txt = $("input").val();
// post the value
if(txt){
$.post("search.php", {searchVal: txt}, function(result){
$("#search_output").html(result+"<div id=\"create\" onclick=\"creatq()\"><br>Not found above? Create.</div>");
});
}
else{
$("#search_output").html("");
}
};
function createq(){
// allert for test purpose: test if the txt has got by the createq function
alert(txt);
**$.post( "create_object.php",{creatVal:txt} );**
}
// if enter key pressed, redirect page to the first search result
$("#search").keypress(function(evt){
if (evt.which == 13) {
// find the first search result in DOM and trigger a click event
var redirectUrl = $('#search_output').find('a').first().attr('href');
alert(redirectUrl);
**window.location.href = "www.google.com";
window.location.href = "www.google.com";**
}
})
</script>
</html>
PHP file (search.php)
<?php
if(isset($_POST["searchVal"])){
//get the search
$search=$_POST["searchVal"];
//sort the search
$search=preg_replace("#[^0-9a-z]#i","",$search);
//query the search
echo "<br/>SELECT * from objects WHERE name LIKE '%$search%'<br/>";
$query=mysqli_query($conn,"SELECT * from objects WHERE name LIKE '%$search%'") or die("could not search!");
$count=mysqli_num_rows($query);
//sort the result
if($count==0){
$output="there was no search result";
}
else{
while($row=mysqli_fetch_assoc($query)){
$object_name=$row["name"];
$output="<div><a href='##'>".$object_name."</a></div>";
}
}
echo $output;
}
?>
php file (create_object.php)
<?php
if(isset($_POST["createVal"])){
$name=$_POST["createVal"];
var_dump($name);
}
?>
In createq() you are trying to access the local variable txt that was defined in another function. If you declare a variable inside a function, only that function has access to the variable.
You can fix this by passing txt as an argument to createq. In order to do this, you need to call createq yourself instead of setting it as an event handler for a click event.
Use jqoery's .click() to add a proper event handler for the click event and from that handler call createq, passing along the value of txt. In order to set the click handler, you need a reference to the element with the id "create", that you currently don't have.
The solution to this particular problem looks something like this:
$.post("search.php", {searchVal: txt}, function(result){
$("#search_output").html(result+"<div id=\"create\"><br>Not found above? Create.</div>");
$("#search_output create").click(function() {
createq(txt);
});
});
...
function createq(txt){
...
}
About the way page refresh. If DOM element with id of window.location.href is missing the page will refresh. For example
assume you have window.location.href="#div1";
If DOM element with id="div1" is missing the page will surely refresh.

upon entering/leaving the page append a string in the url. Is this possible?

Is there a way to append a string in the url upon leaving/entering?
Say the default url is www.foo.com
Then upon entering/leaving, it becomes www.foo.com?param=1 without clicking to something?
Just using javascript.
Any help would be much appreciated. Thanks!
Here is one possible method to do that. This is using jQuery, and only adds the parameter on page entry (on page leave, it's kind of pointless; also, that would trigger on addition for the first case as well) -
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
$( window ).load(function() {
if (! window.location.href.contains("param=0")) {
window.location.href = window.location.href+"?param=0";
}
});
</script>
The easiest ways to do this would be to change document.location.search (which targets parameters) like this:
if (document.location.search != ("?param=1")) {
document.location.search = "?param=1";
}
note that this essentially triggers a page reload though.

Categories

Resources