I am trying to send the data in XMLHttpRequest through json, in the log I receive succesful and the data info correctly but in the php I cannot collect the data,this works with an exit() and the $data on the php file, if you take out $data it the responseText is empty, if you take out exit(), it transforms into some weird characters with ? and more nonsense, and if you use $_POST it shows array() and some weird characters again after the empty array. The js part is sent when you click on the chart.js and then it is accessed from report.php when clicking on an icon, I don't know if when accessing like this the info from the js is not arriving, as I just get a blank page. This is the js and the php:
onComplete: function() {
console.log(myChart.toBase64Image());
var imgData = myChart.toBase64Image();
var imgRes = imgData.replace('data:image/png;base64,', '');
var xhttp=new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == XMLHttpRequest.DONE) {
console.log(xhttp.responseText);
if (xhttp.status === 200) {
console.log('successful');
} else {
console.log('failed');
}
}
}
xhttp.open("POST", base_url_admin+"record/reporte", true);
xhttp.setRequestHeader("Content-type", "application/json");
let data = JSON.stringify({"resultChartImg": imgRes});
xhttp.send(data);
}
php:
header("Content-Type: application/json");
// build a PHP variable from JSON sent using POST method
$data = json_decode(file_get_contents('php://input'), true);
print_r($data);exit();
Error Image of the weird characters
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
Using the code I found from one of the StackOverflow postings, I'm trying to call a REST service GET method. However, when the code runs it is not putting the GET format correctly in the URL.
Here's the code:
<!DOCTYPE html>
<script>
function UserAction(json)
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function ()
{
if (this.readyState == 4 && this.status == 200)
{
alert(this.responseText);
}
};
xhttp.open("GET", "http://localhost:8080/isJsonValid/json", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send(json);
}
</script>
<form>
<button type="submit" onclick="UserAction(json)">Check if JSON Valid</button>
<label for="json">JSON:</label>
<input type="text" id="json" name="json"><br><br>
</form>
</html>
The expected format of this GET REST service would be:
http://localhost:8080/isJsonValid/json
(where json in the line above is the actual JSON sent as a parameter.)
Yet, what is shown in the URL line includes the project, directory and the URL has the ?name=value syntax.
Since the GET doesn't match the simple http://localhost:8080/isJsonValid/json format, I get a 404 error.
I realize there's something obvious I'm missing.
Thanks to all for suggestions.
If you need to send data you need to either send it as a query param or as the body. If you want to send it as a body need to use POST type. Below is the example of POST type.
// Create a request variable and assign a new XMLHttpRequest object to it.
var request = new XMLHttpRequest()
// Open a new connection, using the GET request on the URL endpoint
request.open('GET', 'https://ghibliapi.herokuapp.com/films', true)
request.onload = function() {
// Begin accessing JSON data here
var data = JSON.parse(this.response)
if (request.status >= 200 && request.status < 400) {
data.forEach(movie => {
console.log(movie.title)
})
} else {
console.log('error')
}
}
// Send request
request.send()
For post Request. As I don't have any API with me I have used get API URL.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
console.log(this.responseText)
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
}
};
xhttp.open("POST", "https://ghibliapi.herokuapp.com/films", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send("Your JSON Data Here");
Thanks all for the great input and help!
The best solution for me was to just use, as suggested, a POST. The GET was always putting the "?" in the URL even if I concatenated it, That "?" isn't how the REST service interprets the GET parameters so it wouldn't work that way. In the REST framework I'm using, GET parameters are just concatenated with one or more "/" as separators in the URL.
Appreciate all the terrific help here on SO. :)
I want to send data with the POST method to a php server, then retrieve data from the server, using GET method this time (I assume).
Here's the JS :
function send()
function send(leURL, laValeur) {
try {
return new Promise(function(resolve, reject) {
var req = new XMLHttpRequest();
req.open('POST', leURL);
req.setRequestHeader("Content-Type", "application/json");
req.onreadystatechange = function() {
if (this.readyState == XMLHttpRequest.DONE && this.status == 200) {
document.getElementById("result").innerHTML = "Ok!";
}
};
jmail = JSON.stringify(laValeur);
req.send(jmail);
resolve("true");
});
}
catch (err) {
window.alert("erreur 2");
}
}
function recieve()
function recieve(laURL) {
try {
var reqt = new XMLHttpRequest();
reqt.open('GET', laURL);
reqt.onreadystatechange = function(e) {
if (this.readyState == XMLHttpRequest.DONE && this.status = 200) {
var rep = JSON.parse(this.responseText);
try {
window.alert(rep);
}
catch (e) {
window.alert("erreur 4");
}
}
}
reqt.send();
//return rep;
}
catch (e) {
window.alert("erreur 3");
}
}
function calls :
//there's a form in the HTML (id="form")
document.getElementById("form").addEventListener('submit', function(evt) {
evt.preventDefault();
send(url, mail)
.then(recieve(url));
});
Old recieve() function (for testing purposes) :
function recieve(laURL) {
window.alert(laURL);
}
So, as long as I was using old recieve() function, I had send() print "Ok!" and recieve() creating an alert, which makes me think it worked fine. But now that I use the new recieve() function, the page just reloads. (No catch block is even displayed !)
Here's the PHP :
<?php
if (!empty($_POST)) {
$var = //do something with the data, involving $_POST
echo $var;
}
else {
echo "Hello, there !";
}
?>
Since $var was generated out of the first HTTP request (POST), how do I retrieve it in javascript ?
I suspect the error is caused either by the php or because of using two XMLHttpRequests (still I don't know how I should do this using only one HTTP request)
Your PHP stores the data in a variable, echos it out, then exits.
At this point, the PHP program has finished, the memory gets cleaned up, and the variable no longer exists.
If you want the data to be available to another request, then you have to store it somewhere persistent such as a session or a database.
If you want to use a single request, then read this.responseText in the readyStateChange handler.
The POST request already returns the value (using echo). All you need to so is show it using your JavaScript.
e.g. in the POST request:
if (this.readyState == XMLHttpRequest.DONE && this.status == 200) {
document.getElementById("result").innerHTML = this.responseText;
}
I don't see any need for the GET request, unless you intend to use this at a later time in your process, expecting that the data may have changed on the server. But for that to make any sense, you have to have stored the data somewhere on the server, and also send in the request some identifier telling the server which piece of data to retrieve.
What do you do with your data ?
How do you store them ?
How do you retreive them on the server to sending them after to the client if needed ?
You should store the $var somewhere, generally we use session $_SESSION for that. All depends of what you want finally.
Documentation for PHP session : https://www.php.net/manual/fr/reserved.variables.session.php
Once you have start the session,
I think you want to do something like that:
<?php
if ($_SESSION['var']) {
echo "already done";
...
} else {
if(!empty($_POST)) {
$_SESSION['var'] = //do something with the data, involving $_POST
echo $_SESSION['var'];
} else {
echo "var = not done, post = empty";
}
}
?>
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
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());
}
}
}