I am trying to make an upvote and downvote system in nodejs. The client side javascript should handle the upvote and downvote functionality and send the data to the server, which will store the decisions of the user.
My question is how do I send the data to the server and how can I send back if the upvote or downvote was successfully saved?
Client side:
window.onload = function() {
document
.getElementsByClassName("upvote")[0]
.addEventListener("click", function(event) {
// tell the server that the user upvoted
});
};
And on the server I would do something like this I guess
app.get("/", function(req, res) {
// save req data to a file
if (savedToFile) {
res.send("saved successfully");
}
else {
res.send("error");
}
});
I hope you are using pure javascript, then you can use Ajax to send get a request to the server like bellow inside the click event.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = this.responseText; // here you get the response
}
// handle 500 error state here
};
xhttp.open("GET", "server_url/upvote", true);
xhttp.send();
After you save the data to database send the response as bellow
app.get("/upvote", function(req, res) {
// save req data to a file
if (savedToFile) {
res.status(200).send("saved successfully");
}
else { // if got any error
res.status(500).send("error");
}
});
Related
I'm writing a chrome extension that is connected to an external php server. There are two main things that my chrome app does regarding the interaction with ther server :
1. read the stored comments from the server and show it on the extension
2. if a user writes a new comment, send it to the server so it can store the comment in the MySQL DB.
The problem I have is that while my extension has no problem fetching information from the server, it constantly fails to send new comments to the server. Since the reading function works, I assume that I have no problem with the CORS or anything.
This is the code I wrote to read the info from the server.
function getUrl() {
chrome.windows.getCurrent(function(w) {
chrome.tabs.getSelected(w.id,
function (response){
link = response.url;
//console.log(link);
hr = new XMLHttpRequest();
var info="link="+link;
//console.log(info);
hr.open("POST", "http://nardis.dothome.co.kr/nardis_core/comment_load.php", true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onload = () => {
const data = hr.responseText;
//console.log(data);
box.innerHTML += data;
//console.log(data);
};
hr.send(info);
});
});
}
This is the code I wrote to send the information to the server.
function sendPost(){
chrome.windows.getCurrent(function(w) {
chrome.tabs.getSelected(w.id,
function (response){
//const title = document.getElementById('title').value;
const description = document.getElementById('comment').value;
link = response.url;
//console.log(link);
hr = new XMLHttpRequest();
chrome.storage.sync.get(['u_id'], function(result) {
var info="description="+description+"&link="+link+"&u_id="+result.u_id;
hr.open("POST", "https://nardis.dothome.co.kr/nardis_core/mention_create.php", true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.send(info);
location.reload();
});
});
});
}
I’m trying to submit a form with data to a php file without reloading the page. I also have some js code that changes the form name and values when the next btn is clicked. I had 10 questions all on 1 page and I got it to work with PHP but now I’m trying to get 1 question per page. I looked in the network tab and it looks like the xhr requests are being sent but in my database.php file I wrote $user_anwser = $_POST[‘quiz_1’]; and var dumped it and I get a NULL value. Here is the ajax code.
form.addEventListener("submit", function(e){
if (ind < 10){
e.preventDefault();
} else {
form.setAttribute("action", "results.php");
}
let data = new FormData(form);
let xhr = new XMLHttpRequest();
xhr.open('POST', '../private/database.php');
xhr.onload = function() {
if (xhr.status === 200) {
// if the response is json encoded
let response = JSON.parse(xhr.responseText); // i get a parse error there
if (response.message == 'valid') {
// redirect here
}
}
// }
xhr.send(data);
}
});
I have a simple website that uses JavaScript to collect user input and sends data to PHP script (script is an external php file) via AJAX request. PHP script updates database with this information.
Now, i have a JS function on my website that i want to call only after PHP script is sucessfuly run and database updated. I don't need any data from database or PHP script, i only want to make sure that database is updated before calling this Javascript function.
This is what AJAX request looks like:
function ajax_post(){
if (typeof featureId !== 'undefined') {
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "parse_file.php";
var fn = featureId;
var vars = "featureId="+fn;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
hilites.destroyFeatures();
featureId = undefined;
}
else {
window.alert("Select polygon first");
}
}
What is the best way to do this? Some examples would really help.
Looking at your code, you simply need to call the function around this part:
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
// CALL YOUR FUNCTION HERE
}
}
The best solution is to use a Promise. However, this is not supported in IE 11, so you will need to use a polyfill on some browsers.
Here is an example using jQuery.
// This is the function you want to call after the script succeeds
function callbackSuccess() {
console.log('Done!');
}
// This is the data you want to submit to the PHP script
var myData = {
hello: "world"
};
// This is the actual AJAX request
$.post('/my-script.php', myData).done(function(){
callbackSuccess();
});
Add this to the end of your php save-function:
header('Content-Type: application/json; charset=utf-8');
echo json_encode(array('status' => 'SUCCESS'));
Making the call:
$.getJSON('url_to_your_php_file.php', function(data) {
if (data.status == 'SUCCESS') {
console.log('Save complete');
}
else {
console.log('oops, something went wrong!!');
}
});
It's possible to return something like ERROR, this will return:
console.log('oops, something went wrong!!');
You may try the following:
In php you can use return code from sql statement
echo $sqlResult = $conn->query($sqlStatement);
On Javascript, you can try the following
$.ajax({
url: 'file.php',
type: 'POST',
data: {
data1 : data1,
data2: data2
},
success: function(data){
if(data == success_code){
alert("Success")
}
}
Hope this helps!
Completing ajax request without errors does not mean that the data is saved to DB without errors.
Even if your PHP script fails to save the data, it probably echos some error message or even empty output as regular HTTP response, and it would show as success as far as the ajax request goes.
If your intention is to make sure that the data is really saved before calling the JS function, then the PHP script should containg enough error handling.
If you write the PHP script to return response status code based on the real outcome of save operation, then you can rely on those status codes in ajax response handling (success = ok, error = not ok).
Bu what I usually do, is that instead of using HTTP status codes, I echo "OK" or something similar at the end of succesfull PHP execution (and "ERROR" if there are any errors), and then check for those strings in ajax response handler (hr.responseText in your code).
Maby you have to try this:
setTimeout(function(){
//your function here...
}, 500);
I'm building a front-end interface for a back-end image edited process (don't know all the correct jargon).
Basically:
user should be able to upload an image file through the UI
which sends it to the server
where the image is edited in some way
then the UI should display the edited image
I'm using an XHR request with the POST method as shown below to send the image file to the server.
var fileSelect = document.getElementById('file-select');
var uploadButton = document.getElementById('upload-button');
uploadButton.onclick = function() {
this.innerHTML = 'Uploading...';
//---------------
var files = fileSelect.files
var formData = new FormData();
var file = files[0]
if (file.type.match('image.*')) {
formData.append('photos[]', file, file.name);
}
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://httpbin.org/post', true);
xhr.onload = function() {
if (xhr.status === 200) {
uploadButton.innerHTML = 'Upload';
}
else {
alert('An error occurred!');
}
};
xhr.send(formData);
}; //end on-click 'Upload'
<input type="file" id="file-select" name="photos[]"/>
<button type="submit" id="upload-button">Upload</button>
My question is: In general, once the image file is sent to the server, by the code above, when/how does the edited image get sent back?
Will it be sent back as part of the server response to my POST request, and thus accessible in my processRequest callback function (assuming the server is configured to process it that way)?
Do I have to send a GET request to get the edited file?
I do not have access to the server/back-end at this point in time, and just know how the UI is supposed to work.
So in my company we use SOAP API to get connect to our system, and I'm pretty well rehearsed in it and can use all the calls.
I just want to know where should I start if I want to build a test landing page that can execute the API queries.
I would prefer to do it with JavaScript if that is possible as we don't have PHP installed on our servers.
Looking for some direction of where to start - I'm simply going to take a value from a text box and place within the XML request and execute it :)
Any pointers appreciated!
<script>
function fireRequest(){
..
//parse your SOAP Request and set the request with 'dataContent'
...
var url = //your target gateway here Java/PHP or your web service recpetor
var postStr =//xml SOAP resquest ;
makeRequest(url, postStr);
}
function getXmlHttpRequestObject() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest(); //Mozilla, Safari ...
} else if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP"); //IE
} else {
alert("Your Browser does not support XMLHTTP");
}
}
function makeRequest(url, param) {
//If our readystate is either not started or finished, initiate a new request
//clearing all divs
receiveReq = getXmlHttpRequestObject();
if (receiveReq.readyState == 4 || receiveReq.readyState == 0) {
//Set up the connection to captcha_test.html. True sets the request to asyncronous(default)
receiveReq.open("POST", url, true);
//Set the function that will be called when the XmlHttpRequest objects state changes
receiveReq.onreadystatechange = responseHandler;
//Add HTTP headers to the request
receiveReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
receiveReq.setRequestHeader("Content-length", param.length);
receiveReq.setRequestHeader("Connection", "close");
//Make the request
receiveReq.send(param);
}
}
function responseHandler(){
if (receiveReq.readyState == 4) {
var response = receiveReq.responseText;
if(response){
//do what ever you want with the response XML
}
}
}
</script>
This would be enough for your case. use the methods at your page.