Php, Jquery - Post variable to other page with leaving the page - php

I'm working on a complex project which needs nice variable posting between pages without post or get. I made it with get, before that I used post in php, but then I started to use jquery which has got better ways to do things. I know how to pass variables between two pages without leaving the page:
visible function blahblah (id){
$.ajax({
type: "POST",
url: "blahblah.php",
data: $(id).serialize(),
success: function(data){
$('#results').html(data);
}
});
}
I always show results in a div, but the one I want to achieve is different. I need to pass a variable WITH leaving the page, but without using php post or get. I did search for it, but I wasn't successful. Can you help me out in this, if it's possible? Thank you for your help.

If you're worried about losing the "go back" function I assume this is because of the annoying warning that appears when you go back to a page that has posted data? To get around that you can try (as others have stated):
POST your form normally to the page
Save variables in $_SESSION[]
$_SESSION['var1'] = $_POST['var1'];
Change the header to refresh the page:
header('Location: ' . $_SEVER['SCRIPT_NAME']);
exit;
That way no one sees what you've posted by GET and you avoid the annoying "Resubmit your posted variables" message.

I am not sure, if I got your question perfectly right..I think you want to:
Send your data to a page using POST/GET
Redirect to another page. Use header function for this.
But, when you say, you don't want to use POST/GET, I really get confused! How can you communicate with your server then? Setting everything to session, can never be a good solution.

Related

Hide var data on ajax

I am making AJAX like function but I have problem that bad user can change the value into any other current user. So, how can I prevent this thing?
$live = 'user1';
$fol = 'user2';
function ajax(like){
var data = 'like='+like+'&CURRENTUSER=<?php echo $live; ?>&TOFOLLOW=<?php echo $fol; ?>';
$.ajax( {
type: 'POST',
url: 'ajax.php',
data: data,
success: function(e) {
$('#success').html(e);
}
});
}
Also I want to move this ajax function into ajax.js file, but i am have problem in getting the value $live and $fol of users because echo $live doesn't work on .js.
So, is there any way to do this like Facebook, Twitter AJAX function does ?
This solution works for apache web-server. For interpreting JS file using php, add this line to your .htaccess file:
AddType application/x-httpd-php .js
And put your script inside ajax.js. One other way is using rewrite URL:
RewriteEngine On
RewriteRule ^ajax.js$ ajax.js.php [L]
And put your scripts inside ajax.js.php file. Of course, all these are if you want to show your URL as JS file.
at the top of your ajax.js or ajax.js.php file, before any kind of output, put this:
header('Content-Type: application/javascript');
I have problem that bad user can change the value into any other current user. So, how can I prevent this thing?
Of course you can not do that at all.
HTTP is a stateless protocol – so each and every request that reaches your server is to be mistrusted, period.
You have to check server-side whether the requesting client is authorized to request/perform whatever action it is he wants to trigger – f.e. by checking that the user id that is passed as the “current” user against the session where you stored your login information. (So when you have the id of the current user stored in there, then there’s no need to actually send it from the client any more in the first place.)
This is one of the most basic security principles of any web application – don’t trust any incoming request, until you have verified that the client has the appropriate authorization. So asking for how to “hide” any data that is send from the client is completely the wrong question – that would be what’s called “security by obscurity”, and that does not work.
There can be many solutions for such problem.
Add one of follow user in session before page load so even you dont need to send data in ajax. Just need to confirm action and all data will be taken from session. Hence hackers cant modify users.(This is how i solved the problem in my project)
You can build an function like encode() & decode(). when you are using data in file encode() it first.Then at code end use decode() to extract the info. Since if invalid data came out mean some one has tempered and you will not execute that action. But you have to create such encode() & decode() yourself.
$live = encode(user1);
At php end
$real_live = decode($live);
3. Ajax request to when start php execution you can have a function like
check_auth(user1,user2);
So even if some one used bad data your security rules can filter them.
Hope you can use any of them.

