AJAX POST returning null values - javascript

I have tried and tested various methods for completing this task for about a day now. Please be forewarned that I am building this simply, and then working my way up!
I have a form that consists of a textarea, and two input fields. The input fields allow a XMLHttpRequest to send information pertaining to a username, and message - sent to a chatroom that I am trying to make.
The problem that I have with my request, is simply that I can send the information, and insert a row into a database, but I can't get any information back! You will see from the code below, that I have put an alert in, to check what the response text is, but it comes back as null (not undefined, but ""). Please check the code below:
function insertMessage() {
var username = document.getElementById('username').value;
var message = document.getElementById('message').value;
var queryString = "username=" + username + "&message=" + message;
// send the username and message information to be inserted into the database
var url = 'classes/chatroom/chatroom.upload.php';
// create xml request
var request = createCORSRequest("POST", url)
// create a function that will receive data sent from the server
request.onreadystatechange = function () {
if (request.readyState == 4 && request.status == 200) {
alert(request.responseText);
}
}
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(queryString);
}
function createRequest(method, url) {
var thisRequest = new XMLHttpRequest();
if ("withCredentials" in thisRequest) {
// thisRequest has 'withCredentials' property only if it supports CORS
thisRequest.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") { // if IE use XDR
thisRequest = new XDomainRequest();
thisRequest.open(method, url);
} else {
thisRequest = null;
}
return thisRequest;
}
The code that pertains to the insertion of a database row is:
<?php
include 'chatroom.config.inc.php'; // the database file
$message_username = $_POST['username'];
$message_content = $_POST['message'];
if ($message_username == "Username: Once entered, you don't have to enter again" || $message_username == "") {
$message_username = "Guest";
}
if ($message_content == "Message:" || $message_content == "") {}
else {
$users->post_message($message_username, $message_content); // insert database row using PDO query
}
?>
Could anyone provide a clue as to where I'm going wrong?

The code looks good to me, your PHP code is inserting the data in DB but it isn't returning back any text or value.
For values to be retrieved on the client side i.e. on successful completion of your ajax request, you will have to send the data to client side.
Try using php's echo function and return the text / value.

Related

How do I get value from SQL using AJAX

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

How to send data to php using POST and then retrieve data from php using GET in pure javascript?

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";
}
}
?>

how to use an API on web, using Ajax and Javascript?

I want to implement a login by calling an API using Ajax and Javascript.
User enters username and password and by clicking a button "login()" would be called. If input is correct it should open the welcome page. I implemented it as below. But it does not work!
function login() {
var url = "http://...";
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
console.log("before function. ")
xhr.onreadystatechange = function () {
console.log("before if. ")
if (this.readyState == 4 && this.status == 200) {
console.log("inside if. " + xhr.responseText);
window.open(welcome);
}
};
var obj = { UserName: username , Password: password }
var data = JSON.stringify(obj);
xhr.send(data);
console.log("END ");
}
As suggested, I added several console log to debug it and I found out that it never run inside the if. There is no error on console and here's the output on console:
before function.
END
before if.
(before was repeated 3 times)
I have already checked API by Postman. It works.
If username and password are correct, it returns all information of user and the http status code is 201. If input is incorrect then it returns an error message and status code is 401.

Why isn't JavaScript throwing exceptions as the result of an asynchronous HTTP (AJAX) request?

I've written the following JavaScript function which is very simple, it takes an ID and which then is sent to a PHP page, which echoes out some JSON. It passes the ID into the PHP page via GET.
For example, if I was to make the following GET request: /processing/getAccountInfo.php?id=5, it would return this (got from a database): {"username":"carefulnow","profileImg":null}. This is correct, so I know my PHP is working fine.
My JavaScript code that originally called the AJAX now needs to process it, echo it out and check it for errors. If the PHP function encounters any errors, the returned JSON will contain an "errorMsg" which contains the name of the PHP exception that it encountered including a specific message (Exception::getMessage()). An example error result would be {"errorMsg":"PDOException: some error..."}.
function getAccountInfo(id) {
var loading = document.getElementById("loading");
var inner = document.getElementById("accInfInner");
var name = document.getElementById("accInfName");
var img = document.getElementById("accInfImg");
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
try {
var response = JSON.parse(this.responseText);
if (response.errorMsg === undefined) {
if (response.username === undefined || response.profileImg === undefined) {
throw new Error("Could not get the username and profile image. Try logging in then back out.");
}
name.innerHTML = response.username;
// The profile image is not required.
if (response.profileImg !== null) {
img.src = response.profileImg;
} else {
img.src = "/assets/img/defaultuser.jpg";
}
loading.style.display = "none";
inner.style.display = "block";
} else {
throw new Error(response.errorMsg);
}
} catch (exception) {
inner.innerHTML = "Error. Hover for details.";
inner.title = exception.message;
}
}
};
xmlhttp.open("GET", "/processing/getAccountInfo.php?id=" + id, true);
xmlhttp.send();
}
The problem, however, is that the throw statements aren't working. If an error is thrown from the PHP, nothing happens (no errors in the console)! My IDE (PHPStorm 2017.1) gives the following error: "'throw' of exception caught locally", which after a lot of searching, I cannot find anyone else having this same issue. Is it something to do with the GET request been asynchronous, or is it something a lot simpler I'm not seeing?

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.

Categories