Pass parameters var/value to second page Php - php

I am trying to pass some parameters vars and variables from one page x to another page y
My parameterized portion looks like:
x?path=1&edu=4&cert=
How can I pass these values easily to another page using php?
Note: often times cert var has no value.
For example:
I have a file x.php that is generating a url like: xx.xxx.xxx.xxx/p?path=1&edu=4&cert= . I need to then use this url in y.php - how can I do this?
Note: I am unable to use a framework for this application
Thanks

When receiving the parameters in page x, save them in variables and add them in the link to the page y. There are better ways but they depend on exactly what you want to do.
Simple example below.
x.php?path=1&edu=4&cert=
<?php
$path=$_GET['path'];
$edu=$_GET['edu'];
$cert=$_GET['cert'];
$params = "?path=".$path."&edu=".$edu."&cert=".$cert;
?>
Link to page Y with params obtained from page X
The result will be y.php?path=1&edu=4&cert=
It doesn't matter if you don't have a value in cert, it will pass as cert=

try use header location
$path=$_GET['path'];
$edu=$_GET['edu'];
if(!isset($_GET['cert'])) header("Location: y.php?edu={$edu}&path={$path}");
else $cert = $_GET['cert'];

I'm not to understand what you want but try this :
x.php
<?php
$url = 'http:localhost/test.php?path=1&edu=4&cert=';//generated url
parse_str(parse_url($url)['query']);//get parameter on url
include("y.php");
y.php
<?php
//!\ you must secure this value /!\
var_dump($path);
var_dump($edu);
var_dump($cert);

