JS counter write to database - javascript

Is there any way I can use this JS second counter, to write to mysql:
var counter = 0;
setInterval(function () {
++counter;
}, 1000);
Can I export it as a variable and then use that variable to write to mysql?
What I'm attempting to do is save the time the user was on the page.
Is this even possible?

To help solve your ajax part (need jquery):
$.ajax({
type:'POST',
url: "yourfile.php",
data:{
"foo": filename // to add more variables you add on the spot after filename but remember the last one variable you send shouldn't have a comma
}
});
on the receiving end (php):
<?php
$filename = $_POST["foo"];
?>
basically ajax is used to send data to a php script.
Javascript is a language that is used in client side and can't write to MYsql. The code above will help you send data to your script. Your php script will run once it recieves the data through AJAX

You would need to write a bit of back-end php to handle ajax query from your front-end javascript.
Your JS may look like this:
function ajaxRequest(data) {
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open("POST", "path/to/back-end.php", true);
xmlHttp.timeout = 1000;
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) { //DONE
//success
console.log("Successfully sent to back-end.php");
}
};
xmlHttp.send(data);
}
You can refer to http://www.w3schools.com/ajax/default.asp for more information.
Then your php will retrieve the body of this POST request and insert it to mysql database accordingly.

Related

How to use ajax for php in the same page?

