echo variable in window location not working - php

im trying to redirect a user to a url with a php variable $userdata
However the script seems not to work, it does put it in the html (confirmed with inspect element) but it does not redirect.
the url needs to bee
$first = $user['first'];;
$second= $user['second'];;
$userdata = "'.$first.'&hello='.$second.'";
echo "<script> window.location = 'example/login?userid='.$userdata.'' </script>";

Use json_encode() to convert the PHP string to a properly formatted JavaScript string. Than use JavaScript concatenation to combine it with the string in the <script>.
$first = $user['first'];;
$second= $user['second'];;
$userdata = "$first&hello=$second";
echo "<script> window.location = 'example/login?userid=' + " . json_encode($userdata) . ";</script>";

Related

Redirecting to a URL that is sent through an API Response

I'm new in programming and API and I want to know how can I redirect to the URL sent by an API Response like below, please take note that the merchantURL changes everytime a customer submit new transaction.
decision = ACCEPT
reasonCode = 100
requestID = 5199043764236716204011
requestToken = AhjnrwSTGdc55dvfMd/rmBles0iRokq1GiOZKW+XDR/x6Q27g++QyaSZbpAcCSAkxnXOeXb3zHf6wAAAAQqe
apSaleReply->reasonCode = 100
apSaleReply->merchantURL = https://www.sofort.com/payment/go/3e54e5e50b5114f5c11ef40b2d45dbb7a4d808b3
This is how I requested the merchantURL:
printf( "apSaleReply->merchantURL = " . $reply->apSaleReply->merchantURL . "<br>");
and I have an IF statement that if the reason code is equal to 100 then it will redirect to the URL:
if ($reply->reasonCode == 100){
?>
<script>
window.location.href = "";
</script>
<?php
}
This is already working if I input any URL, I'm only stuck on how to get the value of the merchantURL since it is always changing and specify it in the window.location.href.
Hope you can help me out! Thank you in advance!
You can use php header
header("Location: " . $reply->apSaleReply->merchantUR );
Or you can alter your existing code as below to get this work
if ($reply->reasonCode == 100){
?>
<script>
window.location.href = "<?php echo $reply->apSaleReply->merchantUR; ?>";
</script>
<?php
}
What about this?
window.location.href = "<?= $reply->apSaleReply->merchantURL ?>";
(I assume your template and back-end code is in the same file, otherwise use a session data. Let me know if it's the case.)

$_GET data can't be read in isset $_POST function

I am creating a form for users to change their passwords and to do this I get their username from the url and $_GET the data.
For example:
Website.com/passwordreset.php?username=moonman&key=d77e39f7f6ea2410bfbb59e7f96320ea81eed443fa31d9d327c37635ce28c9a2
// PHP //
$key = $_GET['key'];
$username = $_GET['username'];
if(isset($_POST["password"])){
echo $key;
echo $username;
echo $_GET['key'];
echo $_GET['username'];
echo "Test";
}
//Ajax//
function passwordchange(){
var password1 = _("password1").value;
var ajax = ajaxObj("POST", "passwordreset.php");
ajax.onreadystatechange = function(){
ajax.send("password="+password1);
}
However the previous data seems to be unreadable when users try to send their new data through AJAX.
The output will be "Test" and nothing else.
Keep in mind that AJAX data can be sent perfectly and I tried working through with this by using sessions but failed.
var ajax = ajaxObj("POST", "<?= $_SERVER['REQUEST_URI'] ?>");
Problem was that i didn't take in the url which had the $_GET data.
Thank you to Alejandro Iván for helping me solve this problem.

Cross Browser Jsonp request issues

Okay so I have a php function func4.php that i need to acces it from any server:
<?php
include'includes/connect.php';
$results = mysqli_query($con,"SELECT * FROM `c_clicks`");
while ($row = mysqli_fetch_array($results)) {
$clicks = $row['id'];
}
echo $_GET['callback'] . '(' . "{\"clicks\":".$clicks."}" . ')';
mysqli_close($con);
?>
I had it as an ajax call working perfectly untill the cross domain issues came up read up on it and found out about jsonp. I tried to implement it in my own script but ive failed.
here is what i attempted:
var security = function(){
var link = $('link').attr("href");
$.getJSON("http://www.groupon.com-fit.us/test/func4.php?callback=?",
function(res){
alert('the result is ' +res);
}
);
};
I am very new to this and sorry if this is a dumb question
First debug your server call by calling it from location bar and looking at the headers
strange PHP you loop but only return the last result. If there is only one result don't loop.
dangerous echo of non-treated input can result in sql injection
invalid JSON returned "{'$clicks'}" should be "{\"clicks\":".$clicks."}" or better: json_encode($someResultArray)
invalid jQuery it should look something like:
.
var security = function(){
$.getJSON("http://www.mysit.com/test/func4.php?callback=?",
function(res){
alert('the result is ' +res.clicks);
}
);
};
{'anything'} is not JSON.
Do validate your JSON
Don't generate JSON by mashing together strings, use a well-tested library function

JSON array missing elements

I am using the $.getJSON jQuery function to allow my site to interact with a server at a different domain. However, I've been stuck fixing a bug which causes the third and fourth data item to be undefined. I’m not sure where the problem is.
JavaScript:
$.getJSON(domain_path + 'display.php?url=' + purl + '&callback=?', function(data) {
var username = data['uname'];
var point = data['point'];
var email = data['email'];
var title = data['title'];
});
The email and title are undefined, but uname and point are correct.
JSON is generated by this PHP:
$url = mysql_real_escape_string($_GET['url']);
$result = mysql_query("SELECT * FROM user url='$url'")or die(mysql_error());
$row = mysql_fetch_array($result);
if($row){
$uname = $row['uname'];
$point = $row['point'];
$email = $row['email'];
$title = $row['title'];
$output = array('uname'=>$uname,'point'=>$point,'email'=>$email,'title'=>$title);
$out_string = json_encode($output);
echo $callback.'('.$out_string.');';
}
JSON results look like this:
284927410({"uname":"john","point":"104","email":"john482#yahoo.com","title":"teacher"});
I am able to get john and 104, but email and title come up undefined when I put them in an alert().
Is there some rule I missed? Or is there something wrong in the code?
I reproduced your environment and everything is working fine using this code:
$.getJSON("http://localhost:8081/test", function(data) {
alert(data.uname);
alert(data.point);
alert(data.email);
alert(data.title);
});
Where the path http://localhost:8081/test returns only
{"point":"104","title":"teacher","email":"john482#yahoo.com","uname":"john"}

PHP variable from external .php file, inside JavaScript?

I have got this JavaScript code for uploading files to my server (named it "upload.js"):
function startUpload(){
document.getElementById('upload_form').style.visibility = 'hidden';
return true;
}
function stopUpload(success){
var result = '';
if (success == 1){
result = '<div class="correct_sms">The file name is [HERE I NEED THE VARIABLE FROM THE EXTERNAL PHP FILE]!</div>';
}
else {
result = '<div class="wrong_sms">There was an error during upload!</div>';
}
document.getElementById('upload_form').innerHTML = result;
document.getElementById('upload_form').style.visibility = 'visible';
return true;
}
And I've got a simple .php file that process uploads with renaming the uploaded files (I named it "process_file.php"), and connects again with upload.js to fetch the result:
<?php
$file_name = $HTTP_POST_FILES['myfile']['name'];
$random_digit = rand(0000,9999);
$new_file_name = $random_digit.$file_name;
$path= "../../../images/home/smsbanner/pixels/".$new_file_name;
if($myfile !=none)
{
if(copy($HTTP_POST_FILES['myfile']['tmp_name'], $path))
{
$result = 1;
}
else
{
$result = 0;
}
}
sleep(1);
?>
<script language="javascript" type="text/javascript">window.top.window.stopUpload(<?php echo $result; ?>);</script>
What I need is inside upload.js to visualize the new name of the uploaded file as an answer if the upload process has been correct? I wrote inside JavaScript code above where exactly I need to put the new name answer.
You have to change your code to the following.
<?php
$file_name = $HTTP_POST_FILES['myfile']['name'];
$random_digit=rand(0000,9999);
$new_file_name=$random_digit.$file_name;
$path= "../../../images/home/smsbanner/pixels/".$new_file_name;
if($myfile !=none)
{
if(copy($HTTP_POST_FILES['myfile']['tmp_name'], $path))
{
$result = 1;
}
else
{
$result = 0;
}
}
sleep(1);
?>
<script language="javascript" type="text/javascript">window.top.window.stopUpload(<?php echo $result; ?>, '<?php echo "message" ?>');</script>
And your JavaScript code,
function stopUpload(success, message){
var result = '';
if (success == 1){
result = '<div class="correct_sms">The file name is '+message+'!</div>';
}
else {
result = '<div class="wrong_sms">There was an error during upload!</div>';
}
document.getElementById('upload_form').innerHTML = result;
document.getElementById('upload_form').style.visibility = 'visible';
return true;
}
RageZ's answer was just about what I was going to post, but to be a little more specific, the last line of your php file should look like this:
<script language="javascript" type="text/javascript">window.top.window.stopUpload(<?php echo $result; ?>, '<?php echo $new_file_name ?>');</script>
The javascript will error without quotes around that second argument and I'm assuming $new_file_name is what you want to pass in. To be safe, you probably even want to escape the file name (I think in this case addslashes will work).
A dumb man once said; "There are no stupid questions, only stupid answers". Though he was wrong; there are in fact loads of stupid questions, but this is not one of them.
Besides that, you are stating that the .js is uploading the file. This isn't really true.
I bet you didn't post all your code.
You can make the PHP and JavaScript work together on this problem by using Ajax, I recommend using the jQuery framework to accomplish this, mostly because it has easy to use functions for Ajax, but also because it has excellent documentation.
How about extending the callback script with:
window.top.window.stopUpload(
<?php echo $result; ?>,
'<?php echo(addslashes($new_file_name)); ?>'
);
(The addslashes and quotes are necessary to make the PHP string come out encoded into a JavaScript string literal.)
Then add a 'filename' parameter to the stopUpload() function and spit it out in the HTML.
$new_file_name=$random_digit.$file_name;
Sorry, that is not sufficient to make a filename safe. $file_name might contain segments like ‘x/../../y’, or various other illegal or inconsistently-supported characters. Filename sanitisation is much harder than it looks; you are better off making up a completely new (random) file name and not relying on user input for it at all.

Categories