How to pass GET request to window.location in JavaScript? - javascript

I have a script that is supposed to get the username and go to another page with that username in URL, like this: www.site.com/members/?username=john. How can this be done with javascript? I have my current code like this
<script>
window.location = 'www.site.com/members/?{$member.username}';
</script>
What this does is www.site.com/members/?john but I need to pass assign parameter as GET request. Any help is appreciated.

You need to first create a string with the required location in it:
<script>
window.location = 'www.site.com/members/?username=' + username_variable;
</script>
Or your way of doing it (using ES6 formatting):
<script>
window.location = 'www.site.com/members/?username={$member.username}';
</script>

Suppose member.username is a working variable with the username.
<script>
//..
window.location = 'www.site.com/members/?'+member.username+'';
</script>

JavaScript is client-side technology, it cannot get any data by itself. Try to make ajax call to a server-side REST API and get the data back.

Related

How to pass a GET value when using history.back()?

I have a variable to check if the data is present already in the database.
If the data is already present it would go back to the form page to input a new data. Here is what I have
<script type="text/javascript">
window.history.back();
window.location = 'register.php?msg='<?php echo 1;?>
</script>
Also I have tried this but I don't know how to pass it in the URL:
<script type="text/javascript">
window.history.back();
window.alert('<?php $msg = 1; echo $msg;?>')
</script>
You can use History API to change the url:
history.back();
history.replaceState({}, "Registration", "register.php?msg=1");
location.reload();
You can use:
window.location = "baseurl/route?get=var"
instead of
window.history.back()
You need to be able to have baseurl as your global variable. Have it sent from your server and set in javascript as a global variable.
using browser back is fragile since you cannot predict (or check) where would that lead the user.
instead I would recommend that upon the relevant user action or business logic the app would explicitly navigate to register.php page with your desired parameter
// some code handling
var dataAlreadyPresent = checkIt();
if (dataAlreadyPresent) {
window.location = "/register.php?msg=yourMsg";
}
BTW, keep in mind that this URL is saved and users might bookmark it or forward it along, so may I suggest that the register.php server logic better not act automatically based on that input. you might want to clean the history state using replaceState (as per jcubic answer) once the register.php has loaded.

Displaying data on next page with jQuery session or another possible way?

