Moving Variables from JS to PHP - javascript

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'];

Related

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

Modify webpage element by calling Python function from Javascript

My HTML file looks like this:
Sum: <div id="sum">?</div>
And the corresponding JavaScript like this:
function refresh(){
//Wait for request from Amazon Gateway API, then replace 'sum' with result of
Python function
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "https://8qp45dk604.execute-api.us-east- 1.amazonaws.com/beta", true);
xhttp.send();
xhttp.addEventListener("readystatechange", processRequest, false);
function processRequest(e){
if(xhttp.readyState == 4 && xhttp.status == 200){
var response = JSON.parse(xhttp.responseText);
var a = response.a;
var b = response.b;
document.getElementById("sum").innerHTML =
resultOfPythonFunction('sum.py', 'sum', a, b);
}
}
setTimeout(refresh, 3000);
}
What should I replace the line resultOfPythonFunction('sum.py', 'sum', a, b); with in order to modify the div with the result of a Python sum function?
The browser can't execute python code. To do what you're asking, you would have to set up a python back end that you could send HTTP POST requests to that would perform sum on your request body, and then send back the result. Some common tools for this are django, flask, and pyramid.
You could then grab this result and set it to the div in the way you did before.

Sending data from javascript to php file

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());
}
}
}

Write line to text file with AJAX XMLHttpRequest

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.

replace setInterval with setTimeout

thanks in advance for your help! I am working with (and super new to) JavaScript, node.js with express, and sqlite3. I am trying to make an AJAX request to get a list of all the messages that have been posted to the chatroom page:
var meta = document.querySelector('meta[name=roomName]');
var roomName = meta.content;
window.addEventListener('load', function(){
var intervalID = setInterval(updateMessages, 4000);
}, false);
function updateMessages() {
var req = new XMLHttpRequest();
req.open('GET', '/' + roomName + '/messages.json', true);
req.send();
document.getElementById('messages').innerHTML = req.responseText;
}
Two questions: 1. I think I should be using setTimeout instead of setInterval. How would I go about switching to using this method? 2. Is the server-side code below that corresponds to the code above correct? How do I get access to the data that comes back after this request?
app.get('/:roomName/messages.json', function(request, response){
var roomName = request.params.roomName;
var sql = "SELECT ALL body FROM messages where room="+roomName+";";
conn.query(sql, function(error, result) {
if(error) {
console.log("There was an error.");
}
response.send(result);
});
});
setInterval is the appropriate thing to use here.
However, keep in mind that you will never see any messages because AJAX is asynchronous, so req.responseText won't have anything. You should use a readystatechange event:
req.open(......);
req.onreadystatechange = function() {
if( this.readyState == 4) {
document.getElementById('messages').innerHTML = this.responseText;
}
};
req.send();

Categories