How do I get value from SQL using AJAX - javascript

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

Related

Error receiving json data from XMLHttpRequest

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

Output PHP already encode to json, and send to javascript to be json, not working

I'm do output with json_encode to sending to javascript, with this code.
<?php
include "Connection.php";
$syntax_query = "select * from product";
$thisExecuter = mysqli_query($conn, $syntax_query);
$result = array();
while($row = mysqli_fetch_assoc($thisExecuter)){
array_push(
$result,
array(
"id" => $row["product_id"],
"name" => $row["product_name"]
)
);
}
echo json_encode($result);
?>
so output show like this,
[{"id":"121353568","name":"Baju Casual - Black"},{"id":"556903232","name":"Tas LV - Red"},{"id":"795953280","name":"Sword - Wood"},{"id":"834032960","name":"Scooter - Iron Plate"}]
and code javascript like this
function showHint() {
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
var obj = this.responseText;
document.getElementById("txtHint").innerHTML = obj.id;
}
xmlhttp.open("GET", "Download.php");
xmlhttp.send();
}
so obj.id its not working, output show undifined.
I use ajax calls when I want to call a Php file and get a response from the same as below to try once that as I have shown. Before moving with Ajax you must need jquery to be imported into the calling file.
If Jquery is imported then ignore the steps
Here are steps,
Go to the link https://code.jquery.com/jquery-3.6.0.min.js copy whole content (use ctl+A to select whole content and ctl+C to copy)
Open a new file in the current project folder and paste the copied content (use ctl+V to paste) save it as 'jquery-3.6.0.min.js'
Import the js file in the HTML file in script tag as shown '
Now, this is the ajax example to call the PHP file and to get a response
function showHint() {
//since you have used GET method I have used here GET but You can use POST also here
$.ajax({
url: 'Download.php',
type: 'get',
//if any value you want to pass then uncomment below line
// data: {'name_to_pass':'value'},
//the variable can be accessed in the php file by 'name to pass' under $_GET['name_to_pass'] or $_POST['name_to_pass'] based on type
success: function(res)
{
// open DevTool console to see results
console.log(JSON.parse(res));
}
});
}
Hope this will help you out, thank you
Maybe you need a JSON.parse in the response, something like JSON.parse(this.responseText).
And also I can see the result is an Array so you will need to iterate obj
obj.forEach(item => {
document.getElement("txtHint").innerHTML = item.id;
});
you should define the response type as json
header('Content-Type: application/json; charset=utf-8');
echo json_encode($result);
function showHint() {
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
**var obj = this.responseText;**
document.getElementById("txtHint").innerHTML = obj.id;
}
xmlhttp.open("GET", "Download.php");
xmlhttp.send();
}
When you get the responseText it's text, not an object.
var obj = this.responseText; should be let obj = JSON.parse(this.responseText);
Then you can access obj.id as a property.

access XMLHttpRequests send(data) in PHP backend

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

how do I access the object the object i sent to the server file