here my simple form:
<form id="myform">
Name:<input type="text" name="name"><br>
Email:<input type="text" name="email">
<a class="btn btn-primary" id="click_btn">Submit</a>
</form>
I want to submit the form with Ajax, that bit is okay so far, and submitting.
Here is my jquery code:
$(document).ready(function() {
$('#click_btn').on('click', function() {
$.ajax({
url: $('myform').attr('action'),
data: $('myform').serialize(),
method: 'post',
success: function(data) {
//success meseg then redirct
alert('success');
var data = $('#myform').serializeArray();
var dataObj = {};
$(data).each(function(i, field) {
dataObj[field.name] = field.value;
window.location.href = 'next_page.php';
});
}
})
});
})
next_page.php is where I want to access, example:
<?php echo document.write(dataObj["email"]); ?>
I want to access these form values that I have submitted on next page after the form is submitted. I have created a data object with all the values using jQuery after submit, but still, I cannot access on the next page. Is there any concept related to the session in jquery for storing that array.
I think you're getting a couple of concepts confused here; I don't mean that in a condescending way, just trying to be helpful.
jQuery, and all JavaScript, exists only on the client-side (for practical purposes - there are exceptions where some client-side code might be rendered or compiled on the server-side for whatever reason but that's another matter). PHP, like any other server-side language, exists on the server-side. These two can't directly access each other's scope - which is why AJAX is useful to transfer data between the front and back ends.
Basically what you appear to be doing here is loading the data in the client-side, but not submitting anything to the server-side. You aren't actually doing any AJAX queries. When you redirect the user via window.location.href =..., no data is actually being transmitted - it simply instructs the browser to issue a new GET request to next_page.php (or wherever you instruct it to go).
There are a couple of options to do what you're trying to achieve:
Actually submit an AJAX query, using the methods outlined here http://api.jquery.com/jquery.ajax/. You can then use next_page.php to grab the data and store it in a session and recall it when the user arrives on the page.
Store the data in a client-side cookie.
Use the standard HTML <form method="next_page.php"...><input type="submit"> to cause the browser to forward the form data to the next_page.php script.
A number of other options but I think those are the simplest.
You can totally use sessionStorage ! (Here is documentation)
If user direct to next page in same tab, sessionStorage can easily save you data and reuse in next page.
// set in page A
window.sessionStorage.setItem('youdata', 'youdata');
// or window.sessionStorage['youdata'] = 'youdata';
// get in page B
var youdata = window.sessionStorage.getItem('youdata');
// or var youdata = window.sessionStorage['youdata'];
That's it! very simple!
If you'll open a new tab, you can use localStorage. (Here is documentation)
The usage of localStorage is like the way of sessionStorage.
While do saving information for other pages, these two method only need browsers' support.
<?php echo document.write(dataObj["email"]); ?>
This is unreasoned! echo is a PHP command, but document.write is a JavaScript command.
If the secound page is PHP, why not send data with a simple POST submit from HTML Form?
You can also use localStorage:
var data = '123';
localStorage['stuff'] = data;
Use localStorage.clear(); to remove all data if you want to write it again or for specific item use localStorage.removeItem('stuff');
List of some possible solutions are as follows:
1. Post the data using AJAX request and the get it in next page by doing DB call (Advisable)
2. Using Local storage you can store the data in the browser to push it to next_page.php https://www.w3schools.com/Html/html5_webstorage.asp
2a. In the first page
<script>
localStorage.setItem("name", "John");
localStorage.setItem("email", "John#test.com");
</script>
2b. In second Page
<script>
var name = localStorage.getItem("name");
var emaeil = localStorage.getItem("email");
</script>
3. Using browser session storage https://www.w3schools.com/jsref/prop_win_sessionstorage.asp
3a. In the first page
<script>
sessionStorage.setItem("name", "John");
sessionStorage.setItem("email", "John#test.com");
</script>
3b. In second Page
<script>
var name = sessionStorage.getItem("name");
var emaeil = sessionStorage.getItem("email");
</script>

Pass javascript variable to php without a form and redirect

I'm trying to pass a JS variable to php without a form. In simple words I got the current slide of the flexslider and I passed like a variable in javascript for after convert it to PHP variable and redirect it to the step "step_3.php".
I tried to used an ajax but it didn't work.
step_2.php
Next Step
<script>
$( document ).ready(function() {
$("#btn_next").click(function() {
var face = $('.flexslider').data('flexslider').currentSlide;
/*transform var face to PHP and redirect to step_3.php */
});
</script>
step_3.php
get the value
If any could help me i would appreciate a lot
What about this?
$( document ).ready(function() {
$("#btn_next").click(function() {
var face = $('.flexslider').data('flexslider').currentSlide;
location.href = "step_3.php?face="+face;
});
And then in step_3.php you process the face value and continue doing your things
You could redirect with javascript by setting the url like this window.location.href = url.com and tack a GET variable onto the end of it like window.location.href = url.com?var=value and on the page you redirect to, get the variable in PHP with
$var = $_GET['var'];

Reaching a data in json using getJSON

I want to get the username's profile image. So i prefer to use twitter api version 1 for this.(The regular version of api is here). But my code doesn't return any data. How can i fix this?
<html>
<head>
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script>
$(document).ready( function() {
var userPage = "https//twitter.com/jack";
var arr = userPage.split("/");
var username = "";
for(i=3;i<4;i++)
username += arr[i];
var page = 'https://api.twitter.com/1/users/show.json?screen_name='+username;
$.getJSON(page, function(data) {
alert(data.profile_image_url);
});
})
</script>
</head>
<body>
</body>
</html>
Add "&callback=?" to the URL to force jsonp format to get around the Access-Control-Allow-Origin issue.
var page = 'https://api.twitter.com/1/users/show.json?screen_name='+username + "&callback=?";
EXAMPLE
JSONP:
The way JSONP works is simple, but requires a little bit of
server-side cooperation. Basically, the idea is that you let the
client decide on a small chunk of arbitrary text to prepend to the
JSON document, and you wrap it in parentheses to create a valid
JavaScript document (and possibly a valid function call).
The client decides on the arbitrary prepended text by using a query
argument named jsonp with the text to prepend. Simple! With an empty
jsonp argument, the result document is simply JSON wrapped in
parentheses.

Use Javascript to reload the page and specify a jquery tab

I want to use javascript to reload a page. I can't just use
window.location.reload(); as I'm using jquery tabs and want to specify a tab to be selected after the reload. Is setting window.location.href the best way to do this?
i.e. window.location.href = window.location.href + '#tabs-4';
A cleaner way:
window.location.hash = 'tabs-4';
window.location.reload();
All you have to do is to pass a var in the url (post) than with your javascript retreive it and select the tab associated to the var
you can have variable in redirect link like
index.html?tab=4
and than check it's value in javascript.
function get(name){
if(name=(new RegExp('[?&]'+encodeURIComponent(name)+'=([^&]*)')).exec(location.search))
return decodeURIComponent(name[1]);
}
you can use this code to get a value. like
selec=get('tab');
$tabs.tabs('select', selec);
to switch to a tab.
See this link to get more details about
How to get "GET" request parameters in JavaScript?
As Brandon Joyce commented, my original code was probably best:
window.location.href = window.location.href + '#tabs-4';

Categories

Resources