I have an XMLHttpRequest sending data to a PHP backend.
var req = new XMLHttpRequest();
req.open('GET', url);
req.onload = function() {
// This is called even on 404 etc
// so check the status
if (req.status == 200) {
// Resolve the promise with the response text
resolve(req.response);
}
else {
// Otherwise reject with the status text
// which will hopefully be a meaningful error
reject(Error(req.statusText));
}
};
// Handle network errors
req.onerror = function() {
reject(Error("Network Error"));
};
// Make the request
req.send('query=messages'); // <-- i want to access this in php
i tried
print_r($_GET) and print_r($_REQUEST) but neither works.
anyone knows how to access this data?
You can only send data through the XMLHttpRequest.send()-method for POST-requests, not GET.
For GET-requests, you need to append the data to the url as query string.
url += "?query=message";
Then you can retrieve the data with PHP using:
$message = $_GET['query'];
More info: http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
Related
I know how to pass data from JS to PHP using AJAX, but have no idea how to select data to JS from db using AJAX+php.
I tried to find examples of it but nothing clear found.
Could anyone show me how can I get data from SQL? How I tried:
js function
getdata() {
// ?
var result // I want result to store here
var data = new FormData();
data.append('somekey', 'somevalue');
// AJAX CALL
var xhr = new XMLHttpRequest();
// query for getting some data from SQL
xhr.open('POST', "../php/get_answer.php", true);
xhr.onload = function(){
result = this.response // I presume that I can get result here
};
xhr.send(data);
console.log("RESULT GETTING JSON")
console.log(result)
}
get_answer.php
<?php
include("config.php");
$con = setConnection();
$id = $_COOKIE["id"];
$query = "SELECT results FROM `survey_results` WHERE user_id='$id'";
$n = mysqli_query($con, $query);
$results = 0;
while ($row = mysqli_fetch_assoc($n)) {
$results = $row['results'];
}
// return results ?
$con->close();
?>
In your php file, you can return your data as JSON string.
To do this, tell the client it's json by settings the response header to
header('Content-Type: application/json');
and return the results or data with
echo json_encode($data);
For the Javascript part, XMLHttpRequest is now an old way to make Ajax request but it's a good start to learn.
Fisrt, in your code you have to check if XMLHttpRequest is available in the navigator and try to use the old IE fashion way if not. To do this:
if (window.XMLHttpRequest) {
// code for modern browsers
xmlhttp = new XMLHttpRequest();
} else {
// code for old IE browsers
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
now you have your object so you have to set a listener witch listen for change in the state of XMLHttpRequest. If all seems ok the result go there:
xhr.onreadystatechange = function()
{
console.log("Wait server...");
if(xhr.readyState == 4) // 4 : request finished and response is ready
{
if(xhr.status == 200) // HTTP OK
{
console.log("Got data!");
result=xhr.responseText; // or result = JSON.parse(xhr.responseText) to have your data as js object
//It's here you have to modify your dom to show your data, change a variable, etc...
} ;
else // bad http response header like forbiden, not found, ...
{
console.log("Error: returned status code", xhr.status, xhr.statusText);
}
}
};
now you can set the URI and send your request:
xhr.open("GET", "../php/get_answer.php", true);
xhr.send(null)
;
If you want more informations about states and status, have a look at XMLHttpRequest Object Methods
This question already has answers here:
"Cross origin requests are only supported for HTTP." error when loading a local file
(30 answers)
Closed 2 years ago.
[enter image description here][1]i was learning ajax . but when i tried fetching data from local file it showed me error due to cors.i tried installing allow-access control origin but it didnt work .please help me
this is my java script code
function loadData() {
// Create an XHR Object
const xhr = new XMLHttpRequest();
// OPEN
xhr.open('GET', '/data.txt', true);
// console.log('READYSTATE', xhr.readyState);
// Optional - Used for spinners/loaders
xhr.onprogress = function(){
console.log('READYSTATE', xhr.readyState);
}
xhr.onload = function(){
console.log('READYSTATE', xhr.readyState);
if(this.status === 200) {
// console.log(this.responseText);
document.getElementById('output').innerHTML = `<h1>${this.responseText}</h1>`;
}
}
// xhr.onreadystatechange = function() {
// console.log('READYSTATE', xhr.readyState);
// if(this.status === 200 && this.readyState === 4){
// console.log(this.responseText);
// }
// }
xhr.onerror = function() {
console.log('Request error...');
}
xhr.send();
// readyState Values
// 0: request not initialized
// 1: server connection established
// 2: request received
// 3: processing request
// 4: request finished and response is ready
// HTTP Statuses
// 200: "OK"
// 403: "Forbidden"
// 404: "Not Found"
}```
[this the image of output which is showing error .][2]
[1]: https://i.stack.imgur.com/4YOqJ.png
[2]: https://i.stack.imgur.com/Bh1km.png
If you want to persist data in your client, use localStorage.
If you want to download data from a data source, use a web service.You can easily create a simple web server using Node and Express, for example (plenty of resources online), but this is beyond the scope of this answer.
This is part of the code for the extension:
let url = "https://mywebsite.com/data.php";
function newRequest() {
var client = new XMLHttpRequest();
client.open("POST", url, true);
client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
client.send("status=true");
console.log(client.status);
}
newRequest();
Which also logs 0 in the console. I've been following the documentation here: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest, trying countless tweaks, and there aren't any errors in the console. Not really sure what the issue could be.
The PHP on my server definitely works since I was able to POST the data successfully from a local html file.
Since the AJAX request is asynchronous, you need to handle it through a callback onreadystatechange.
The code should be like this
let url = "https://mywebsite.com/data.php";
function newRequest() {
var client = new XMLHttpRequest();
client.onreadystatechange = function() {
console.log(this.readyState) // should be 4
console.log(this.status) // should be 200 OK
console.log(this.responseText) // response return from request
};
client.open("POST", url, true);
client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
client.send("status=true");
console.log(client.status);
}
newRequest();
Hope this helps.
For More Info: https://www.w3schools.com/js/js_ajax_http_response.asp
I have this function that gets text from a php file on the server and plonks it into an HTML page.
What changes do I need to make to it to SEND data (just a couple of javascript variables) to the php file rather than read from it ? Hoping not many !!
function process() {
if (xmlHttp) // the object is not void
{
try {
xmlHttp.open("GET", "testAJAX.php", true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
} catch (e) {
alert(e.toString());
}
}
}
Take a look at what all headers you can make use of. In your case, you would want to use POST instead of GET
xmlHttp.open("POST", "testAJAX.php", true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");//or JSON if needed
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(data);
You are probably better of using POST to send data it has less limitations. e.g:
var data = {
user: 'Joe',
age: 12
};
var httpReq = new XMLHttpRequest();
// true means async - you want this.
httpReq.open('POST', 'testAJAX.php', true);
// json is just a nice way of passing data between server and client
xmlhttpReq.setRequestHeader('Content-type', 'application/json');
// When the http state changes check if it was successful (http 200 OK and
// readyState is 4 which means complete and console out the php script response.
httpReq.onreadystatechange = function () {
if (httpReq.readyState != 4 || httpReq.status != 200) return;
console.log(httpReq.responseText);
};
httpReq.send(JSON.stringify(data));
And read it:
$name = json_decode($_POST['name']);
$age = json_decode($_POST['age']);
If it's just a couple of variables, you can pop them into the query string - although you'll want to make sure their values won't break your PHP script or open a security hole (for example, don't interpret user input as a SQL string). For more complicated data structures, use POST as others have suggested.
function process(var1value, var2value) {
if(xmlHttp) {
try {
xmlHttp.open("GET", "testAJAX.php?var1="+var1value+"&var2="+var2value, true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
} catch(e) {
alert(e.toString());
}
}
}
I'm using a Javascript to ask our app (which is in Google App Engine) if the file a user wants to upload is already in his list of files (he will overwrite).
I know how to send the request, but how can I create a response from the server, using Python?
This is the request:
var req = new XMLHttpRequest();
req.open('POST', 'https://safeshareapp.appspot.com/upload', async);
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.setRequestHeader("Content-length", body.length);
req.setRequestHeader("Connection", "close");
if (async) {
req.onreadystatechange = function() {
if(req.readyState == 4 && req.status == 200) {
var response = null;
try {
response = JSON.parse(req.responseText);
} catch (e) {
response = req.responseText;
}
callback(response);
}
}
}
// Make the actual request
req.send(body);
As you see, we are getting the responseText from the request after everything has gone OK, but my question is how do we fill that responseText field on the server side??
class MyRequestHandler(webapp.RequestHandler):
def get(self):
import json
result = {"filename": xxx} // just an example, result can be any Python object
json_obj = json.dumps(result)
self.response.out.write(str(json_obj))