Reading JavaScript Variables in PHP - javascript

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+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/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

Related

Sending array to PHP using XMLHttpRequest (pure JS)

I'm attempting to send an array from JS to PHP using AJAX.
What seems to be happening is that the request is going through and is successful, but no data is received on the server (my test.php script needs the data from this array). Here is what I have so far...
Javascript
myButton.onclick = function() {
var xhr = new XMLHttpRequest();
xhr.open("POST", "test.php", true);
xhr.onreadystatechange = function () {
if (xhr.readyState==4 && xhr.status==200) {
console.log("Done. ", xhr.responseText);
}
}
//xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send('myArray='+JSON.stringify(myArray));
};
test.php
<?php
//$myArray = json_decode($_POST['myArray']); //Undefined index
print_r($_POST);
Note, myArray is not shown in the above code, but it is a valid array.
I've searched around SO (which led me to adding the 'setRequestHeader' in), as well as the wider internet. However, this has made no difference and I seem to be going round in circles. When I print $_POST, it's always an empty array.
I'm sure there's something I'm missing/misunderstanding.
Edit
As requested...
var myArray = ["John", "Jill", "James"];
I've also attempted this with an array of booleans, as well as an associative array/object.
Edit 2
As requested, adding screen shot from dev console...
you can use formData :
let data = new FormData();
let values = [1, 2, 3];
data.append('myArr', JSON.stringify(values));
// send data to server
and in php use json_decode :
$Values = json_decode($_POST['myArr']);
another way is to create HTML checkbox or select elements with javascript , assign values , serialize them and send them to back-end .

ASP.net and HTML File Upload

Problem: I'm working on a site written with a master page and a wrapper form. The page I'm writing needs to upload a file to the server to be validated.
What's needed: A way to submit a file without using a form and receive that form on the server in a WebMethod.
What I've tried: Using an XMLHttpRequest to send FormData to a WebMethod. The FormData is created and the file is appended like so:
let dataXML = new FormData();
dataXML.append("xml", $("#fileUpload")[0].files[0]);
sent it like this:
let request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState === 4 && request.status === 200)
// Do stuff with the request.responseText
};
request.open("POST", PageName + "/" + Route, true);
request.send(dataXML);
with a webMethod like this:
[WebMethod]
public static string myWebMethod(MultipartFormDataContent Files)
{
// Do stuff with the file
}
The WebMethod does not run at all. I'm assuming this is an issue with the WebMethod and its parameters. If I look at Page_Init() (which is run because it's returning the pages html right now rather than running my WebMethod) I can see the file in HttpContext.Current.Request.Files[0] but I don't know how to make the WebMethod run.
And before anyone says it: yes, I tried JQuery AJAX but it doesn't make a difference, the problem doesn't appear to be client side (the file was uploaded in both cases). I don't really care between JQuery AJAX and XMLHttpRequest.

uploading pdf/doc etc and sending data to the server in request - Javascript

I need to upload pdf,excelsheets,doc. etc format to server - data in request file using simple Javascript.
I was thinking to do with Blob , byte stream .. is it possible.
Can someone explain ?
Using vanilla Javascript you can create an XMLHTTPRequest object and send the file to any endpoint of your choice.
Some questions to consider when you are working doing this:
Are you looking to upload just the file or do you need to upload any associated data with it?
Do I need to support multiple files? If so, you could use the FormData object (it is a defined key value pair type) to hold multiple files if you have an HTML5 input form with the multiple attribute set. Make sure your project allows support for it.
What server/framework are you using? How do you access this? A request object? Something similar?
How do you want/need to create a selector for your html file input for use with Javascript? I'll provide an example of using the html attribute of id below.
Do you need to support CORS? Essentially, are you sending a request to the same server or a remote server? If remote, you'll need to configure CORS in your server.
file input that allows multiple file support
<input type='file' id='multiple-file-input' multiple>
javascript example
// idElementForFiles - id of the <input type="file" multiple>
// endpoint - URL to send your request to
var idElementForFiles = 'multiple-file-input';
var endpoint = '/path_to_server/request';
var formdata = new FormData(); // Create FormData
var uploadedFiles = document.getElementById(idElementForFiles); // set our uploadedFiles variable
// Iterate through each file in uploadedFiles
for (i = 0; i < uploadedFiles.files.length; i++) {
// Appending each file to FormData object
// sending to 'endpoint' as an array of {'name_of_file': 'binary_file_data'}
formdata.append(uploadedFiles.files[i].name, uploadedFiles.files[i]);
}
// create new Ajax call and send
var xhr = new XMLHttpRequest();
xhr.open('POST', endpoint);
xhr.send(formdata);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr); // log response object
}
}

JS counter write to database

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.

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