How to get parameter from URL using javascript - javascript

I passed a parameter through an URL using javascript. Here's the code:
<script>
window.onload = function() {
// Creating a cookie after the document is ready
var cookies = document.cookie.split(";")
var cookiePair = cookies[0].split("=");
var cookie_user=cookiePair[1]; // remove ending parenthesis here
window.location.replace("http://192.168.206.1/foodblog/?page=http://192.168.206.1/test/ChangeInfo.php&username="+cookie_user);
};
</script>
The page that received the parameter is called ChangeInfo
This is what I see in the URL when I get to the ChangeInfo page:
http://192.168.206.1/foodblog/?page=http://192.168.206.1/test/ChangeInfo.php&username=nitzan
When I'm trying to get the parameter username from the URL, I get this error:
Notice: Undefined index: username in C:\xampp\htdocs\test\ChangeInfo.php on line 5
The way I'm trying to get this parameter is to use $_GET like that: $username = $_GET['username'];
Does anyone know why this makes me a problem?
Thanks in advance

I just solve the problem
I deleted the Page parameter from the URL I created in javascript part.
this is the updated Javascript part:
<script>
window.onload = function() {
// Creating a cookie after the document is ready
var cookies = document.cookie.split(";")
var cookiePair = cookies[0].split("=");
var cookie_user=cookiePair[1]; // remove ending parenthesis here
window.location.replace("http://192.168.206.1/test/ChangeInfo.php?username="+cookie_user);
};
</script>
thank you :)

Ignoring the javascript part, needing to focus on PHP.
You are on this page:
http://192.168.206.1/foodblog/?page=http://192.168.206.1/test/ChangeInfo.php&username=nitzan
And when you use $_GET['username'] you get the error, that it is not assigned.
It seems that your $_GET is not working at all, probably Apache settings.
Also, it is safer to get GET parameters with isset first.
if(isset($_GET['username']) && $_GET['username']] {
$username = $_GET['username'];
}
else {
$username = '';
}
Then you can compare, if username is set or not in your php code:
if($username) {
//Do something
}
Final thought. Is your first parameter page=http://192.168.206.1/test/ChangeInfo.php working? Can you get it through $_GET?
The problem seems to be just in the way you set and get the url parameter though $_GET. If you use some framework, it might be disabled to use $_GET directly and for example in Symfony you need to use:
$request->get('username');

Related

How to sent data to server, remove parameter from url and reload window with new url Javascript, jQuery and PHP

I am currently stuck with a problem I can't seem to find a decent solution for.
Problem:
I have written some code that will send 2 parameters to an action within a PHP script through a url. I need these parameters sent to the action no matter what. However, after the parameters are sent, I need to remove one of said parameters from the URL and then reload the page with said new URL.
I hope I could give you a clear description of my problem. Following is the code I have written so far.
jQuery(document).ready(function() {
// Define array with the dashboard id and title as key => value pairs.
var dashboardArray = <?php echo json_encode(CHtml::listData($dashboards, 'iddashboard', 'title')); ?>;
// Loop through the elements in the dashboardArray and then create option elements to be added to the above create select element.
for (var idDashboard in dashboardArray) {
$('#idDashboards').append($(document.createElement('option')).prop({
value: idDashboard,
text: dashboardArray[idDashboard].charAt(0).toUpperCase() + dashboardArray[idDashboard].slice(1)
}));
};
// Get arg01 from the server.
var arg01 = <?php echo json_encode($arg01); ?>;
// Prepare URL variable and spike it with arg01 to be sent back to the server.
var url = 'Path/To/action/Index/index&arg01='+arg01;
// Button change and function tied to it. Instead of an ajax request, we reload the page completely.
$("#idDashboards").change(function() {
// Define dashboardIndex. The -1 stands for the option tag that has already been created.
var dashboardIndex = $(this).prop('selectedIndex')-1;
// Sent parameters to actionIndex in Controller and remove dashboardIndex after the request was successful.
if (url.includes(arg01)) {
window.location.href = url+"&dashboardIndex="+dashboardIndex;
console.log("Yes i was here");
}
// window.location.href = url; <---- Here is where the problem begins.
});
});

Passing section of query result into session variables with Javascript