Hello friends i want use ajax on same php page. But problem is i can use ajax on different pages but not in same page. I saw people accomplished it with jquery but i dont wanna use jquery. Thanks-
<?php
$gg = $_POST['day'];
echo 'today is '.$gg;
?>
<html>
<head>
<script>
function clickMe(){
// Create our XMLHttpRequest object
var req = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "example.php";
var dayName = document.getElementById("dayName").innerText;
var vars = "day="+dayName;
req.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
req.onreadystatechange = function() {
if(req.readyState == 4 && req.status == 200) {
let return_data = req.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
req.send(vars); // Actually execute the request
</script>
</head>
<body>
<h2>Ajax Post to PHP and Get Return Data</h2>
<p id="dayName">saturday</p>
<button onclick="clickMe()">btn</button>
<br><br>
<div id="status"></div>
</body>
</html>
First of all in your php code you are getting input via $_GET and in your code you are sending a POST request which is counter intuitive. What you can do is when certain parameters are passed either through query string or request body with a post request, you can write your desired output and call die() to not display the rest of it which will interfere with the response you get. I don't see a real reason to do so in the same file but, here's an example using query string:
<?php
if(isset($_GET['day'])) {
die('Today is ' . htmlspecialchars($_GET['day']));
}
?>
Then in your javascript code make sure you send a valid request according to your needs.
It's not a good idea to use the same page to print html and do some php stuff. But, if you really want to do so, with javascript you can send another var like ajax=1 and change you php code :
<?php
if(isset($_POST['ajax'])) {
echo 'today is '.$_POST['day'];
exit;
}
?>

Reading JavaScript Variables in PHP

I am looking for a way to either read an image src in PHP or read a JavaScript variable in PHP.
The plan:
I have a webcam script in JavaScript that takes an image using the base64 Canvas method, but I need it to update a MySQL record using PHP.
After trying many methods; cookies, submit forms, ajax. I decided that making a post here was the best idea.
(!) Use with caution. This is a proof of concept. In PHP you should never just accept and compute client-side data without checking it for malicious code and sanitizing the input. (!)
You could send it to PHP using AJAX by putting your base64-source into formData.
Javascript:
// ajax.js
var xhr = new XMLHttpRequest(); // initialize a new XHR
var formData = new FormData(); // initialize form data
var myFile = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASwAAACWCAYAAABkW7XSAAAEaElEQVR4Xu3UgQkAMAwCwXb/oS10i4fLBHIG77YdR4AAgYDANViBlkQkQOALGCyPQIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBE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oAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiDwAIGUVl1ZhH69AAAAAElFTkSuQmCC';
xhr.open('POST', '/requestHandler.php') // init your request
xhr.onreadystatechange = function () {
// check if the server was able to compute the XHR
if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
// handle the response
console.log(xhr.responseText) // log the PHP output
}
}
// a form data element needs a descriptor/name and a value.
formData.append('myfile', myFile);
xhr.send(formData); // send your xhr to the server
PHP:
// requestHandler.php
<?php
if('$_POST') {
echo $_POST['myfile']; // this is your image source
}
Further information:
XMLHttpRequest
FormData
PHP $_POST

How can I access my Javascript Variables in PHP?

I have a file called lightstatuspage.php and within it, I have HTML, JavaScript and PHP code. I have used some variables within the JavaScript part of the code and I am trying to send these variables to the server by passing them to the PHP part of the code. However, this is not working.
I am using $.post("lightstatuspage.php", slider_val); and then in the PHP part, I am calling the variable by doing $_GET['rangeslider_val'];.
What am I doing wrong and what can I do differently to get the variable from JavaScript and send it to the server?
function show_value(x)
{
document.getElementById("slider_value").innerHTML=x;
event.preventDefault();
var slider_val = x;
var query = new Parse.Query(Post);
query.first({
success: function(objects){
objects.set("slider_val", slider_val);
objects.setACL(new Parse.ACL(Parse.User.current()));
return objects.save();
window.location.href = "lightstatuspage.php?rangeslider_val=" + slider_val;
}
})
}
The PHP code is:
<?php
$_GET['rangeslider_val'];
print($rangeslider_val);
?>
First Add Jquery
<script src='https://code.jquery.com/jquery-1.11.3.min.js'></script>
to the end of page before closing body tag.
To send Javascript variable to PHP. the best way is to use Ajax. and add the following code to your javascript.
Do not forget that the below code should be on an event. For example on a button click or something like that
$( document ).ready(function() {
var x = $('#input1').val();
//or var x= 15;
$.post("lightstatuspage.php",
{
'rangeslider_val': x
},
function(data, status){
//alert("Data: " + data + "\nStatus: " + status);
// you can show alert or not
});
});
and in php, you can use:
$value = $_POST['field1'];
now your variable is in $value in php.
P.S:
Backend Page and HTML page should be on same domain or you have to check Cross-Origin Resource Sharing
Second Solution
as the User accepted this solution here would be the code:
$.get("lightstatuspage.php?rangeslider_val=" + slider_val,function(res) {
console.log(res);
});
the second way is only the difference between POST and GET method
Third Solution
if you don't want to use Jquery in your project and you need pure javascript you can use below code
var str = "Send me to PHP";
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
console.log(xmlhttp.responseText);
}
};
xmlhttp.open("GET", "lightstatuspage.php?rangeslider_val=" + str, true);
xmlhttp.send();
Change the order of the last 2 lines of your JS function. You are returning from the function before changing the page's location.
you forgot to store variable on print
<?php
$rangeslider_val = $_GET['rangeslider_val'];
print($rangeslider_val);
?>
You call $_GET but you don't assign the value to the variable $rangeslider_val in PHP and you are returning in JavaScript before calling the PHP script. Also you mentioned that you want to use $.post from clentside if you do it this way you have to use PHP $_POST to get it from there.

I need a hashtag value from the url in php

