I'm sending the variable like this:
xmlhttp.open("GET","insert-karma.php?pid=<? echo $pid; ?>",true);
The AJAX part doesn't seem to be the problem, if I check the Sript the PHP is echoing the integer correctly. (It displays the url as: insert-karma.php?pid=5). However the PHP isn't getting the variable. (I tried echoing and it does't show anthing)
This is the PHP file:
// Connect to db;
$pid = $_POST['pid'];
$sql="UPDATE Poems SET Karma = Karma + 1 WHERE Pid = '$pid'";
// Disconnect form database;
What am I doing wrong? How do I manage to send $pid to the PHP update-karma.php?
try $pid = $_GET['pid']
or
$pid = $_REQUEST['pid'];
You are sending the variable using GET, so in your php you have to use the $_GET variable
$pid = $_GET["pid"];
Also avoid using your variable directly in your sql query. you will be vulnerable to sql injection.
if using mysql:
$pid = mysql_real_escape_string($_GET["pid"]);
or in case you are passing an integer:
$pid = (int)$_GET["pid"];
first you should not use PHP in you ajax requests it's just make things more complicated and PHP is for server side scripting in the first place
secound , you should use xmlhttp.open("POST","insert-karma....) if u plain to use POST
Third the only important difference (not the only but the important) between POST and Get is :
GET requests can be cached
GET requests can remain in the browser history
GET requests can be bookmarked
GET requests can be distributed & shared
GET requests can be hacked lool
so u cant use Get For unsecured and dangerous action like LOGIN OR ...
POST Can handel too long Data
Post is more secured Cuz it's not gonna be cached or saved in history or bookmarked
u can clearly notice that POST's dont display in the browsers address bar but Get do
'www.anything.com/index.php?bla=bhe'
i hope that i am helping here !! :)
Just a suggestion here since you have already got the answer. Try to use some javascript library to aid you while you are writing your JS code.
I would suggest jquery
And also please read what is the difference in GET, POST requests and when it should be used.
Related
I have a central PHP script I use for handling many requests from my page, using XMLHttpRequest() calls from JavaScript, using the GET method. My server PHP is currently 5.6, and yes, I'm avoiding synchronous calls.
It all works well, however there are cases where I'd prefer NOT to have the request remain in browser history, or even be displayed in the URL. So based on the MDN reference on this call, I thought I could simply switch to the POST method, keeping my existing requests (such as "http://myscript.php?cmd=dothis&data=somedata"). then all I'd have to do is add some code to my PHP script, so I could gather the passed data either way...
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
if(isset($_GET['cmd'])) $cmd = $_GET['cmd'];
if(isset($_GET['data'])) $data = $_GET['data'];
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if(isset($_POST['cmd'])) $cmd = $_POST['cmd'];
if(isset($_POST['data'])) $data = $_POST['data'];
}
Well obviously i was dead wrong. What I found was...
Neither of the variables shown in this example are seen by the script within the $_POST array, when I switch to the POST method.
Switching from the $_POST array to the $_REQUEST array works fine (eg: "if(isset($_REQUEST['cmd'])) $cmd = $_REQUEST['cmd']);" ), BUT....
Just the act of issuing my XMLHttpRequest() calls with the POST method, results in errors like this in my log:
PHP Deprecated: Automatically populating $HTTP_RAW_POST_DATA is
deprecated and will be removed in a future version. To avoid this
warning set 'always_populate_raw_post_data' to '-1' in php.ini and use
the php://input stream instead. in Unknown on line 0
So obviously This is a dead end. Doing my best to research what is going on here, in the PHP manual reference to POST I read this right on top...
$_POST $HTTP_POST_VARS [deprecated]
So if I'm understanding this right, the reason I can only obtain the POST variables using the $_REQUEST array is because my requests are still formatted as if I were still using GET, which (apparently?) is a deprecated method. Therefore, "coaxing" it to work is just moving the problem to the future.
Incidentally, I can see by calling the phpinfo.php on my server that despite the ERROR I see in my logs, "always_populate_raw_post_data" is indeed already set to "-1". So all the "solutions" I've found recommending I "JUST" make this setting in my PHP.INI file do not help.
And even if it DID "hide" the error, doing so seems irrelevant to me. Am I wrong in saying that even if I simply gather my passed PHP vars from the $_REQUEST array when using the POST method, AND figure out a way to suppressing the "deprecated" warnings in my LOG, the whole scheme would still fall apart (and make my POST requests fail), the day I finally migrate to PHP 7.x.?
I apologize for asking here, but I have really tried to search every reference I could find for both doing XMLHttpRequests using POST method, AND the deprecated error messages I get in my logs. There is so much obsolete info out there, I can't find any clear discussion on how to PROPERLY alter or re-format my XMLHttpRequests so that I can use the POST method. In fact, I can't even positively determine whether doing so will be possible beyond PHP.5.6. Any help will be very much appreciated.
PHP made a mistake of naming $_GET and $_POST after the default place that a web browser will put data in an HTML form where the method attribute is set to GET or POST.
$_GET gets data from the query string, even if the request method was POST.
The request body is determined by the argument you pass to send. Data you put in the query string remains in the query string.
const url = 'http://myscript.php'
const form_data = new FormData();
form_data.append("cmd", "dothis");
form_data.append("data", "somedata");
cost xhr = new XMLHttpRequest;
xhr.open("POST", url);
xhr.addEventListener('load', function () { console.log(this.response); });
xhr.send(form_data);
I am sending parameters to a PHP file as a POST request, direct from my browser like :
example.com/
with example.php?CID=1
But not getting the values in the PHP file.
I am sending parameters to a PHP file as a POST request, direct from my browser like
in the php file i am trying to read :
$cid = $_POST["CID"];
$cname = $_POST["CNAME"];
But the local variables are null after executing this.
I also tried doing this :
echo var_dump($_POST);
and it returns :
array(0)
i am hosting this on a paid hosting server, and the configuration allows upto 1000 parameters.
The way you have set this up you are using the get method
$cid = $_GET["CID"];
$cname = $_GET["CNAME"];
If you are wanting to use post then please read the PHP manual
https://www.php.net/manual/en/reserved.variables.post.php
first of all try this PHP "php://input" vs $_POST
php://input
it will solve your issues and let you process developement as workaround - it is very usefull when communicating with pure json not as jason passed into Post field.
next make a check configuration of your server - i had the same problem with nginx and solved it somehow but do not remember how ;)
what i'm trying to do is get a variable to update every 5 seconds doing this:
setInterval(document.getElementById("listeners").innerHTML =
"<?php include('../includes/shoutcaststuff.php');
echo $dnas_data['CURRENTLISTENERS']; ?>",5000);
but what happens is the inner html is set but doesn't update every 5 seconds like it should.
my guess is that the php only executes once, but i have no idea if that's the case or not.
and i'm aware i should make a function to do the stuff inside setInterval... i'll clean up the code once i figure out how to make it work.
thanks in advance.
ok... ajax was 'the best' answer since no more than 2 people would be logged in at a time here so server requests isn't such a big deal.
here's how i got it to work:
function lCount(){
$.get("../includes/shoutcaststuff.php",{Count: "TRUE"}, function(data){
document.getElementById('listeners').innerHTML = data;
});
}
setInterval(lCount,5000);
and added this to the end of the php:
if(isset($_GET["Count"])){
echo $dnas_data['CURRENTLISTENERS'];
}
now it works fine.
thanks for the suggestions guys :)
<?php include('../includes/shoutcaststuff.php');
echo $dnas_data['CURRENTLISTENERS']; ?>
This code only executes once when the page is built. For the rest of the times this javascript is called whatever is first echoed will be the value.
Instead of using a static value here, you are going to need to use an ajax request (or a websocket if you want to use html5). The request will then hit your server once every 5 seconds. Keep in mind that this can cause undue load on your server.
Ratchet is a commonly used PHP WebSocket implementation that allows for data to be sent to the client using push technology. This is probably more preferable than using your polling approach.
PHP code is run on the server generating the HTML/JS. Use ajax if you need to run php code once the page has loaded.
Take a look at this for example;
Using this:
setInterval(document.getElementById("listeners").innerHTML =
"<?php echo "1";?>",5000);
Will output this to the browser:
setInterval(document.getElementById("listeners").innerHTML =
"1",5000);
$name="document.write(get_name());";
echo $n= $name; // Here it prints name also (correct one)
$sql=mysql_query("INSERT INTO tab1 (name,visited_time) values ('$n',NOW())");
Ideally this should print got name from the function but it inserting
document.write(get_name());
Note : get_name function is returning the value correctly. and function is mandatory. Only the problem is it inserting document.write(get_name()); instead it's value.
It looks like you missed an important chapter about PHP / JS programming...
PHP code is executed server side.
JavaScript code is executed client side.
Steps to solve this are:
whenever you need this query to be executed, you need to make a call from JavaScript to PHP and pass the variables to the PHP. You can do this with an asynchronous call with jquery for example:
// JS, executed on client side
var name = get_name(); // this javascript function must exist
$.get("path/to/your/page.php", {"name":name});
More info about jQuery here: http://api.jquery.com/jQuery.get/
then, in PHP, you get this value from the global $_GET and you can use it:
// php code that will be executed when path/to/your/page.php will be called
$name = $_GET['name'];
$sql = "INSERT INTO tab1 (name,visited_time) values ('" . $name . "',NOW())";
$rs= mysql_query($sql);
And that will do what you expect.
You can use this code to implement the logic, but it requires lots of improvements then:
It is highly unsecured and leaves room for the most simple SQL injection attack. You must "quote" all values you use in your SQL queries (you can't trust any data coming from the client)
$_GET['name'] may not exist or contain what you except so you need to use function like isset and to do more tests after to verify that nobody is trying to hack your variable
you should POST method and not GET since this HTTP call will result in changing the state of the datbase
mysql_query is deprecated: http://us2.php.net/manual/en/function.mysql-query.php you should use mysqli_query or PDO...
I'm not gonna talk about all these topics, they are highly covered on the web and a simple search your favorite search engine will give all the information you need.
Note: I wrote that "JavaScript code is executed client side". This is not exactly true since it is possible to build a server in JavaScript but this is far far far away from you concern and that wouldn't even change the fact that you still need to send the value from the client to the server with the kind of logic I just described.
I'm pretty new to PHP but trying to find my way which has worked quite well up till now.
Problem is the following: I have a website with 2 links. Both should redirect to the same second website but depending on the link clicked, some values should change. I was trying to use a PHP session for this.
Here is the code up to now:
Link 1:
<a href="<? echo $link ?>" class="helsinki" onclick="<? $_SESSION['clicked']= "helsinki"; ?>"^^Helsinki^^</a>
Link 2:
^^Seattle^^
Now if I try to read which link was clicked on the next side like this:
<? if(isset($_SESSION['clicked']))
echo "clicked ". $_SESSION['clicked'];
?>
I always see "Seattle", Helsinki never appears although (I thought) I input Seattle if the Seattle link is clicked. Apparently it's not like that... Can anyone help me here?
This is because PHP code is server side, and thus executed at the time of the page request. So $_SESSION['clicked'] is set to helsinki then reset to seattle at the time your first page loads. You may want to use $_GET variables instead of $_SESSION variables.
Wait wait wait a second: PHP is "server-side", javascript is "client-side". That means you will ALWAYS execute PHP before javascript.
What you are trying to achieve can be simply done with a GET variable:
^^Seattle^^
^^Helsinki^^
And than in the second site you can get the value of our parameter:
$city = $_GET['city'];
Not sure if this is useful, but you could create a "redirector". It takes the user to a server side page that will redirect them to the final page and at the same time change the session.
The page:
...
...
The code for redirector.php:
<?php
session_start();
// determine where to redirect user (could be done with database or array of options)
switch ($_GET['link']) {
case 'helsinki':
header('Location: /link/to/helsinki');
break;
case 'seattle':
header('Location: /link/to/seattle');
break;
default:
return;
}
$_SESSION['clicked'] = $_GET['link'];
You're mixing up Javascript and PHP.
PHP is server side, that means that all PHP code is parsed and executed on the server side, and then is sent to the client.
So if you write
line #1: ^^Helsinki^^
and then
line #2: ^^Seattle^^
the value of $_SESSION['clicked'] is always first "Helsinki" (line #1), but then immediately overwritten by "Seattle" (on line #2).
In order to achieve what you want the script to achieve, is, for example, as follows:
^^Helsinki^^
^^Seattle^^
and then catch the sent variables from the PHP variable $_GET:
if (isset($_GET['location'])) {
if ($_GET['location'] == "helsinki") {
// Whatever
}
elseif ($_GET['location'] == "seattle") {
// You want
}
}
"^^Helsinki^^
"^^Seattle^^
and use $_GET['location'] at the other page to check weather it is helsinki or seattle.
$link should be the same for both links.
Also you can't mix PHP (server-side) with Javascript (client-side). Look it up for why that is.
You cannot write PHP code in the onclick event. If you want to do it like that, you should use Javascript/AJAX. Even if you do it like that, you won't still get the result as you desire, since AJAX request will delay some seconds.
I think the right way to do this kind of thing is like below:
Helsinki"
and this is the change_city.php:
<?php
$_SESSION["clicked"] = $_GET["city"];
?>
if you want to still use the $link, then you just put this above code top of your PHP file.