Showing posts with label url. Show all posts
Showing posts with label url. Show all posts

How to get URL parameters using JavaScript?

In this tutorial we are going to show you how to parse a URL and get values from the URL that you are passed.  

We will be using the JavaScript's built in function split() which splits the string from a separator which is passed as a parameter to this function. The result is stored as an array and we will be using it multiple times since we want to split data into key value pairs, as the server generally processes it. 

Just have a look at the following simple code.



<html>
<head>
<title>PHPJavascript.com</title>
</head>
<script>

var URL = "http://www.phpjavascript.com?firstValue=name&secondValue=email";

var query = URL.split('?')[1].split('&');

query.forEach(function(key) {
  var pair = key.split('=');
  alert(pair[0] + '=' + pair[1]);
});

</script>
</html>


URL will be split into parts based on the type of separators you are given in the function.
In this example we gave ('?', '&')

In forEach loop we are checking for the key and value pairs.
Those should be 

key1 = firstValue
value1 = name
key2 = secondValue
value2 = email

We are alerting the result that generated here.

For any queries please comment in the bellow comment section.
For more interesting and useful code snippets please follow our blog.

How to Parse/Divide URL in PHP?

parse_url is a simple tool/predefined function to parse/divide URL into individual components.

components are:

1. scheme
2. host
3. path
4. query


example:


<?php

//URL
$url = "http://www.phpjavascript.com/post.php?par1=one&par2=two";

$url = parse_url($url);

//print_r($url);

echo 'scheme = '.$url['scheme'];
echo 'host = '.$url['host'];
echo 'path = '.$url['path'];
echo 'query = '.$url['query'];

?>

Result:

scheme = http
host = www.phpjavascript.com
path = /post.php
query = par1=one&par2=two

Labels

php (35) javascript (31) phpjavascript (30) jquery (23) html (20) mysql (14) database (9) codeigniter (4) json (4) bar chart (2) calendar (2) column chart (2) framework (2) google maps (2) query (2) tables (2) url (2) dropdown (1)

Popular Posts