Are u submitting any form???If you are going from x.php to y.php through some event like button click then you can do an ajax call and easily can receive the parameters in the other page.
like <input name="" type="button" onclick="showHint($x);" value="click on me!" id="start" />//wher $x=1 your value
<div id="txtHint"></div>
You can write function as
<script>
function showHint(path) {
if (path.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "y.php?p=" + path, true);
xmlhttp.send();
}
}
</script>`
Now in y.php you can catch the param as
$path= $_REQUEST["p"];
Like this you can pass the params from one php page to another.
I don't know whether you want this kind of thing or something else.

Related

script is not getting variable from GET

I have code in /user.php:
<?php
$thisuser = $_GET['user'];
echo $thisuser;
?>
And i write in browser: /user.php?user=Maria
And the website do not echo anything. What is wrong about it?
I actually have a ajax script that should send there a variable by get but it do not work at all.
EDIT here is the whole thing:
echo '<div class="thisphotobox"><div class="photouser">' . 'Dodał: '.$numphotos["user"].'</div>';
<script>
function prof(profuser){
var xmlhttp=new window.XMLHttpRequest();
xmlhttp.open("GET", "user.php?user=" + profuser, true);
xmlhttp.send();
}
</script>
This seems to be related to the <a> tag's default behavior preventing your function to execute on click.
Since you are setting the URL inside the prof() function, you don't need he href value inside the <a> tag, so you could do something like this:
echo '<div class="thisphotobox"><div class="photouser">' . 'Dodał: '.$numphotos["user"].'</div>';
Note that I just set the href value to javascript:void(0);. So now onClick should take effect and the prof() function should be invoked.
** Visually verify if it's working: **
Use this javascript code:
<script>
function prof(profuser)
{
var xmlhttp=new window.XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if ( (xmlhttp.readyState == 4) && (xmlhttp.status==200) )
{
document.getElementById('result').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "user.php?user=" + profuser, true);
xmlhttp.send();
}
</script>
Then you will also have to add, in the same file where the javascript code is, the following:
<div id="result"></div>
Finally, please make sure you are properly closing the PHP tags <?php ?> and make sure that only PHP code is inside that block. HTML and Javascript must be outside that block.
The AJAX script will send the data by POST not by GET.
GET is to 'get' the value, POST is to pass the value.
You also only use the send() value for POST, so change the GET to POST in the AJAX.
Also, you need to declare your script BEFORE you call it in the HTML.

Play audio when hidden input change value

I need to play an audio file when the hidden input field changes value.
This hidden input is in the <table> which is refreshed by Ajax to update the values.
What I need to do is, (for example) when the value turns to Yes the Clap.wav needs to play, otherwise, when the value turns to Noboo.wav must play.
Anyone can give me a sample code for this or an idea?
Thank you for those who are willing to help.
Here are some of my codes
This is the hidden input field code. It is located on table with the id of connExcel on platinum.php
<input type="hidden" name="indVal" id="indVal" value=" <?php echo $objWorksheet->getCellByColumnAndRow(5, 5)->getOldCalculatedValue(); ?> ">
And here are some of my Ajax codes
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4){
document.getElementById('connExcel').innerHTML=xmlHttp.responseText;
setTimeout('AutoRefresh()',100); // JavaScript function calls AutoRefresh() every 3 seconds
}
}
xmlHttp.open("GET","<?php if( isset( $isAdmin ) && $isAdmin == TRUE ){ echo '../../library/tosloader.php?page='. $pageID; } else { echo ../library/tosloader.php?page='. $pageID; } ?>",true);
the 'tosloader.php' just including the platinum.php to refresh the table.
in the code where you set the hidden input's value do this
$('#myHiddenID').val(myValue).trigger('change');
then just use the change event like this
$('#myHiddenID').change(function(){
var OnOff = $(this).val();
if (OnOff == "ON") { // play clap}
if (OnOff == "OFF) { //play boo}
})
Sounds like you're completely adding and removing the element from the DOM, so you'll need to watch the DOMNodeInserted event. Luckily we can bind to it. We'll assume the hidden input has a class of hiddenInput. Then we'll need to grab our source elements, aptly named <source id="yesAudio"..../> and <source id="noAudio".../> we'll use jquery's .get() method and then use the HTML5 audio api's .play(); to invoke them.
$(document).on('DOMNodeInserted', function(e){
if(e.srcElement.className == 'hiddenInput'){
if(e.srcElement.value == 'yes'){
$('#yesAudio').get().play();
}else{
$('#noAudio').get().play();
}
}
});​​​​​
I think this is what you want.
jsBin demo
HTML:
<input id="inp" type="text" value="NO" />
JS:
function checkInputValue(){
var files = { "YES": "Clap.wav", "NO": "boo.wav" };
var sound = new Audio( files[ $('#inp').val() ] );
sound.play();
}
checkInputValue(); // USE WHEREVER YOU LIKE
Or you can do like:
name your files: yes.wav and no.wav
function checkInputValue( snd ){
var sound = new Audio( snd+'.wav');
sound.play();
}
var AJAXval = ("YES").toLowerCase() ; // the returned value to lowercase
checkInputValue( AJAXval );

AJAX/LocalStorage : Is it possible to pass a JS variable to PHP?

I was wondering, what'd be the best way to store a shopping cart?
I thought about storing products ID's in localstorage/sessionstorage and then use AJAX to retrieve the products from the server.
The only problem is that I don't know how to pass the items from the localstorage to PHP...
I'm guessing it's probably not possible directly, and I thought about a form though I have no idea how to implent it...
The idea is that when a user clicks "Add to cart" the item id and quantity is added to the localstorage, and when a user views his cart, the item details (image, name, price...) are being retreived from the database.
I'm probably going to use this tutorial
http://verido.dk/index.php/ressourcer/artikler/loading-and-saving-data-dynamically-using-php-jquery-and-mysql/
I could as well give up on local storage and go with sessions and database but I'd really like to give users that dynamic web experience.
Another possible way I just came up with is to use URLs like file.php?prodid=......, although URLs like this may get way too long.
Thanks in advance!
'You must remember that Server-Side (PHP) code is read before it converts the code to browser-side code. JavaScript is manipulated browser-side...
So one-dimensionally, you cannot pass JavaScript to PHP.
However...
With Ajax and in your case I suggest JSON you can send JavaScript data to a PHP page and bring the response back to your JavaScript methods. I think this will suit your needs. I can provide a simple example if you want.
//--example below:
JavaScript:
//Ajax Method
function processAjax(queryString, processDiv, responseDiv) {
responseDiv.innerHTML = '';
var myAjax;
try {
// Modern Browsers-->
myAjax =new XMLHttpRequest();
} catch (e) {
// antique ie browsers-->
try {
myAjax =new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
myAjax =new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// Something went wrong
document.getElementById('processDiv').innerHTML="";
alert("Your browser malfunctioned! Please try again. Consider installing a modern browser if the problem persists.");
return false;
}
}
}
myAjax.onreadystatechange = function() {
if (myAjax.readyState == 4) {
var ajaxResponse = myAjax.responseText;
responseDiv.innerHTML = ajaxResponse;
processDiv.innerHTML = "";
//NOTE: HERE IS WHERE AJAX IS FINISHED, SO IF YOU WANT TO DO SOMETHING ELSE HERE YOU CAN!
//POST PROCESSING----->
// IE: alert('I am finished processing now!');
// or call another function:
// anotherFunction();
} else {
processDiv.innerHTML = '<img src="http://www.mysite.com/images/loadingicon.gif" alt="processing....." />';
}
}
myAjax.open("GET", queryString, true);
myAjax.send(null);
}
function sendStorage() {
var helloVar = 'Hello, I am passed to PHP #1';
var worldVar = 'I am the second value passed to PHP!';
var processId = 'process_div';
var resultId = 'result_div';
var queryString = 'http://www.mysite.com/process.php?hello=' + helloVar + '&world=' + worldVar;
processAjax(queryString, processId, resultId);
}
Now for some HTML:
<div id="content">
<div id="process_div"> This is where processing will occur </div>
<div id="result_div"> This is where my response will display </div>
</div>
Now for a process.php (NOTE: FOR SECURITY, I STRONGLY SUGGEST YOU DON'T REVEAL A SERVER-SIDE PROCESSING PAGE IN YOUR JAVASCRIPT)
<?php
//init
$hello = '';
$world = '';
$errors = 0;
//set
//Security note: never trust a URL request.. you should clean all $_GET, $_REQUEST, AND $_POST with the PHP htmlspecialchars() method (take a look at php.net for that)
(isset($_GET['hello'])) ? $hello = $_GET['hello'] : $errors++;
(isset($_GET['world'])) ? $world = $_GET['world'] : $errors++;
//process
if($errors > 0) {
echo 'Errors Detected! Missing querystring get data!';
} else {
echo '<p>Hello received: ' . $hello . '</p>';
echo '<p>World received: ' . $world . '</p>';
//now we can process $hello and $world server side!
}
?>
Important: you should really look into learning some JSON and $_POST requests as they are more secure, faster and you can easily manipulate returned data. I suggest looking at a library like jquery for simplified examples.
I have not tested this code, but it should work.. Let me know if you have questions or this does not answer your question.
Glad to help!
Use AJAX to send data to the server (GET or POST) and store these values in a session variable or cookie on the server
You can use your local/session storage data and populate some hidden inputs, then submit the respective form in an ajax request. To make things cleaner you can use one hidden input and set it's value into a JSON object created from your storage data.
No, javascript runs on the client, php runs on the server.

How to call multiple AJAX functions (to PHP) without repeating code

I have a little script which uses AJAX and PHP to display an image. You can see below that if I call the function mom() it looks in the PHP file index.php?i=mom and displays the image I'm looking for.
But I need the javascript to be lighter as I have 30 images and for each one I have to modify and copy the script below. Is there not a simpler way to have the functions be different and still call a different page?
<script type="text/javascript">
function mom()
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
HandleResponse(xmlHttp.responseText);
}
}
xmlHttp.open("GET", "index.php?i=mom", true);
xmlHttp.send(null);
}
function HandleResponse(response)
{
document.getElementById('mom').innerHTML = response;
}
</script>
My Trigger is this
<a href="#" onclick='mom();' />Mom</a>
<div id='mom'></div>
You could modify your function so it takes a parameter :
// The function receives the value it should pass to the server
function my_func(param)
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
// Pass the received value to the handler
HandleResponse(param, xmlHttp.responseText);
}
}
// Send to the server the value that was passed as a parameter
xmlHttp.open("GET", "index.php?i=" + param, true);
xmlHttp.send(null);
}
And, of course, use that parameter in the second function :
function HandleResponse(param, response)
{
// The handler gets the param too -- and, so, knows where to inject the response
document.getElementById(param).innerHTML = response;
}
And modify your HTML so the function is called with the right parameter :
<!-- for this first call, you'll want the function to work on 'mom' -->
<a href="#" onclick="my_func('mom');" />Mom</a>
<div id='mom'></div>
<!-- for this secondcall, you'll want the function to work on 'blah' -->
<a href="#" onclick="my_func('blah');" />Blah</a>
<div id='blah'></div>
This should work (if I understand correctly)
<script type="text/javascript">
function func(imgName)
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
document.getElementById(imgName).innerHTML =
}
}
xmlHttp.open("GET", "index.php?i=mom", true);
xmlHttp.send(null);
}
</script>
MARTIN's solution will work perfectly.
By the way you should use some javascript framework for Ajax handling like jQuery.
It will make your life easy.
If you are having light weight images you preload the images on your page.
I solved this by making an array of in your case xmlHttp and a global variable, so it increments for each request. Then if you repeatedly make calls to the same thing (eg it returns online users, or, whatever) then you can actually resubmit using the same element of the array too.
Added example code:
To convert it to a reoccuring event, make a copy of these 2, and in the got data call, just resubmit using reget
var req_fifo=Array();
var eleID=Array();
var i=0;
function GetAsyncData(myid,url) {
eleID[i]=myid;
if (window.XMLHttpRequest)
{
req_fifo[i] = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
req_fifo[i] = new ActiveXObject("Microsoft.XMLHTTP");
}
req_fifo[i].abort();
req_fifo[i].onreadystatechange = function(index){ return function() { GotAsyncData(index); }; }(i);
req_fifo[i].open("GET", url, true);
req_fifo[i].send(null);
i++;
}
function GotAsyncData(id) {
if (req_fifo[id].readyState != 4 || req_fifo[id].status != 200) {
return;
}
document.getElementById(eleID[id]).innerHTML=
req_fifo[id].responseText;
req_fifo[id]=null;
eleID[id]=null;
return;
}
function reget(id) {
myid=eleID[id];
url=urlID[id];
req_fifo[id].abort();
req_fifo[id].onreadystatechange = function(index){ return function() { GotAsyncData(index); }; }(id);
req_fifo[id].open("GET", url, true);
req_fifo[id].send(null);
}
The suggestions to parameterize your function are correct and would allow you to avoid repeating code.
the jQuery library is also worth considering. http://jquery.com
If you use jQuery, each ajax call would literally be this easy.
$('#mom').load('/index.php?i=mom');
And you could wrap it up as follows if you'd like, since you say you'll be using it many times (and that you want it done when a link is clicked)
function doAjax(imgForAjax) { $('#'+imgForAjax).load('/index.php&i='+imgForAjax);}
doAjax('mom');
It makes the oft-repeated ajax patterns much simpler, and handles the issues between different browsers just as I presume your getXMLhttp function does.
At the website I linked above you can download the library's single 29kb file so you can use it on your pages with a simple <script src='jquery.min.js'></script> There is also a lot of great documentaiton. jQuery is pretty popular and you'll see it has a lot of questions and stuff on SO. ajax is just one of many things that jQuery library/framework (idk the preferred term) can help with.

[HTML/PHP]: Abort refresh of page

In a Form, I am calling a PHP file if the validation passes. My Form header looks like this:
<form method="POST" action="inst.php" style="margin:0px;"name="form1" onSubmit="return CheckUsername(document.getElementById('username').value);">
</form>
The problem is that even if the validation fails, it shows a blank page in an attempt to open the PHP file, when it must remain on the same page. The PHP file contains code to access the database to check whether the user exists or not.
Is there any way to check the database for value without refreshing the page?
It is very likely that the JavaScript function has an error. The validation function will then not be executed and the form sent (!). Check Firefox's Javascript console for errors, they will appear there even if the page has already reloaded.
You should however never rely on client side validation. I would highly recommend checking in the PHP script as well.
While you should never rely upon client-side verification alone and should definitely treat all data as "dirty" in the PHP, there is another way using JavaScipt that you can prevent the browser from directly posting the form. Rather than setting the form's method and action, simply define its onsubmit function to construct an XmlHttpResponse object, set the method to POST and set data to your form.serialize(), and send the appropriate POST request. Or, if the PHP script will accept GET or REQUEST parameters, you can (after your verification) construct the URL query and simply set window.location to redirect to the PHP page with the appropriate data.
EDIT - Here is my illustration - this uses Prototype's Form.serialize function.
<form id="my_form" onSubmit="return checkUsername();">
Username: <input type="text" name="username" id="username" />
</form>
<script type="text/javascript">
var xhr; // global XMLHttpRequest object
var formElem = $('my_form'); // our form element
function checkUsername() {
var formData = formElem.serialize();
sendPOSTRequest('http://mydomain.com/mypath/myscript.php', formData);
}
function sendPOSTRequest(toURL, sendData) {
xhr = false;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!xhr) {
alert('Cannot create XHR');
return false;
}
xhr.onreadystatechange = handleResponse;
xhr.open('POST', toURL, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-length", sendData.length);
xhr.setRequestHeader("Connection", "close");
xhr.send(sendData);
}
function handleResponse() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var result = xhr.responseText;
// result is now whatever content was returned by the PHP script
// do whatever you want with the result here
// for example, you might have the PHP return 'true' or some such thing, and then
// change window.location, or perhaps if it returns 'false' you put up an alert('No!')
// use your imagination, go nuts
} else {
alert('The script returned an error.');
}
}
}
</script>
There are some more sophisticated ways to create and handle the XMLHttpRequest object. I might post an update later with some pointers.
Once the POST request has been sent then it is up to the browser how it handles the response, but in every browser I have come across it will display the result of the request in some for be it a message saying it recieved a response (200,404, etc), a blank page or whatever, so I'm afraid you will have to reconstruct your page and send it back to the client (complete with invalid entries in the form elements) as a response.
Its a pain, but that's how HTTP works.

Categories