Optional Form - How do I remove the "this page has used data..." message? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
I am confused about PHP Post/Redirect/Get
I have a form on a page, so I get the "this page has used data, are you sure you want to refresh" message when I reload the page.
I looked into the HTTP-303 response code, which gets rid of the message (I'm on Chrome btw) until I submit the form once, and then it starts bugging me again.
Basically, I have an optional "contact me" form, that shouldn't throw a prompt if the page is refreshed. I don't think/see why I should need a separate page for submission for a short form like this. Can anyone help me out?
Your best option is to use Ajax. That way you don't need to reload.
I usually use it with JQuery.
So you end up with something like:
function send_message(vMessage,vWho) {
$.ajax({
url:"messageSender.php",
data:{message:vMessage,from:vWho},
type:"POST",
success:function(result) {
// DO SOMETHING HERE, LIKE AN ALERT
}
});
}
Final Solution:
How to prevent form resubmission, on the same page
You should have the action="something" tag. Required in HTML5
Check if a form was submitted. If you don't, and have a header('Location: ...') it will be like an infinite loop (crap out). So something like if (isset($_POST['some_submit_btn'])) {
Do you processing logic
Do header('Location: same_page') (eg: header('Location: ' . $_SERVER['PHP_SELF'])) and exit
Your page can now refresh regularly, even after submitting a form. The redirect clears the POST request or whatever.
Others have pointed out Ajax is a simpler solution. I've accepted it as an answer, but in case anyone wants to do it this way I put this for reference.
Note: If you want to pass data between the two pages/refreshes, you have to pass it through sessions or cookies (I prefer sessions). I don't think there's a "clean" workaround
You need to redirect after you saved the form data. It can be done on the same page, it's not a problem, you just need to issue a GET request instead of a POST.

javascript post to .php file one server does not work - manual entry of URL in browser to same .php works

i had some issues with understanding how to get javascript (client) variables transferred so they were acessible from php (serverside) as session : get an iframe's "src" value in PHP?
Now im in a situation where i use firebug to try to debug whats going on, but it just doesnt make sense :
i have this function to update an iframe and i want to pass on the page that that iframe is displaying :
function frameclick(pageurl)
{
$.post("session_write.php?",
{
frameurl : pageurl
}
$("#iFrame1").attr('src', pageurl);
console.log ('<?php echo "logout:".$langpath.$_SESSION['frameurl'];?>');
}
pageurl is ex. "/lang/en/new.htm" - and if i inspect it with firebug i also can see it says that it passes it correctly ( also with conversion of /).
my script serverside that its posted to is like this :
#session_write.php
<?php
session_start();
print_r($_GET['frameurl']);
if (isset($_GET['frameurl']))
{
$_SESSION['frameurl'] = $_GET['frameurl'];
print_r($_SESSION);
}
?>
Posting to that php script on the server will fail via the javascropt - $_SESSION['frameurl'] will be '', but if i ex. do it manually like this :
(http):
//localhost/phpmenu/session_write.php?frameurl=lang%2Fen%2Fnew.htm
then it will be correctly set in the $_SESSION["frameurl"] variable.
I simply cannot understand whats different between doing the javascript post and doing it manually in the browser and why its causing me this problem ?
anyone with an idea ? thanks
You are using .post, which executes a POST request, but when you type in the URL in the address bar, that is a GET request.
$_GET retrieves any params passed through GET, while $_POST retrieves any params passed through POST. So if you use .post with Javascript but try to retrieve with $_GET in PHP, it wouldn't work.
When you POST variables to a PHP file, $_GET is not set. Use $_POST['frameurl'] instead. Also, it looks like you're missing a close paren in frameclick to end the post call.
You are passing data via a
POST request and retrieving for all the GET requests. Use $_POST instead. You may also be interested in $_REQUEST

Obtain actual browser URL in PHP

I need to retrieve the actual URL that the user see's in their browser. I have an Ajax request running at page load. Hence, the regular $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"] expression returns the request URL of the Ajax request instead of the actual URL in the browser.
Any idea how to get this?
You could pass it up from javascript in your ajax request, using window.location.href.
Also, it's likely that $_SERVER['HTTP_REFERER'] will contain the browser's current location.
You could also try using $_SERVER['HTTP_REFERER'];. This might work, not 100% sure though.
You can't do that with server-side code, as there is no server-side variable that refers to what the client sees. The only thing you CAN see (and then again, it depends on the browser the user's using, some don't pass this info) is the HTTP_REFERRER variable. This however, is only set when a page calls another, not when users first access your site.
See this for more details.
A possible solution however, might be to use javascript function to send the browser's top URL to the server using an AJAX query, and to fire it client-side whenever a user loads the pages) you want to get this info for.
Edit: Damn, too slow, already answered!
Pass a hidden input that has the browser value set with your ajax request. Unless someone is being malicious, it should suffice.
If you do an Ajax-request, you could pass the address available through Javascripts window.location.href variable as a POST-variable with the request.
With jQuery it would be something like:
$.ajax({
url: 'your-url.php',
type: "POST",
data: { url: window.location.href },
success: function (data) {
// Do something on success
}
});
With such a request you could access the URL on the server-side with a simple:
<?php
$url = $_POST["url"];
?>
Actual Website Link in php
<?php
echo $actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
?>
Server-side languages can't see what happens after they've rendered and outputted the page.

access post vars JS or PHP?

I am using jquery to post vars to a php script.
Is it possible to access these vars once the script has posted? If I post the data to the php script, is the only way to access it in the html/js that i posted it from, to send it back from the php script as json?
I cant seem to do it in JS, but even php will not work?, Sorry correction i can access the post vars in the php page, but not in the html/js page i posted from
Any ideas how to access posted vars from the page thats doing the posting?
update: yep to be a bit clearer, i am using a html page with javascript to post to a php page, i would like to access the posted vars in the html javascript page. I tried outputting $.post and $.ajax and these just show a long function.
Cheers
Ke
How are you submitting your elements to php page? If you are doing everything fine and using ajax (see jquery post method) for example, you can access the php variables normally with $_POST['var_name'].
Make sure that:
Your form method type is set to POST
Your ajax request goes successful
You have specified the correct path to your server side script
In PHP, the data should be accessible through the $_POST array, just like if you posted to the script using a form (whether you make an AJAX request or a normal request through your browser, the server behaves the same). If they're not there, perhaps you actually sent your data by GET instead (you could check $_REQUEST, but it's better, and more secure, to know what method your data will be coming in), or else your AJAX request failed.
I don't recommend using $_REQUEST to post something back to your site. If someone changes their $_REQUEST vars on you, then you have an opening for cross site scripting.
Push all your vars to $_SESSION and post them as you see fit but only after they have been purified. That way even if you make some modifications to them after the fact you can rely on the source, which is in the $_SESSION. However if you are trying to perform actions after a page has executed you are straying outside the boundaries of PHP's limitations. People do it all the time with things like Jquery but it doesn't make it right.
Warning: if you allow accessing and process of vars after PHP has finished printing the page, then you run the risk of enabling attacks on your code.
I assume that you are using $.ajax or $.post to do this.
Just keep your data in local variables. There i sno reason why you should lose the posted data, or your php not being able to access it.
If you post code, maybe someone can help better.
In your php function, you can use this:
function foo() {
//do something
echo json_encode($var);
}
I use .ajax, use dataType: "json". The success attribute would be:
$.ajax(
{
url: 'ajaxfile.php',
type: "POST",
data: ($("#myForm").serialize()),
dataType: "json",
success: function(data)
{
//Insert your logic to handle the vars from php
}
});

Categories