I'm following a knockout.js tutorial for loading data from the server and I'm a bit confused on where the query is actually coming from. The tutorial can be found here and the specific bit of code I'm talking about is on page 2.
I understand the necessity for using ajax, but I'm not actually sure how to make a query based on what they're doing.
$.getJSON("query/tasks", function(allData) {
var mappedTasks = $.map(allData, function(item) { return new Task(item) });
self.tasks(mappedTasks);
});
The description of what is taking place:
On this server, there's some code that handles requests to the URL /tasks, and
responds with JSON data. Add code to the end of TaskListViewModel to request that
data and use it to populate the tasks array:
So, say I'm working with PHP and want to make the following query to find the tasks:
$tasks= mysql_query("select * from tasks");
Where would I place this query? I see it's somehow related to /tasks, but what's going on here exactly?
edit, would I do something like this? So essentially the $.getJSON request is calling a function residing at query/tasks in this case?
//assuming this is on query.php
Class query{
function tasks(){
$task = mysql_query("select * from tasks");
return $task;
}
}
Essentially what is happening is that you are making an AJAX call to some endpoint on your server that will return JSON data. I haven't worked with PHP in quite a while, but you are basically requesting a resource on your server. Let's say that your website is http://www.myawesomesite.com. If you were to make an AJAX request to "/tasks", there will be a request to http://www.myawesomesite.com/tasks that is expected to return JSON data.
That resource can be another page, a web-service of some kind, whatever you have available. I work primarily in the ASP.NET MVC space, so my experience is different from PHP, but the idea is the same. You are making a request to a resource on your server to return JSON data. Whatever that resource is is up to you. HTH!
Related
I have a problem and hope you can help.
Ii have a status.PHP file containing a js.
STATUS.PHP
<? ..stuff... ?>
<html>
<head>
<title>BCM Status Page</title>
<script src="jquery-3.3.1.min.js"></script>
<script src="updater.js"></script>
</head>
<body bgcolor="#305c57" onload='init();'>
As you can see in the html ihave included a JS, during "onload" i'm calling the init() function of the javascript called updater.js
Now in the UPDATER.JS
function init() {
setInterval(read, 2000)
}
function read() {
$.ajax({
type: 'POST',
url: 'readDB.php',
dataType: 'jsonp',
success: function (data) {
console.log(data);
var json_obj = $.parseJSON(data);
console.log(json_obj[0].gwnumber);
},
error: function () {
console.log("Error loading data");
}
});
}
I'm doing an ajax call to the readDB.php that is working as intended, infact i have the correct value in the json_obj.
My question is: how can i get the json_obj value and pass it to the status.PHP file that is the one who's including the JS too?
Hope you can help. TY
Ok, there is a lot to say in this argument, but i will be the briefiest possible.
first things first
php and Javascript are two different programming language with a completely different paradigm.
The first is a back-end focused programming language;
Javascript instead is more front-end focused, just for entirety i have to mention that JS is used also for the backend part with a special eviroment called Node.js
back to the problem, the things that you are trying to do is not impossible but is excactly as you asked, your're idea (if i got it) was to pass the data from the js to the php like a parameter in a function...
the thing is that the php is elaborate and renderizated before in the server and the javascript is executed in the client, in the client web page there is no more footprint the php. This process is described very well at this link: http://php.net/manual/en/intro-whatis.php
The possible solution is:
FRONT-END(js): make another ajax call(request) to the same page that you are displaying with all the data that you want to elaborate.
BACK-END(php): controll if this request has been made, then access the data with the global variables $_POST & $_GET (depending on the type of the request), then elaborate this data.
if I can I suggest you to make a check if the manipulation that you want to do on those data need to be done in the server-side and not by the js!
Consider the order of execution:
User visits status.php
Browser requests status.php
Server executes status.php and sends response to browser
JS requests readDB.php
Browser requests readDB.php
Server executes readDB.php and sends response to browser
JS processes response
Go To 4
By the time you get to 7, it is too late to influence what happens at step 2.
You could make a new Ajax request to status.php and process the response in JS, but since status.php returns an entire HTML document, that doesn't make sense.
You could use location to load a new page using a URL that includes status.php and a query string with information from the Ajax response, but that would making using Ajax in the first place pointless.
You should probably change readDB.php to return *all** the data you need, and then using DOM methods (or jQuery wrappers around them) to modify the page the user is already looking at.
The simpliest and fastest (maybe not the sexiest way) to do it :
create global variable var respondData; in STATUS.PHP
within you ajax request on success function assign your data callback to it
respondData = data;
Now you have an access to it from every place in your code even when the ajax request is done. Just bare in mind to ensure you will try to access this variable after the page will fully load and after ajax will process the request. Otherwise you will get 'undefined'
I am aware of how REST calls work from within a Java Web application. E.g. when a URL is reached its method will be called using HTTP.
For example:
#GET
#Path("people/{id}")
public Response getPersonWithId(#PathParam("id") id) {
//return the person object with that Id
}
What I am unsure of is how this links to the front end?
Is the role of the UI ( i.e. javascript ) just to take a user to the specific URLs so that the back end methods can be called?
E.g. if a user presses a "get details" button, does the button just redirect them to this URL that deails with returning the details, and the back end functionality is then called?
WebService is not actually linked or tied to the front end similar to webapp. Instead, webservice is a service that provides result in the form of JSON/XML, Plain text Format according to request type(get, post, update, delete) and hence, the service can be used by any multiple front end application(not only web application but also smartphone app, desktop app etc.). Also, webservice can be on totally different server.
Let me give you a scenario:
Suppose, you have an front end web site ABC-Website and a backend
webservice on host: www.xyzservice.com/api with following methods:
/product - get request that return all product as list in json format.
/product/id - get request return product detail given id in json
format.
Now, if you simply type in browser www.xyzservice.com/api/product then
all product list will displayed in json format in the browser. That means, You can also read data from webservice directly in browser without front end system and i.e. webservice is not linked/tied to any front end.
Now, you want to use this webservice in your ABC-Website to display all the product list:
You call www.xyzservice.com/api/products and get JSON object that you can use to display in your html page.
<button type="button" onclick="getProducts()">Click Me!</button>
function getProducts(){
$.ajax({
type : "GET",
contentType : "application/json",
url : "http://www.xyzservice.com/api/product",
dataType : 'json',
timeout : 100000,
success : function(data) {
// now you have "data" which is in json format-same data that is displayed on browser.
displayDate(date);
},
error : function(e) {
//do something
},
done : function(e) {
//do something
}
});
}
function displayDate(){
//your codes to parse and display json data in html table in your page.
}
Lets say that your client is a website and you have a Java API.
In the javascript of your website you could do a request to the backend to retrieve the data and then present it to the user. Your javascript (using jQuery as an example) could look like the following:
// here it prints the data retrieved from the backend route (/people/{id}
$.get('http://localhost:3000/people/3',function onDataReceived(data) {
console.log(data);
})
As pointed out, jQuery is not necessary. Here is an example using regular javascript:
this.getRequest('http://localhost:3000/people/3', function onReceived(data) {
});
function getRequest(url, callback)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}
in javascript, usually you want to do these request at the background your webpage.
Im gonna try to explain this with an example:
Imagine you have a page that displays a list of cars for sell which can be fetched from the web service provided by java back-end. The back-end have an url that will respond to GET method with a JSON (or XML) object.
What you have is a HTML file where you write a structure for the displayed data and also includes a javascript file that asynchronously calls this webservice, GETs the data, parses the JSON and then it can manipulate it to the form you want to display it on the page.
In different example you can validate forms on the background, or save the forms or do any other stuff that works with the web service API.
For making these asynchronous request you can use different libraries.
Most used is ajax included in jQuery framework or fetch as n standalone library.
so i've been looking at how to record and send client-side data to a php server.
i'm not sure of the correct terminologies, but i think that using an ajax call to send a post to the php server is the most elegant way to solve this problem.
so i decided to implement this data exchange:
$("#"+activityInfo.ID).click(function(){
window.open(activityInfo.URL+"userId="+$("#userid").val()+"&activityId="+activityID+"&classId="+classID);
classid = classID;
activityid = activityID;
$("body").append("class: " + classid);
$("body").append("id: " + activityid);
$.post('http://chemcollective.org/chemvlab/php/updateProgress.php', { 'cid':classid , 'aid':activityid } );}); //i think this is the important line that sends the data
and the corresponding php file (updateProgress.php)
$class_id = $_POST['cid']; //receives the data
$activity_id = $_POST['aid'];
i'm not sure why this is the case, but class_id and activity_id variables always return an empty value.
i understand somewhat that the client-browser is on a page that is preloaded by information from a php server. but there were posts that said this is a possible way to communicate back to the php server with information from the client. i'm not really sure what is going on b/c at this point i don't really know what questions to ask.
one of the example explanations that i had been following:
Ajax passing data to php script
thanks for the help.
i've also played around with start_session() and storing/loading session variables as a way to transfer data information. this works but only for php <-> php communication. it does not for saving javascript variables, so i couldn't really use $_SESSION = ..... in my javascript code.
you need to get the cid and aid outside of the single-qouts while using $.post! try this:
$.post('http://chemcollective.org/chemvlab/php/updateProgress.php', { cid:classid , aid:activityid } );
I need to use a javascript variable value in server side.
Example:
JavaScript
var result = false;
CS Code
if(result)
{
Console.Write("Welcome..")
}
else
{
Console.Write("plz try again..")
}
Note
I don't want to post a hidden field.
With each request, any server side code will run and then any client side code will run. You can't switch between them at will.
Your options are:
Provide all the data to the client in the first place, then use JS to decide which of them to keep/delete/show/hide/etc
Use Ajax to make a second request to the server with the data you get from JS, return content, and then do something with that content in the JS callback function.
Make a second request to the server and load a complete new page.
Remember to build on things that work.
best way to do this use hidden fields...
i have a 5 stars rating system, on javascript!!! bau i want to update mysql table, when clicking on stars!!! can somebody tell me how can i update the table!!!
thanks. . .
Respond to a click by sending an ajax POST to the server. With Prototype, this might look like this:
document.observe('click', handleDocClick);
function handleDocClick(event) {
var star;
star = event.findElement('.star'); // <= assumes images have the class "star",
// use any CSS here you like
if (star) {
event.stop();
new Ajax.Request('some_url', {
parameters: {star: star.id},
onSuccess: handleSuccess,
onFailure: handleFailure
});
}
}
...and define handleSuccess handleFailure as you see fit. More on the unofficial wiki and in the API docs.
You can also use jQuery, YUI, Google Closure, and many many other tools, or use the XMLHttpRequest object itself directly.
That's the client side. On the server side, you'd have to have a page (PHP, JSP, servlet, ASP.Net, FastCGI, old CGI, Perl, Python, ...) that can receive HTTP POSTs and handle them by updating the underlying MySQL data.