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());
}
}
}
Related
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 am currently attempting to move a variable from JS to PHP.
They are being used for Stripe.
I understand I may have to use AJAX?
function _goAheadWithCustomerId(c) {
console.log('Customer Id is :', c);
customerId = c; }
I want to move customerId to a PHP file.
How might I do that?
Well the easiest way i can think of without using AJAX is just send a get request to a php page using
window.location.href
Code for JS
function _goAheadWithCustomerId(c) {
console.log('Customer Id is :', c);
customerId = c;
window.location.href = "index.php?customerid=" + c;
}
And later using php check if(isset($_GET["customerid"] to check if the value has been received or not.
Php Code
if(isset($_GET["customerid"]))
{
$c = $_GET["customerid"];
// use it the way you want.
}
You can try following code in AJAX.
function sendCustId(c) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("custDiv").innerHTML = "Customer ID successfully sent to server.";
}
};
xhttp.open("GET", "myPhpScript.php?custId="+c, true);
xhttp.send();
}
At server side you need to access variable as
$customerId = $_REQUEST['custId'];
Can I send a request as below? With parameters being assigned with a JSON style object. I only get error. But when I use a REST client and choose RAW data, it's OK. I guess I must have written incorrect code. How to send raw JSON data in JavaScript? Could anyone help me?
xmlhttp = new XMLHttpRequest();
var url = "https://someURL";
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function () { //Call a function when the state changes.
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
var parameters = {
"username": "myname",
"password": "mypass"
};
// Neither was accepted when I set with parameters="username=myname"+"&password=mypass" as the server may not accept that
xmlhttp.send(parameters);
No. The send() method can take a number of different argument types, but a plain object is not one of them (so it will probably end up having toString() being called on it and being turned into "[Object object]").
If you want to send JSON then you must:
Say you are sending JSON: xmlhttp.setRequestHeader("Content-type", "application/json");
Convert your JavaScript object to a string of JSON text: var parameters = JSON.stringify({"username":"myname","password":"mypass"});
Be prepared to accept JSON instead of application/x-www-form-urlencoded data on the server side.
Also note that, since you are using an absolute URI, you may run into cross domain issues.
xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", AjaxURL, true);
xmlhttp.onreadystatechange = function () { //Call a function when the state changes.
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
cb(xmlhttp.responseText);
}
};
xmlhttp.send(JSON.stringify(Idata));
I'm creating a simple WebGL project and need a way to load in models. I decided to use OBJ format so I need a way to load it in. The file is (going to be) stored on the server and my question is: how does one in JS load in a text file and scan it line by line, token by token (like with streams in C++)? I'm new to JS, hence my question. The easier way, the better.
UPDATE: I used your solution, broofa, but I'm not sure if I did it right. I load the data from a file in forEach loop you wrote but outside of it (i.e. after all your code) the object I've been filling data with is "undefined". What am I doing wrong? Here's the code:
var materialFilename;
function loadOBJModel(filename)
{
// ...
var req = new XMLHttpRequest();
req.open('GET', filename);
req.responseType = 'text';
req.onreadystatechange = function()
{
if (req.readyState == 4)
{
var lines = req.responseText.split(/\n/g);
lines.forEach(function(line)
{
readLine(line);
});
}
}
req.send();
alert(materialFilename);
// ...
}
function readLine(line)
{
// ...
else if (tokens[0] == "mtllib")
{
materialFilename = tokens[1];
}
// ...
}
You can use XMLHttpRequest to fetch the file, assuming it's coming from the same domain as your main web page. If not, and you have control over the server hosting your file, you can enable CORS without too much trouble. E.g.
To scan line-by-line, you can use split(). E.g. Something like this ...
var req = new XMLHttpRequest();
req.open('GET', '/your/url/goes/here');
req.onreadystatechange = function() {
if (req.readyState == 4) {
if (req.status == 200) {
var lines = req.responseText.split(/\n/g);
lines.forEach(function(line, i) {
// 'line' is a line of your file, 'i' is the line number (starting at 0)
});
} else {
// (something went wrong with the request)
}
}
}
req.send();
If you can't simply load the data with XHR or CORS, you could always use the JSON-P method by wrapping it with a JavaScript function and dynamically attaching the script tag to your page.
You would have a server-side script that would accept a callback parameter, and return something like callback1234(/* file data here */);.
Once you have the data, parsing should be trivial, but you will have to write your own parsing functions. Nothing exists for that out of the box.