Ok so I am trying to make a program that allows teachers to edit/design a test and for students to take it. I made dropdown menues to select type of question and the category (history, english, etc.) and have textboxes to receive the question text. My question though is how to save this text and selections permanently. My initial thought was to change the contents of a js file variable, but javascript is client side. What is the easiest option as I need this quickly? Please just plain javascript/html, no jquery or jfiddle. Please explain in simple words :). I am no pro. PHP is ok but I do not know it so I will need it to be clear. If you could help, that would be fantastic as I and another guy have not found a simple solution ( at least to our minds).
If your users only use modern browsers (very unlikely), you can use local storage:
// Store
localStorage.setItem("lastname", "Smith");
// Retrieve
document.getElementById("result").innerHTML=localStorage.getItem("lastname");
Otherwise learn AJAX. It allows to save/read data from a server async. That means you don't have to change the page and you can save your data on every selection change.
And if you want to have it easy, use a Framework. Because this is a ajax request without a framework:
var xhr=new XMLHttpRequest(); // Initialize the Ajax request
xhr.open('get', 'send-ajax-data.php');
xhr.onreadystatechange=function(){ // Track the state changes of the request
if(xhr.readyState === 4){ // Ready state 4 means the request is done
if(xhr.status === 200){ // 200 is a successful return
}
}
}
xhr.send(null); // Send the request to send-ajax-data.php
And this is a ajax request with a framework (jquery):
$.get( "send-ajax-data.php", function( data ) {
});
You can use the above answer, and send your data using ajax call.
or
you can save your data in xml file in client side.
var newXml = "text to be saved"; // your data is here (form the xml).
//Sets the data in a hyperlink for download.
$('#DownloadLink')
.attr('href', 'data:text/xml;base64,' + btoa(newXml))
.attr('download', 'autounattended.xml');
or you can save the data in json too.
//creates javascript object
var sampledata = {'PkId' : 123, 'Name':'sudhansu' };
//Converts the object to json string.
var dataTobeSaved = JSON.stringify(sampledata);
then you can save this data to a file using the above method.
No matter how you slice it, there are a few things that you will need to learn in order to make this work. So instead of handing you code that you might not understand or be able to implement, I think you would be better served by some references and a simple explanation.
First, you will need to implement a CGI (common gateway interface). CGI can be implemented via Perl, PHP, Python, JavaScript (with nodejs). There are other languages that can be used, but these are the most common.
After you have a CGI script setup on your server, your client-side application can submit data to the server via a AJAX request or via a HTML Form submit. Most people use AJAX, but both options work.
Once the data is sent from the client and handled by the CGI script, you will want to be able to interface with the data. CRUD is an acronym for interfacing with data, it stands for Create, Read, Update, Delete. While it is possible to implement this by storing the data in a raw text file, it is generally considered a bad practice. Thus I would recommend that you look into using some type of SQL database, MySQL, PostgreSQL, SQLite are a few that are relatively easy to implement (SQLite being the easiest of the three imo).
Related
I need to get user details behind the scene when he is accessing our browser based application. So a plug and play JavaScript component need to be created which can be easily embedded in the header of the web page. The logic of capturing the data points should sit on server side. So an API can be invoked from this component and then "User-Agent" header can be leveraged in that API to get the data points.
However, not all data points can be Identified from User-Agent such as language, screen resolution, color depth, etc. Capturing these attributes need an execution of JavaScript on client side.
Two approaches:
With Redirect(If allowed and component is an iFrame so that parent page is not reloaded)
When the component loads initially, redirect it to another page which will contain the JavaScript that will capture these details and it will be auto submitted and sent to the API which will use the data points and then redirect to the component with a flag to not perform the capture activity again.
Without redirect
So, The approach am thinking is to have a component in which, during onLoad event, an API will be invoked and the JavaScript code (To capture the data points from client) will be returned as response. Then this returned JavaScript will be executed on client and result will be saved in a hidden field. There will be an Allow button(part of requirement to take user consent) in this component, which when clicked, the data from the hidden field will be submitted to the API.
Please review the approach and let me know if it sounds good and viable.
I bet that the second approach would be better. And even better, you don't actually need to write a dedicated API to generate the JS file s required for tracking.
Now, write a simple JavaScript file which will collect the required data. I'll name this as track.js.
function collectAndSubmit(){
var data = {};
// Then collect the required data
data.screenWidth = window.innerWidth;
data.screenHeight = window.innerHeight;
data.preferredLanguages = navigator.languages; // In the form of an array
// Submit the data through XHR
var xhr = new XMLHttpRequest();
xhr.open("POST", "https://example.com/track.php");
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); // Note that we're sending a JSON request
xhr.send(JSON.stringify(data));
}
The last 6 lines of code will send all of the collected data in JSON format to a server. However, I don't know which server are you using (e.g. PHP, Node.js) since they have different ways to parse the JSON data. For example, PHP you can use $data = json_decode(file_get_contents('php://input')); to obtain the requested data or var data = req.body; if you're using Node.js with Express and the body-parser module.
The best part here is that track.js doesn't have to be generated by an api, e.g. by performing a GET request to /gettrackingscript. Instead, you can serve this as a static file, putting it on your CDN and so on.
And now, what is the best way to download this track.js file? Well, it depends on how would you use it. You can simply include a <script src="track.js"> tag when the page loads and call the collectAndSubmit() method when you would like to send the data. Or by getting the script through another XMLHttpRequest and execute them with eval().
Since you're planning to redirect the user after all of the data has been sent, you don't have to refresh the page unless if you're sticking to the MVC (mode-view-controller) pattern when building the site. After the xhr.send(), you can set your backend server to send additional data back to the browser by sending a HTTP response, which you can parse it here by using:
xhr.onreadystatechange = function() {
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
// Assuming that you're using JSON
var additionalData = JSON.parse(xhr.responseText);
}
}
I'm want to (or think I need to) use AJAX to accomplish what I intend.
When clicking on a specific link in a list of links, I want to fill the HTML markup below with content of specific subpages. The data is naturally somewhere in the database and actually easily accessible with the CMS's API (I'm using Processwire).
I'm quite new to coding and especially AJAX and all documentation I find online only mention it in combination with a JSON file that would be loaded via AJAX.
However, I don't have a JSON file on the server, that means, according to my understanding, I would need to
store the data I need in a multidimensional php array,
use json_decode to create and then save that JSON-file on the server,
load that file via AJAX and process through more JS.
Let alone keep that JSON-file updated (or create a new one and delete the old one?) since new content will arrive periodically. It seems unnecessarily complicated to me, but what do I know.
There's got to be a better way…
Any help is appreciated.
AJAX is simply a way to make a request to the web server for information.
When you make an AJAX request you ask for a response from a file on a server. So, you can send an AJAX request to a PHP script for-instance.
The PHP script could return anything, JSON is common and very widely used response format, but XML might be another one you've encountered.
So, your request for information is made using AJAX, and the response you get back is JSON.
You don't need to store a JSON file on your server. You just need to make an AJAX request that returns current data in JSON format.
AJAX allows you to do asynchronous HTTP requests.
You can of course ask for a json file, but you can also (for example) call an API.
I suggest you start by reading the the getting started guide for AJAX in MDN:
https://developer.mozilla.org/en-US/docs/Web/Guide/AJAX/Getting_Started
I think I have a tough one for you guys. Or at least it's been tough for me. I've been searching for the best way to do this in Stack Overflow and everyone that has asked has been given a different response.
I have this code that is accessing an API and calling a maintenance list of all the vehicles in a fleet.
function getMaintenanceList() {
var settings = {
"url": "API URL HERE",
"method": "GET",
"timeout": 0,
"headers": {
"Authorization": "Bearer token here"
},
};
$.ajax(settings).done(function (response) {
// The response the API sends is a JSON object.
// It is an array.
var jsonMaintenance = response;
var parsedJson = JSON.stringify(jsonMaintenance);
//Left over code from when I was trying to
//pass the data directly into the other page
// I was unable to do so
//return jsonMaintenance;
//Left over code from when this was in a PHP file
//and I was posting the stringified response to the page
// for testing purpose
//I had to disable CORS in Google Chrome to test the response out
//console.log(jsonMaintenance);
//document.getElementById("main").innerHTML = parsedJson;
});
};
The code above works well. What I was attempting to do here was write the stringified response to a file. Save that file in the server. Call it from another page using JavaScript and save it as an object in JavaScript, parse it using JSON.parse(), and then pull the required information.
Here's an explanation as to why I'm trying to do it this way. When I call the maintenance list from the API, I'm getting the entire maintenance list from the API, but I need to be able to display only parts of the information from the list.
On one page, we'll call it vehicle-list.php, on it I have a list of all the vehicles in our fleet. They all have unit numbers assigned to them. When I click on a unit number on this page it'll take me to another page which has more information on the vehicle such as the VIN number, license plate, etc. we'll call this page vehicle-info.php. We're using this page for all the vehicles' information, in other words, when we click on different unit numbers on vehicle-list.php it'll always take us to vehicle-info.php. We're only updating the DOM when we go to the page.
I only want to include the information specific to each vehicle unit in the page along with the other info in the DOM. And I only want to call the info from the API once as I am limited to a certain amount of calls for that API. This is why I am attempting to do it this way.
I will say that what I originally wanted to do was get this JSON response once every 24 hours by using a function in vehicle-list.php save the reponse as a variable as seen above var jsonMaintenance = response; and then just access certain parts of the array every time a unit number is clicked. However, I have been unable to access the variable in any other page. I've written many test files attempting to call jsonMaintenance without success so I've been trying to to just save it as a text file to the server and I haven't been able to figure that out either.
After explaining all of the above. My questions are these:
How do I best manipulate this data to accomplish what I want to accomplish? What would be the best standard? Is the above code even the right way to call the data for what I'm trying to do?
There doesn't seem to be a set standard on accomplishing any of this when I search on Stack Overflow. I'd like to be as efficient as possible.
Thank you for your time.
there is a lot of ways how you pass your data through your website after getting it in from an api call, the best approach is to store these information in a database and call it back in which ever way you want, you can do that as far as you are using php, you can store it to sql or to access, if you don't want to store these information in a database like in sql or access, then best way is to store it to localStorage and call it back whenever you want.
I will show you briefly how you can do that, if you want better explanation post an example of your returned data.
to store an item in localstorage use,
localStorage.setItem('key', 'value');
to call an item back from localstorage use,
var somevar = localStorage.getItem('key')
to remove specific item from localstorage use,
localStorage.removeItem('key')
to clear all items saved to localstorage use,
localStorage.clear()
be aware storing the data to localStorage is only at the station you are using
I would do it somehow like this.
Call the maintenance list from the API with the server side language of your choice which seems to be PHP in your case. Lets say the script is called: get-list.php. This can be triggered by a cron job running get-list.php in intervals limited to the certain amount of calls that you are allowed to do for that API. Or if you are not able to create cron jobs then trigger the same get-list.php with an AJAX-call (eg jQuery.get('sld.tld/get-list.php') - in this case get-list.php have to figure out if its the right time to call the API or not).
Now that you have the data you can prepare it as you want and store it as a JSON-string in a text file or database of your choice. If I get you right you have a specific dataset for each vehicle, which have to be identified by an id (you named it "unit number") so your JSON would look kind of: {"unit1": { property1: "val1", property2: "val2" }, "unit2": { property1: "valXYZ", property2: "valABC" }} or alike.
Now when you link to vehicle-info.php from vehicle-list.php, you do it like so: ancor or similar as well. Of course you can also grab the data with AJAX, its just important to deliver vehicle-info.php the corresponding unit number (or id - better to say) and you are good to go.
vehicle-info.php now have all there is to render the page, which is the complete data set stored in text file or data base and the id (unit number) to know which part of the whole dataset to extract.
I wanted to give you this different approach because in my experience this should work out just so much better. If you are working server side (eg PHP) you have write permissions which is not the case for JavaScript-client side. And also performance is not so much of an issue. For instance its not an issue if you have heavy manipulating on the data set at the get-list.php-level. It can run for minutes and once its done it stores the ready-to-use-data making it staticly available without any further impact on performance.
Hope it helps!
If i ran into a similiar problem i would just store the data in a database of my own and call it from there, considering you are only (willing/abe/allowed) to request the data from the API very rarely but need to operate on the data quite frequently (whenever someone clicks on a specific vehice on your applicaiton) this seems like the best course of action.
So rather than querying the data on client side, I'd call it from server, store it on server and and have the client operate on that data.
I am developing a query PHP enabled chat, currently am using ajax to pull data from the server and display it in the chatbox but this makes use of multiple ajax requests to the client computer which causes it to slow abit....
This is what I am doing using ajax and yii2
function getdata() {
$.get("controller/action").
done(function(){
//process json
$("#chatbox").html(data);
})
}
then am using
windows.setInterval(getdata(),1000);
Are there better ways to fetch this son data without using ajax and jquery
I have checked on This link buts its not very helpful
You can use socket.io or websockets api which is an alternate option to ajax, So, by using socket.io, jquery, php OR nodejs one can build one to one private chat without using ajax, following links will help you out how to build private chat.
socket.io
WebSockets
Private chat reference 1
Private chat reference 2
A better approach is using nodejs instead of php. You can check this link for a really nice implementation of chat which you can use.
While php chat has performance issues like you mentioned, nodejs doesn't because instead of polling the messages it pushes them to the client when there is something to push. And also you receive ready to use solution right out of the box (of course you have to modify it) which will save you development time.
But if you still want to go with the php way, then you have these options:
jquery + ajax (like you are doing it right now)
php sockets - here is an example of php chat using websockets https://www.sanwebe.com/2013/05/chat-using-websocket-php-socket. This approach has its pros and cons. One of the major cons is that is not supported by old browsers and may be the setup process is not that easy. But I'll prefer it over the ajax requests.
You mention getting data from the database, but one could argue that, for the purpose of a chat application, the database is incidental. Maybe you want to store the chat history and the database is a natural place to do so, but the primary functionality is to transmit messages. So you are using the database as some kind of message buffer.
Websockets seems the best option, as others have mentioned. If you want PHP server-side, in addition to the Kraken framework as mentioned in a comment to your question, you can take a look at the Ratchet library. They have a tutorial for a simple chat in their site: http://socketo.me/docs/hello-world
Basically, you need another server-side process (in addition to your webserver) to receive and broadcast the chat messages. Following that tutorial, in the onMessage method of the Chat class you can do the insert in the database if needed, preferably asynchronously.
Client-side, you will need to connect to the websocket using Javascript. Simple example:
var conn = new WebSocket('ws://localhost:8080');
conn.onopen = function(e) {
console.log("Connection established!");
};
conn.onmessage = function(e) {
console.log('Message received: ' + e.data);
addMessageToChatbox(e.data);
};
$('#yourChatInput').keypress(function(e) {
if(e.which == 13) { // "enter" was pressed
conn.send($(this).val());
$(this).val('');
}
});
function addMessageToChatbox(message) {
//
}
You can do a trick, suppose data is not json it is javascript file declaring single variable now you have to add it to document such as
below is your data.php(javascript generated by php)
in php
echo 'var x = {"name":"Anshuman"}'
In javascript
var s = document.createElement( 'script' );
s.setAttribute( 'src', 'data.php');
s.onload=callback;
document.body.appendChild( s );
function callback(){
console.log(x);
}
There aren't any sensible ways. You have to bring the new data in somehow right?
The to ways to do that are by reloading the page or by Javascript / Ajax to avoid the reload.
You could make the update one sided so that when Person A writes to person B the request is performed on the submit of the new message. This would mean that no new messages are retrieved unless one is sent. (Not practical)
Another method would be to have a last message time noted somewhere on its own and you could repeatedly check for that.
Should that time change you could fetch new data then but that would not fix the amount of requests... only the amount of data being transferred.
I suggest you look at the size of the data from the json/php. Have you ran tests to see how long that is taking or how it is performing?
I could refer you to this post which is using NON jquery requests if you like.
I'm building REST web app and my server side Java code expects request body to have pure JSON string.
My goal is to use regular HTTP POST method (not ajax) and set JSON into request body message.
If I use ajax, it is very simple. Something like:
var jsonInput = '{"foo":"bar"}';
ajaxRequest.setRequestHeader("Content-Type", "application/json");
ajaxRequest.send(jsonInput)
But I want to use regular HTTP POST.
Looking at the thread below, the answer is to create a form with hidden input field and put JSON in to the input field and have server side code handle the rest.
JavaScript post request like a form submit
I tried that and it works just fine but do I really have to bother creating new form and input field to accomplish this? Or is there any other way available?
NOTE: I don't want to use JQuery or Prototype framework. Just simple Javascript.
FORMs only allow for name-value pairs to be submitted, and so your JSON needs to be inserted into one such pair.
Yout can read about this at w3.org
As a solution, what about using xhr to send the data to the server, exchange it for some token, and then direct the user via a regular GET to a url passing the token?
This should fit with the REST paradigm too.