I have a javascript array which stores seat numbers (in a cinema), which are selected by the user via clicking and added to the array each time using a function. I want the page to show the total cost of these seats, which means accessing an sql table inside some php.
So I have e.g. seatNumbers = ["a1", "d6", "e3"] and three sql query like 'select cost from seat where seat_number='a1';'. The function that adds to the array on clicking a seat and prints the seats is something like:
var seatArray = [];
function addSeat(seat) {
seatArray.push(seat);
document.getElementById("textarea").innerHTML="Seats : ";
for (x in arraytest) {
document.getElementById("textarea").innerHTML+=arraytest[x];
document.getElementById("textarea").innerHTML+=" ";
}
}
And I want to show the total cost in the HTML.
I'm wondering if what I'm trying to achieve is possible? What would be the general method and would I need to load a new page instead? And if it's not possible, what would be a better way to go about this?
Your question is very broad, and to answer it, quite some stuff needs to be known and used.
What you want is very possible though. In fact, there are technologies that in their core focus on providing solutions to problems like yours! What you need is some solid info (and possibly experience with) AJAX and maybe even REST. By using AJAX your page wont have to reload, and in your situation AJAX is probably the best choice anyway.
To point you in the right direction: AJAX javascript W3Schools Tutorial and PHP AJAX W3Schools tutorial
Then, use jQuery to make it all a LOT easier: jQuery (i'd go for 1.x)
You'll have to create an API that accepts an HTTP (preferably GET) request and returns the cost for the seat that you refer to in your URL like (more REST like, should return a whole seat object with price included): /seat/200, or (not REST like)/seat/cost/200).
Your choice if you want to follow (if you haven't read up on it, possibly confusing) REST rules. In your situation i'd just begin with some good old AJAX, it just works and is even better suited for stuff like this.
You should use AJAX. Try using jQuery library and ajax function.
Covert Your array with seats on JSON string and send it by AJAX to page which check the whole price. Then, You can update Your HTML code with total cost.
var json_data = '{...}';
$.ajax({
url: "total_cost.php",
dataType: "json",
type: 'POST',
data: { json: json_data },
success: function(response) {
// .. on success
var json_response = jQuery.parseJSON(response);
var cost = json_response.total_cost;
}
});
Related
I am writing an application that allows a user to dynamically select which columns they want to pull from our database (all public internal data) as well as customize their logic (WHERE Clause).
The result sets from these queries can be anything from a 10 records to our whole table of over 35,000 records.
On load of the result page, I trigger an AJAX function which runs the query that user has chosen and this triggers to stored procedure to run the query. This data is then passed to the AJAX success function and rendered to the DOM so it can be manipulated, exported etc.
--
The Issue:
When people choose to download the entire table (not often but certain departments have a need), we are having timeout issues which can be expected.
I am trying to find out where the bottle neck is to try and improve the experience.
When I run the query directly on the database for the 35,000 record result set, it takes about 12 seconds over VPN so I don't think the issue is with the database it self.
You can see in the image above where the timeout happened on the POST call.
I am trying to understand how the process flows for fetching / writing data to the DOM. Is the connection that is fetching the data from the database timing out or do we successfully have that data but we are timing out trying to write the 35,000 table rows?
Example Code:
var output = '';
$.ajax({
url: "api/fetchDashboardRender",
type: 'POST',
cache: false,
data: {
dashboardID: dashboardID
},
error: function(err) {
alert(err.statusText);
},
success: function(data) {
// Example .. Loop over the data in the result set
$(data).each(function(){
// Append each table row to a variable
output += '';
});
// Once done, append the variable to the DOM
$('#results').append(output);
}
});
Questions:
While I understand there is no need to write that much data to the DOM, there are reasons they want it done and I am following instruction.
Does the success function of an AJAX call include the DOM
manipulation or is it it successful once the data has been retrieved
from the source?
Is there a better way to approach this type of situation outside of making multiple calls in a paginated approach for batches of data?
Can you help me identify the main bottle neck here as to where things are being hung up?
Thanks for any pointers.
I have a URL that I'd like to scrape a certain bit of information from and I'd preferably do that by obtaining the element. I'd also need to get it as plaintext, but I'm still pretty new to Ajax/jQuery and don't quite know what the correct syntax is..
My ajax call is:
$.ajax({
url: URL,
dataType: 'text',
success: function(data) {
var info = data; //How can I get a table from the data without loading the whole site extracting a small portion?
if(info != undefined) {
console.log(info); //Needs to be plaintext.
}
}
});
I hope my question is clear... I'm essentially loading a website and retrieving a table or class name as plaintext... How could I do that? Thanks.
Your options on the client-side are:
1.) First, optionally use a regular expression to isolate that tag contents, but this is usually considered rather costly.
2.) Create a node, then drop the text into it's innerHTML.
That's usually the standard way of rendering text responses to the DOM.
Neither one are all that lightweight.
If you just need to pick something out of the text, use Regular Expression. Also, as mentioned, be aware of XSS and cross-origin policy.
Additionally, you may want to handle this on the server-side.
Apologies if this particular question has been solved before, I have looked everywhere it seems and can't quite get the answer I'm looking for! I am no expert and can imagine the solution is embarrassingly easy.
My problem is this: I have some php and javascript code working on a html based website, linked to a database (reading data in and also writing data out via a save function called once at the end of the script). I need the javascript code to automatically save/update itself to db via an Ajax request, without the need to keep running the page. The data being saved here needs to be read by various other pages and is relied upon to give correct results elsewhere! (so a solution would be to have the user keep the page open in the background - but suggestions for this separate issue are also welcome!)
Anyway, at the moment I have:
function sessionSave () {
var newData = kpiCA.getData().concat(kpiHA.getData(),kpiStocks.getData(),kpiCV.getData(),kpiPD.getData());
$.ajax({
url: 'saveMain.php',
type: 'POST',
data: {'kpi': newData},
success: function () {
},
error: function () {
$console.text('Data Save Error');
}
});
}
sessionSave();
I have seen some autosave scripts and the addition of timers etc. but as I am a complete noob, some help would be much appreciated,
Thanks guys!
Basically it's just timers or intervals. For example:
window.setInterval(sessionSave, NUMBER_OF_SECONDS * 1000)
// where NUMBER_OF_SECONDS is, obviously, the number of seconds to repeat your function at
I am working on a project for school and it's about jQuery, PHP, symfony and all that web stuff :). It is actually my first time using jQuery and even though I have already learned something, there are still many thing I dont know how to solve.
In this project, one of the things I am supposed to make is basically filtering some results. I have a database and when the site is loaded, all items from the database are displayed in a table. Then above the table, there is a text field. When I type in it, the items in the table are filtered as I type. But sometimes, when I write for example "HP", the jQuery first finishes the request for "HP" and displays the result and then it finished the request for "H" and so it overwrites the result of "HP" and this shouldnt happen. If I make the requests synchronous, it prevents me from writing in the text field when a request is being processed. How can I make it so that the requests are completed in the order they were called?
The jQuery code of this part of the project looks like this:
var oldTerm;
function filter() {
var term = $('#term').val();
//alert(term);
if(term != oldTerm) {
$.ajax({
url: url.replace('--', term).replace(/\/$/, '')
//musi bejt synchronni
}).done(function(data) {
$('#items_table tbody').html(data);
alert(term);
// udalost se musi registrovat po nacteni radku!
$('.edit_button').click(createForm);
});
oldTerm = term;
}
}
$(document).ready(function() {
oldTerm = null;
$('#term').keyup(filter);
});
I think your best shoot is to make a queue for the ajax call maybe use a lock too. You can also use this : Queue AJAX calls
Thanks to a javascript function and an ajax request, I have a count indicating the number of points a user makes when he uses my app. He can see that count on the page where he 'plays'.
Now, what I would like to do, is to pass this number into my views.py so that it modifies the object "Score" of my user.
I explain. Thanks to this function, I get the count:
var count = parseInt(0);
setInterval(function() {
$.ajax({
type: "GET",
url: "http://myxml",
success: Escore
});
}, 60000);
function Escore(xml){
$(xml).find("user").each(function() {
if($(this).attr("id") === id ) {
count += parseInt($(this).attr("count"));
$(".PlayerScore").html(count)
}
});
}
displayed in my html:
<div class="PlayerScore"> </div>
Now, I would like to modify the object "score" of my user thanks to that. Every minute, I have a request that gives me the number of points the player makes in my div. How can I take this count in order to modify my "request.user.userprofile.score" in my views.py?
I hope my question is not too confusing. Any help would be really welcome. thanks!
Hm If I understand the question, you need to do the following:
Create your view function, and create a URL pattern in URL.conf that attaches to this view function. Something like /points/save/
This function will likely require the points of the user and the user ID (so you can make changes to the specific user in the database)
You need to make an ajax request that sends the point data and the user ID To the URL that points to your view function. Sent through GET/POST
Your view function will lookup the user from the user id sent from jquery ajax call, then edit the user points with the points sent from the ajax call
Here are a few guides to help
Ajax with Jquery and Django
Django and Jquery