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.
Related
Can I dynamically edit the url of the datatable depending on the value of the “Value” field of the search form in another file?
For example:
{ view:"text", label:"input data", value:"apple" }
In datatable.js
url: 'resource->/api/archive/apple'
Okay, I was told that I can send AJAX requests, but now I can't figure out how to get them correctly on another page
Sending:
webix.ajax().post('apples', get_form())
routie('apples')
In devtools I get the form value
I'm trying to get the formData value to substitute it in the URL
function get_data() {
let result;
webix.ajax("apples").then(function (data) {
data = data.text();
result = data;
});
return result;
}
URL
url: 'resource->/api/archive/all/'.concat(get_data()),
On the backend side, this controller works well, but I can't call it from the front side. I'm just learning frontend, so any help would be greatly appreciated.
In general, the way to do this is: When the value is changed (the onChange event), call clearAll() and load(newUrl) methods of the datatable. You cannot change the url property at runtime (well, you can, but it won't work).
As for different files, people usually build SPAs with Webix, so files here might be modules, not pages. Do you use Webix Jet? If yes, then communication between the form and the datatable can be done via the app event bus. If not, then they can communicate directly (import both files in some other file and do it there). If this is a multiple-page app, then yes, you do need some server side communication between them (maybe even with sockets).
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 on Linux -both browser side & server side- with a recent Firefox 38 or 42 if that matters; this question gives more context, and the github GPLv3 project containing my code. It is not a usual Web application (it would have usually one, and perhaps a dozen, of simultaneous Web users). I am writing or generating both server & browser side code
Let's suppose I have some HTML5 code like
<div id="mydyndiv_id"></div>
I am making an AJAX request with JQuery. On success it should insert some (AJAX generated) HTML element, e.g. <b>bold</b> (in reality it is a much bigger HTML fragment with nested <span>-s whose content is dynamically generated from the POST argument of the AJAX request), into that div and call some other Javascript function doit, e.g. doit(42) only once just after the AJAX request (e.g. that function would clear some other <textarea> in my page, and the 42 argument is provided by the AJAX response). I can change code both on server side (e.g. alter the AJAX processing) and on browser side.
What is the most idiomatic way to achieve that?
making a JSON AJAX which contains both the inserted HTML & the function argument, so the AJAX response could be {"text":"<b>bold</b>", "data": 42}" of Content-type: "application/json" and the Javascript code would be
$.ajax
({url: "/someajax",
method: "POST",
data: {"somearg": "foo"},
datatype: "json",
success: function(jsa) {
$("#mydyndiv_id").html(jsa.text);
doit(jsa.data);
}});
this is rather heavy, the server should double-encode HTML&JSON the HTML fragment: it needs first to construct the <b>bold</b> fragment -with HTML encoding, and then to construct the JSON object and send it.
making an HTML AJAX which has some <script> element. The AJAX response would be of Content-type: text/html and would contain <b>bold</b><script>doit(42)</script>, and the Javascript code would be
$.ajax
({url: "/someajax",
method: "POST",
data: {"somearg": "foo"},
datatype: "html",
success: function(ht) {
$("#mydyndiv_id").html(ht);
}});
this might be wrong, since the doit(42) function could be perhaps called more than once and is kept in the DOM and I don't want that
making a Javascript AJAX; the AJAX response would be of Content-type: application-javascript and would contain:
$("#mydyndiv_id").html("<b>bold</b>");
doit(42);
with the AJAX invocation in Javascript being
$.ajax
({url: "/someajax",
method: "POST",
data: {"somearg": "foo"},
datatype: "script",
success: function(jscode) { /* empty body */ }
})
This is brittle w.r.t. errors in doit(42) (see this question; the only debugging technique I found is lots of console.log and that is painful) and also requires double encoding on server side.
Of course, any other technique is welcome!
PS. If you are curious, the code is commit a6f1dd7514e5 of the MELT monitor (alpha stage) and you would try the http://localhost.localdomain:8086/nanoedit.html URL in your browser; this software (which is also a specialized HTTP server!) would have only very few simultaneous Web users (usually one, perhaps a dozen); in that sense it is not a usual web application. In my dreams it could become a workbench for a small team of (C & C++) software developers, and the GUI of that workbench would be their browser.
These different approaches have pros and cons, but generally the first two options are more advisable, let's see:
JSON AJAX
First of all, working with templating on your server is the right approach. If you use this method you will be able to pass more flexible data from your server to your client as you can e.g. use {"text":"<b>bold</b>", "data": 42, "more_data": 43}".
You are not bound to use just the data at the moment you initially create the service but expand passed data easily.
HTML AJAX
This method is simple and if you would like to have a service for every single piece of data you need to pass, rather than a service for multiple pieces, this is the preferable choice. In difference to the JSON AJAX method, you will not be able to expand here and if needed, you'll naturally have to create a new service for passing new data.
Javascript AJAX
Altough it is possible, tis method is rather unadivsable, as you can not maintain your application in a reasonable way, as your templating is client-side. See what Peter-Paul Koch says here:
Although templating is the correct solution, doing it in the browser is fundamentally wrong. The cost of application maintenance should not be offloaded onto all their users’s browsers (we’re talking millions of hits per month here) — especially not the mobile ones. This job belongs on the server.
Further reading : Why client-side templating is wrong.
First approach looks good for me, but generally it's a little bit ugly to transfer raw HTML via AJAX, if you have to transfer raw HTML it's better to use techniques called PJAX, see jquery-pjax plugin for more information of how to use and customize it.
From my point of view best approach would start using jquery-template to avoid transferring HTML over AJAX and start transfer only object witch would be rendered to template on frontend.Call doit method within handling success is ok until it use data provided in response.
I would rather go with a variation of first approach. But, it depends on the kind of generated HTML that you are currently returning from the server-side.
If it is a simple element, then you could just return a JSON object from server with one of the properties identifying the element.
For example, the response from the web-service would be like:
{'elem': 'b', 'text': 'bold', 'value': '42'}
And you consume that in the AJAX call like this:
$.ajax({
datatype: "json",
...
success: function(response) {
// create the required element client-side
var elem = document.createElement(response.elem);
// use other properties of the response object
elem.textContent = response.text + doit(response.value);
// add the element to your div
$('#mydiv-1')[0].appendChild(elem);
}
});
Where doit is the Javascript function that is already part of your client-side code-base and you just use the arguments returned by the web-service.
Alternatively, if your generated HTML is a complex fragment, then you need to identify common patterns and use client-side templates to transform the returned data into presentation.
For example, your client-side template may look like this:
<script type='text/template' id='tmpl'>
<div><h3></h3><p></p><h5></h5></div>
</script>
Your web-service returns something like this:
{'title': 'title', 'text': 'paragraph', 'value': '42'}
And you consume that in the AJAX call like this:
$.ajax({
datatype: "json",
...
success: function(response) {
// clone the client-side template
var template = $('#tmpl').html(), $elem = $(template);
// append to your div
$('#mydiv-2').append($elem);
// populate the cloned template with returned object properties
$elem.find('h3').text(response.title);
$elem.find('p').text(response.text);
$elem.find('h5').text(doit(response.value));
}
});
This way you avoid returning generated HTML from your server and manage the presentation details at the client-side only. Your web-service needs not to know the presentational aspects and deals only with raw data (consuming or spewing). The client-side code gets data from the web-service and deals with using and/or presenting that data as part of the client-side app.
Demo for both the variations: https://jsfiddle.net/abhitalks/wuhnuv99/
Bottom-line: Don't transfer code. Transfer data. Code should then use that data.
Hi I want to create a page where it monitors(view) or render the value of the variable inside the controller dynamically as the iteration of variable goes by.
view.html.erb
<a id='get_value' class="btn">Run</a>
<ul id="value_variable_from_controller"><ul>
<script>
var getTheValue=function(){
$.ajax({
type:'GET',
url:'/run/results',
success:function(data,status){
<!--how to dynamically UPDATE the value_variable_from_controller?-->
alert("Successfully");
}
});
}
$(document).on("click","#get_value",getTheValue);
</script>
And here's my controller where i iterate the value of x,
results.rb
x=0
5.times do
x++
sleep(1)
#HOW TO RETURN THE VALUE OF VAR X EVERY UPDATE?
#render :json => x, :status => :ok #do i need to have a loop in js?
end
Many Thanks.
If I understand you correctly you want to update the value in the HTML document every time it is updated on the server, correct? There are ways to accomplish this, although the transitioning of state between client and server is usually initiated by the client. 1
To combat this, websockets are currently the most popular approach - basically opening up a two-way communication pipe between the client and the server. Of course, for your simple example this might be overkill (unless you require heavy real-time interactions between the client and the server - then it's certainly worth taking a gander at) - and something like polling might be more suitable (which is indeed initiated by the client), although it will generate a large number of requests.
You might also consider long polling which only opens one connection.
Polling is a technique in which the client calls the server requesting data at a certain interval, which would work for your situation. From the code you posted it also seems like you want it to be possible to fetch the value by clicking on the #get_value link, which can utilise the same method as the long polling service. Here's an example:
// in your view/javascript
$(document).ready(function() {
function getValue(trigger) {
$.ajax({
type: 'GET',
url: '/run/results/',
success: function(data, status) {
$('#value_variable_from_controller').text(data.x);
if(trigger) {
setTimeout(getValue(true), 1000); }
}
)} // end AJAX
} // end getValue
// binding the action to your link as well
$('#get_value').on('click', function(event) {
event.preventDefault();
getValue(false);
});
// start the polling
getValue(true);
});
# in your controller
#x = 0 # initial value
def results
#x++ # increment every time this action is called
render #x.to_json
end
This way the client initialises the data flow, and the server mutates state in response to a client request - which is the norm in a client/server architecture.
1 The client–server characteristic describes the relationship of cooperating programs in an application. The server component provides a function or service to one or many clients, which initiate requests for such services. (http://en.wikipedia.org/wiki/Client%E2%80%93server_model)
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!