//Sent an ajax http post request to a php file on the server, the post //request is a simple object.
var xhr = new XMLHttpRequest();
var person = {
"firstName" : "Adebowale",
"lastName" : "Johnson",
"ago" : 43
}
xhr.open("POST","phfile.php",true);
xhr.setRequestHeader("Content-type","application/x-www-form- urlencoded");
xhr.onreadystatechange = function() {
if(xhr.readyState === 4) {
var status = xhr.status;
if((status >= 200) && (status < 300) || (status === 304)) {
alert(xhr.responseText);
}
}
};
xhr.send(JSON.stringify(person));
//if I do alert(xhr.responseText);
//I get object{} from the browser.
//On the server, using php, how do I access the object, if I do echo or //print_r, I get the empty object --- object{} with none of the properties.
//As you can tell from the tone of my question, am still very new to all //these, am just trying to learn please.
//on my phfile.php, I set up the following php code...
<?php
print_r
//How do I access the object I sent to this file please
?>
I dont see the need for JSON.stringify(person) in your AJAX request, since all the keys of the Object are already in strings.
Since you are using POST method, you can directly access the object like
print_r ($_POST['person']);
You can read raw POST data using STDIN:
$post_data = fopen("php://input", "r");
$json = fgets($post_data);
$object = json_decode($json);
$firstName = $object->firstName;
$lastName = $object->lastName;
$age = $object->age;
You could simplify all of this by just passing the data as URL-encoded form fields:
xhr.send('firstName=' + encodeURIComponent(person.firstName) + '&lastName=' + encodeURIComponent(person.lastName) + '&ago=' + encodeURIComponent(person.ago);
Then you can just access them as $_POST['firstName'], etc. in PHP.

Javascript Returing Value from httprequest

The php script is returning a value and the 1st alert works.
I am unable to reference the value returned by httprequest at the 2nd alert. Ideally, I would call the function get_captcha() - and it would return the value - its just that I dont know how to do this.
I realize setting the variable globally may not be the best way to do this but its the only thing I could think of - Im open to alternatives.
<script type="text/javascript">
var url = "captcha_get_code.php"; // The server-side script
var cap;
function ValidateForm() {
get_captcha()
alert(cap); //undefined
}
function get_captcha() {
http.open("GET", url, true);
http.onreadystatechange = handleHttpResponse;
http.send(null);
}
function handleHttpResponse() {
if (http.readyState == 4) {
if (http.status==200) {
//return http.responseText;
cap=http.responseText;
alert(cap); //this one works
}
}
}
function getHTTPObject() {
var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject){
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
if (!xmlhttp){
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
}
}
return xmlhttp;
}
var http = getHTTPObject(); // We create the HTTP Object
</script>
You cannot "return" values from successful XMLHttpRequest invocations. You can perform whatever sort of processing you need inside the callback function.
XMLHttpRequests are performed asynchronously. You cannot make your code "wait" for them (unless you make them synchronous) (and you really, really should not do that). There's no real need, however, because the runtime system will call your "readystatechange" handler when the request completes. From in that code, you're free to do whatever you need.
This fact requires you to think a little differently about how to write the code, but it's not really that much of an adjustment. If, for example, you would be inclined to write a "processResults()" function, then you can still do that — you would simply call that from inside the "readystatechange" handler.
I see this thread is 4 years old, but it has wrong answer!
You can get return value from a successful XMLHttpRequest invocations.
My project use WebSocket, but it use XMLHttpRequest to upload images.
In a javascript, call uploadSend(containerID) where all <img> are stored.
// ----- uploadSend()
// ----- This function sends all objects in a container (containerID)
// ----- All object has to be <img>
FILE: upload.js
function uploadSend(containerID) {
var elm = document.getElementById(containerID);
for (i=0; i<elm.childNodes.length; i++) {
var form = new FormData();
form.append('id', elm.childNodes[i].id);
form.append('src', elm.childNodes[i].src);
TOS(form);
}
}
function xhrState(self) {
if ((self.readyState == 4) && (self.status === 200))
console.log(self.responseText);
}
function xhrProgress(event) {
if (event.lengthComputable)
if (event.loaded == event.total)
console.log('Image 100% uploaded.');
}
function TOS(form) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () { xhrState(this); }
xhr.open('POST', '/upload.php');
xhr.upload.onprogress = function(event) { xhrProgress(event); }
xhr.send(form);
}
FILE: upload.php
header("Content-type: text/plain");
$filename = '/var/www/public/upload/'.microtime(true);
// ----- Save a complete file for what we did get.
$hnd = fopen($filename . 'TXT', 'wb');
fwrite($hnd, print_r($_COOKIE, true));
fwrite($hnd, print_r($_GET, true));
fwrite($hnd, print_r($_FILES, true));
fwrite($hnd, print_r($_POST, true));
fclose($hnd);
// ----- Save just jpg for the images we did get.
$hnd = fopen($filename . 'jpg', 'wb');
$image = explode(',', $_POST['src']);
fwrite($hnd, base64_decode($image[1]));
fclose($hnd );
// ----- Type the result that you want back.
echo "{$filename}.jpg";

Categories