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";
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
i have a function with a XML-HTTP-Request. Unfortunately i don't get back my DB-result when i call this function getUserdataByToken() <-- working, via a second Function sendPost(wall).
I just want to have the return value (array) inside my second function but the value is always "undefined". Can someone help me?
function getUserdataByToken() {
var token = localStorage.getItem("token");
var userDataRequest;
//-AJAX-REQUEST
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var url= window.location.protocol+"//"+window.location.host+"/getuserdatabytoken";
var param = "token=" + token;
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
userDataRequest = JSON.parse(xhttp.responseText);
if (userDataRequest.success === "false") {
warningMessage('homeMessage', false, userDataRequest.message);
} else {
return userDataRequest;
}
}
};
xhttp.open("POST", url, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(param);
}
Function call via second Function (AJAX) leads too "undefined" Value for "userDataRequest" (return of function 1).
function sendPost(wall) {
var content;
var token = localStorage.getItem("token");
var userData = getUserdataByToken(); // PROBLEM
console.log(userData); // "leads to undefined"
alert(userData); // "leads to undefined"
… Ajax Call etc…
P.S. it's my first post here in stackoverflow, I'm always grateful for tips.
Thanks!
The userdata value only exists within the anonymous Ajax callback function, and you only return it from there. That is pointless because there is nowhere for it to be returned to; certainly the value does not get returned from getUserdataByToken. Don't forget that Ajax calls are asynchronous; when sendPost calls getUserdataByToken the request won't even have been made.
Generally you'd be much better off using a library like jQuery for this whole thing. Apart from making your code much simpler, it will allow you to use things like Promises which are explicitly intended to solve this kind of problem.
(And, do you really need to support IE5? Are you sure?)
I am working on an assignment for class and we have to create a dynamic website. We have to create all the containers in HTML, then load all out content onto a MySQL DB and then use Javascript to read the PHP file that collects the content from MySQL.
I have managed to get it to pull a list from the DB and display on my site, but now I'm stuck as to how to get it to read other parts of the page and pull them into the html.
Here is the PHP I have so far:
$con=mysqli_connect("localhost","Username","password",'DBname');
if (mysqli_connect_errno()){
die("Error: " . mysqli_connect_error());
}
$result = mysqli_query($con,"SELECT * FROM HomeList");
echo "<ul>";
while($row = mysqli_fetch_array($result)){
echo "<li>".$row['ListItem']."</li>";
}
echo "</ul>";
mysqli_close($conn);
?>
Here is my Javascript:
function getOutput() {
getRequest(
'php/getinfo.php',
drawOutput,
drawError
);
return false;
}
// handles drawing an error message
function drawError () {
var container = document.getElementById('id');
container.innerHTML = 'Error has occurred';
}
// handles the response, adds the html
function drawOutput(responseText) {
var container = document.getElementById('id');
container.innerHTML = responseText;
}
// helper function for cross-browser request object
function getRequest(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req .readyState == 4){
return req.status === 200 ?
success(req.responseText) : error(req.status)
;
}
}
req.open("GET", url, true);
req.send(null);
return req;
}
I'm wanting to reuse as much code as possible but for pulling content from the DB without having to have multiple JS and PHP files. And we are under strict orders to not use plugins or Bootstrap.
Any help would be great!
Thank you!
A solution could be to declare a new function (ex. updateElt) which calls getOutput by giving it the parameter url ('php/getinfo.php'), but you also need to set your 'id' parameter in order to update the correct element.
So you have to declare an id var in your script (not in a function) and assign it a value in the updateElt. This way the id will have a global scope to your script and you 'll be able to access it in your drawError and drawOutput function.
Here is my javascript function that reads from the file every second and outputs it:
var timer;
var url = "http://.../testdata.txt";
function ajaxcall() {
var lines;
var alltext;
request = new XMLHttpRequest();
request.open("GET", url, true);
request.onreadystatechange = function() {
if (request.readyState === 4) { // document is ready to parse.
if (request.status === 200) { // file is found
allText = request.responseText;
lines = request.responseText.split("\n");
document.getElementById("test").innerHTML = "";
for (i in lines) {
document.getElementById("test").innerHTML += lines[i] + "<br>";
}
}
}
}
request.send();
}
timer = setInterval(ajaxcall, 1000);
I haven't got the hang of AJAX yet so I tried to make a similar way to write into the file using what I read on the internet:
function chat() {
request = new XMLHttpRequest();
request.open("POST", url, true);
request.send("\n" + document.getElementById("chatbox").value);
}
However that does absolutely nothing and I don't understand why. The element "chatbox" is input type textbox and chat() is called by input type submit.
You cannot write to a file using just a POST call. In fact, you cant write to a file using only JavaScript/AJAX. You will need a server-side script in for example PHP that will write to the file for you, and then you need to call this script using AJAX.
So I have a .js file that I need to retreive a variable from a PHP file. No, I can't make the server treat .js as a .php though.
So anyway, I have this script
function getPHPVariable(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
variableIWant = ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "phpfile.php", true);
ajaxRequest.send(null);
}
Now the variableIWant is what I need to be used in another string later on, but everytime I call it it is shown as undefined. I do know that the variable is being sent properly though because by simply adding alert(variableIWant); underneath the responseText line, it properly alerts me of the variable.
So for simplicity, is it possible to get the variableIWant and use it in another string, or am I SOL because it has to wait for the readystate?
Where do you define variableIWant?
If you just assign it inside the onreadystatechange function it's just available within the scope of that function.
So you have to either declare it outside all of the functions or write
window.variableIWant = ajaxRequest.responseText;
UPDATE: just as Quentin points out, just put the code inside the onreadystatechange function...
either:
ajaxRequest.onreadystatechange = function() {
if (ajaxRequest.readyState == 4) {
variableIWant = ajaxRequest.responseText;
longString = "The variable I retrieved is: "+variableIWant+". Isn't this nice?";
document.getElementById('theDivPart').innerHTML = longString;
}
}
or:
ajaxRequest.onreadystatechange = function() {
if (ajaxRequest.readyState == 4) {
update(ajaxRequest.responseText);
}
}
function update(value) {
longString = "The variable I retrieved is: " + value + ". Isn't this nice?";
document.getElementById('theDivPart').innerHTML = longString;
}
http://jsfiddle.net/roberkules/JgZ2B/
by the way, is there a reason why you don't use a javascript framework? e.g. like jquery that takes care of all the ajax hassle? your code in jquery:
<script type="text/javascript">
$.get('http://sumary.org/phpfile.php').done(function(data){
$(function() {
$('#theDivPart').html('The variable I retrieved is: ' + data + '. Isn\'t this nice?');
});
});
</script>
<body>
<div id="theDivPart"></div>
</body>
So for simplicity, is it possible to get the variableIWant and use it in another string, or am I out of luck because it has to wait for the readystate?
It has to wait for the readystate function to be called, and that won't happen until the HTTP response returns.
Put your logic in the function you assign to readystate, that is what readystate is for.