I'm having trouble passing the result of a query into a session variable, I think that the easiest way to do this is through Javascript. I have the query result showing but they will not pass to the session variable. At the end of each query resultant row, I have an add button that will activate the JS function to add to the session variable.
Query Result:
echo '<tr><td>'.$products['Name'].'</td><td>£'.$products['Price'].'</td><td>'.$products['Category'].'</td><td><img src="'.$products['Image'].'" width=100px /></td><td>'.$products['ProductID'].'</td><td><button onclick="setProduct('.$products['ProductID'].')">Add to Basket</button></td></tr>';
JS Function:
function setProduct(x){
var productID = x;
'<%Session["ProductID"] = "'+$products['productID']+'";%>';
Code displaying contents of session variable:
echo $_SESSION['ProductID'];
$_SESSION is a server-side variable. You'd most likely want to set a $_COOKIE instead. Those are accessible on the client-side.
In addition to the answer posted, you can create a jQuery post request (or you can use AJAX) and send the JS session as value to a PHP file where you can access that value and create the corresponding PHP session.
Let's say, your JS function:
function setProduct(x){
var productID = x;
'<%Session["ProductID"] = "'+$products['productID']+'";%>';
// ...
$.post('example.php', { session_name: YOUR-SESSION-NAME, session_value: YOUR-SESSION-VALUE });
example.php:
if (isset($_POST['session_name']) && isset($_POST['session_value'])) {
$_SESSION[$_POST['session_name']] = $_POST['session_value'];
}
This is not taking into consideration security issues you might face. You should encrypt your data before sending it.

js refresh page while passing variable in yii

I am trying to refresh the page while pass an array from an onclick button.
Since I am using yii, posting isn't an option, and setting a session variable wasn't working. Any ideas would help. Thank you
<a style="width:100%;" onclick="my_picks_reset()" id="my_picks_reset">Reset</a>
<script>
$(function() {
/*set var picks = array of TBA and reset th my_picks div*/
$("#my_picks_reset").click(function() {
var my_picks = ['TBA','TBA','TBA','TBA','TBA','TBA','TBA','TBA'];
var url = document.URL;
$(location).attr('href',url,'my_picks',my_picks);
})
})
</script>
It seems from your comments that you're expecting POST request. Changing location of the page will give you GET request. So you have two options here:
1) Continue using location and read the the values from $_GET variable.
If you decide to use this option your need loop through my_picks array and construct the query string that would look like that:
?my_picks[]=arrayValue1&my_picks[]=arrayValue2... and do location.assign(currentLocation + composedQueryString)
2) The second better solution is to use $.ajax() to send values with post method.

Jquery .get() result evaluation not working

I'm relatively new to javascript, but I've read lots of posts talking about Jquery .get and the need to use a callback function today... but I guess I'm still not doing it right. I have a function that 'gets' the result from a PHP page which accesses a MySQL table.
I've included alerts in my code so I can see that the page is called correctly and is returning the result I expect. If the file already exists in the database then the 'get' returns "exists" if the file is in the database but flagged as deleted 'get' returns "deleted" and if the file isn't in the database 'get' returns nothing.
However, when I place alerts inside the if(file_exists=="exists") statement they never get triggered. I even tried moving the entire evaluation section to another function and calling that function from inside the first. still no joy. docReplace never gets set to true and I never see the dialog asking if I want to replace it.
Please, some helpful suggestions?
<script type = "text/javascript" language = "javascript">
function docCheck(){
var attachfilepath = document.getElementById("AttachFile").value;
var docguid = document.getElementById("DocGuid").value;
//cut the file path down so just get the filename
attachfile = attachfilepath.substr(attachfilepath.lastIndexOf("\\")+1);
// Check to see if file exists.
$.get("Doc_Check.php", {guid:docguid, filename:attachfile}, function(file_exists){
alert(file_exists);
if(file_exists=="exists"){
if(confirm("The file \"" + attachfile +"\" already exists. Would you like to replace it?")){
document.getElementById('docReplace').value = "true";
}else{
return false;
}
}else if(file_exists == "deleted"){
document.getElementById('docReplace').value = "true";
}
});
var rreplace = document.getElementById('docReplace').value;
alert (attachfile);
alert (docguid);
alert (rreplace);
}
</script>

get value of a php variable set by url in javascript

Hey i defined a php variable like this inside the body tag:
<?php $v=null;?>
Now i am using this code to check if the variable is set through the url
if ("<?php echo $_GET["v"];?>;" == null) {
// Do something because the variable is set through the url
}
else {
// Do something else because the variable is not set through the url
}
I am using an url like this: www.example.com/index.php?v=12345
When i run this code by opening the index with this url it says v is undefined..
When i run this code by opening the index with "www.example.com/index.php" it is undefined as well.. but not 'null'
What is the problem here? Thank you
Try like
var my_var_arr = location.search.replace('?', '').split('=');
if (my_var_arr[1] == null) {
// Do something because the variable is set through the url
}
else {
// Do something else because the variable is not set through the url
}
Try this FIDDLE
You can use javascript to get the query string parameter instead of php. There is lot of tutorials around here.
Ref: http://javascriptproductivity.blogspot.in/2013/02/get-url-variables-with-javascript.html
Possible solution: jquery get querystring from URL

Categories