I need to get the text behind the hashtag in the url (http://www.example.com/#TEXT) so i can use it in a php script. I know that I have to gather the text using javascript then save it as a cookie or something like that. The only problem is that I'm not good at javascript and I have tried but failed.
How can i do this the easiest way?
Here is one thing i have tried:
<script>
var query = window.location.hash;
document.cookies = 'anchor=' + query[1];
<?php if (!$_COOKIE['anchor']) : ?>
window.location.reload();
<?php endif; ?>
<?php
echo $_COOKIE['anchor'];
?>
Most sites that use the fragment like this (such as Facebook) will use JavaScript AJAX calls, depending on location.hash, to send its request to the server. Try that!
var xhr = new XMLHttpRequest();
xhr.open("GET","something.php?hash="+location.hash.substr(1),true);
xhr.onreadystatechange = function() {
if( this.readyState == 4 && this.status == 200) {
// do something with this.responseText
}
};
xhr.send();
The hash part of the URL is not sent to the server, so you need to do so yourself.
The cookies set by the client too are not sent to the server either; the client just remembers them when it talks to the server.
This means that you have to retrieve in Javascript, as you already did, and make an explicit call.
// Example in jQuery
jQuery.ajax({
type: "POST",
url: "/path/to/php/script.php",
data: {
hash: window.location.hash
}
});
Then in the script.php you receive a $_POST['hash'] variable and can store it in the session. But remember that when you do, the sending page has already been loaded and is "stopped". If you want to trigger a reload, you need to send back some kind of response and react to it in jQuery's return function.
You can't. hashtags don't fly to the server. that's why MEGA site is still alive. hashes live only in the browser.

Using AJAX to access to the Twitter API

I'm thinking about adding some twitter functions in my web-application, so I started doing some tests. I checked the way to call the search twitter URL (more info in: http://dev.twitter.com/doc/get/search) in order to get tweets that contains the searched word/sentence. I realized that you can do it in php just getting the JSON file that the search URL returns with the file_get_contents() function. Also you can do it directly in JavaScript creating a script object, appending it to the body and use the callback parameter of the search URL to process the data.
Different ways to do, but that's the way I finally did it:
MAIN HTML FILE:
<title>Twitter API JSON</title>
<script type="text/javascript">
//function that created the AJAX object
function newAjax(){
var xmlhttp=false;
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}
//function that search the tweets containing an specific word/sentence
function gettweets(){
ajax = newAjax();
//ajax call to a php file that will search the tweets
ajax.open( 'GET', 'getsearch.php', true);
// Process the data when the ajax object changes its state
ajax.onreadystatechange = function() {
if( ajax.readyState == 4 ) {
if ( ajax.status ==200 ) { //no problem has been detected
res = ajax.responseText;
//use eval to format the data
searchres = eval("(" + res + ")");
resdiv = document.getElementById("result");
//insert the first 10 items(user and tweet text) in the div
for(i=0;i<10;i++){
resdiv.innerHTML += searchres.results[i].from_user+' says:<BR>'+searchres.results[i].text+'<BR><BR>';
}
}
}
}
ajax.send(null);
} //end gettweets function
</script>
#search_word Tweets
<input type="button" onclick="gettweets();"value="search" />
<div id="result">
<BR>
</div>
</html>
PHP WHERE WE GET THE JSON DATA:
$jsonurl = "http://search.twitter.com/search.json?q=%23search_word&rpp=10";
$json = file_get_contents($jsonurl,0,null,null);
echo $json;
And that's it, in this way it works fine. I call the PHP file, it returns the JSON data retrieved from the search URL, and in the main HTML JavaScript functions I insert the tweets in the div. The problem is that at the first time, I tried to do it directly in JavaScript, calling the search URL with Ajax, like this:
MAIN HTML FILE:
//same code above
//ajax call to a php file that will search the tweets
ajax.open( 'GET', 'http://search.twitter.com/search.json?q=%23search_word&rpp=10', true);
//same code above
I thought it should return the JSON data, but it doesn't. I'm wondering why not and that is what I would like to ask. Does someone have any idea of why I can't get JSON data using the Ajax object? If the search URL http://search.twitter.com/search.json?q=%23search_word&rpp=10 returns JSON data, it should be obtained in the ajax object, right?
XHR requests are generally limited to same-domain requests; e.g, if you're on bertsbees.com, you can't use an Ajax method to pull data from twitter.com.
That said, Twitter's API supports a popular data transport method known as JSON-P, which is really just a glorified injection technique. You simply pass it a callback method, and the data returned will be wrapped in your desired function, so it gets eval'd and passed in.
You cannot make a cross domain request using javascript, unless you are doing from an browser addon.

Categories

Resources