Auto saving JAVASCRIPT data via AJAX to database - javascript

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

Related

Slow Webservice Callback

The question is about speeding up the loading of a ASP.NET web app, and I found that the loading time of the filtering feature of the web app is unacceptable. The filter list is generated from a database. Please see the following code:
This function is in .js and is invoking the webservice method.
function filterSetup() {
filterChanged = true;
var reset = true;
DDL_WebService.fillFilter(SucceededCallbackWithContext, FailedCallback,new ddlContext("My_Filter", reset));
filterSystemSetup();
}
This function is in .js too and is executed after the webservice method.
function SucceededCallbackWithContext(result, userContext) {
var ddl = $get(userContext.cntrl);
var curVal = userContext.getVal();
// Fetching result...
}
This function is one method in a web service file called "DDL_WebService.vb". It is in .vb and is getting the data from a database.
<WebMethod()> _
Public Function fillFilter() As List(Of String)
Dim strSQL As String
strSQL = "select '(All)' from My_Table "
Return getData(strSQL)
End Function
Problem: I thought after the last line of fillFilter(), it should go to SucceededCallbackWithContext()in almost no time (The step-into command tells me nothing happens in between too). However, getting to SucceededCallbackWithContext() from the last line of fillFilter() takes around 7 seconds.
I am not sure what is taking the time and how can I confirm and resolve that.
Any help is greatly appreciated :)
Updates:
Looking at the problem from another angle using Developer tool, I get the result shown in the sceenshot. Now my question becomes what are the possible reasons that some methods take too long to run (Note: For the webservice method with the longest request time, I speed up the query from 10 seconds to less than 3 seconds, but the request time is still arount 15 seconds). Could it be that the executing of one webservice method would affect the speed of another webservice method? Thanks again!
If you are going to filter data why you try to load all records with all columns?
If your my_table records is around 1000 or less than 1000(I mean you have a small data set) you can not understand performance issue but after a while as your data grow(for example it reaches up to 100000) you notice that your service is getting slower and slower.
If you query is not your main query in code so first use browsers developer tools or any other tools to measure response time of your service to be sure that problem is in your server side codes or in your javascript codes
Try to compress your datataTable before sending it !I share with you two functions thaallow the compression and decompression :
Public Shared Function CompressData(ByVal ds As DataSet) As Byte()
Try
Dim data As Byte()
Dim memStream As New MemoryStream()
Dim zipStream As GZipStream = New GZipStream(memStream, CompressionMode.Compress)
ds.WriteXml(zipStream, XmlWriteMode.WriteSchema)
zipStream.Close()
data = memStream.ToArray()
memStream.Close()
Return data
Catch ex As Exception
Return Nothing
End Try
End Function
Public Shared Function DecompressData(ByVal data As Byte()) As DataSet
Try
Dim memStream As New MemoryStream(data)
Dim unzipStream As New GZipStream(memStream, CompressionMode.Decompress)
Dim objDataSet As New DataSet()
objDataSet.ReadXml(unzipStream, XmlReadMode.ReadSchema)
unzipStream.Close()
memStream.Close()
Return objDataSet
Catch ex As Exception
Return Nothing
End Try
End Function
Hope help you.
Although it has been a long time since I posted the question, I still want to update my progress on this problem just to thanks Beldi and mostafa for the suggestions and to give people some hints when having similar issues.
Overall the problem has not been resolve but we came up with a workaround.
We were guessing that some queries might take a long time to finish, so I carved out all the queries that take a long time according to the developer tool. I tested them one by one and found that they are all pretty fast. In the next quite a bit of time, I was stuck on verifying what the developer tool indicates.
One breakthrough happens when I dissect the following code:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "dataservice/getSimData_WebService.asmx/getSimsList",
data: JSON.stringify(params),
dataType: "json",
success: function (data, textStatus) {
if (textStatus == "success") {
var thegrid = $("#jqGrid_sims")[0];
thegrid.addJSONData(data.d);
}
},
error: function (data, textStatus) {
alert("Error from get grid data");
}
});
In this piece of ajax call, the code sends out the request upon executing. The time between the beginning of the execution and the beginning of the if statement is requesting time, and that is the time the developer tool indicates.The time that code inside if statement spends is the fetching time.
After looking into the requesting time and the fetching time for each ajax call, I found the fetching time for a simulation functionality takes a relatively significant amount of time. Since loading the functionality would cause the page to be frozen and trying to reduce the frozen time has more uncertainties and takes longer, we finally decide to not load it initially. Instead, it will load once a user clicks on a button.
Hope this would help anyone who has similar problems.

retrieve value from mysql database with php/javascript in refreshing window

i have script that works as follows:
there is main page with 'start' button that initializes javascript function which loads a php page into a div frame, then via setTimeout it calls a 'refresh' function thats supposed to work indefinitelly and refresh the page inside frame
the refreesh timer is in database and is forwarded to java like this:
var min_refresh_time = ;
$min_refresh_time_sec is taken from database earlier in the code
what i wanted to modify is so the refresh min_refresh_time would be taken each time a refresh function is run, to my surprise this worked (or at least i thought so):
var min_refresh_time = ;
(custom sql functions are defined in separate php file included in main.php which is my main page)
unfortunatelly it seems that it 'worked' only due to some strange caching on java part and my pseudo-php code to take value from database is just a hoax - it looks like it is run only initially and then stores output somehow
simplified code of what is done and what i want to do:
function refresh_code(){
refresh_time = <?php Print(sql_result(sql_execute("SELECT value FROM settings WHERE setting='min_refresh_time'", $connection), 0, 0)); ?>;
refresh_time = 5;
alert(refresh_time);
$.post("index.php",{refresh_time:refresh_time_post, account_group: "1"},
function(data)
{
$.ajaxSetup ({
cache: false,
});
$("#frame_1").html(data);
});
setTimeout(function(){refresh_code()}, refresh_time);}
lets say min_refresh_time is 1 in database, i run it, it alerts 1 then 5 each time it self-refreshes, now if i go to database and change 1 to 3 i would want it to alert 3 then 5 obvious, it still does 1 then 5 tho...
i need a way to execute a dummy php file that only takes value from database, then sends it via post back to java and it gets intercepted there, any simple way to do that?
or do i need to use entirely different method for retrieving database value without js...
thx in advance
update:
i actually came back to it and analyzed potential solutions with fresh mind
first of all, i dont think my initial code had chance to work, java cant execute serverside code by itself, i took some of my aax code from other script and reworked it to launch php file that grabs the value from database, then i intercept output data and put into variable
looks like that:
$.ajax({
method: "POST",
url: "retrieve_refresh.php",
data: { retrieve_data: "max"},
cache: false,
timeout: 5000,
async: false,
cache: false,
error: function(){
return true;
},
success: function(msg){
if (parseFloat(msg)){
return false;
}
else {
return true;
}
}
}).done(function(php_output2) {
max_refresh_time = php_output2;
});
retrieve_refresh.php returns only the variable i want but the solution is unelegant to say the least, i havent searched yet but could use a way of sending variables as post back to ajax...

Cakephp creates many cache files

I've just started writing code with this framework. I have a big problem after adding this code to my View file (to add AJAX support for the form):
echo $this->Js->submit('Send',array(
'before'=> $this->Js->get('#success')->effect('fadeOut'),
'success'=>$this->Js->get('#success')->effect('fadeIn'),
'update'=>'#success'
));
Every time I refresh the page, Cakephp creates a file named {hash}.js like 987276be3fa726db322142ee6dfee435.js What's more, every refresh takes around 5s.
So after a few hours of work I had over 200 files in /webroot/js.
Every file contains code like this:
$(document).ready(function () {$("#submit-1856995147").bind("click", function (event) {$.ajax({beforeSend:function (XMLHttpRequest) {$("#success").fadeOut();}, data:$("#submit-1856995147").closest("form").serialize(), dataType:"html", success:function (data, textStatus) {$("#success").fadeIn();$("#success").html(data);}, type:"post", url:"\/newapp\/Sender"});
return false;});});
Do you know how to solve this?
try
core.php(inside /app/config/) has lot of features that help us improve our web application.
Configure::write(‘Asset.timestamp’, ‘force’);
This will helpful for you.

Send javascript array to SQL then get info back to the HTML

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;
}
});

Load .txt file using JQuery or Ajax

How can I fix the script below so that it will work EVERY TIME! Sometimes it works and sometimes it doesn't. Pro JQuery explains what causes this, but it doesn't talk about how to fix it. I am almost positive it has to do with the ajax ready state but I have no clue how to write it. The web shows about 99 different ways to write ajax and JQuery, its a bit overwhelming.
My goal is to create an HTML shell that can be filled with text from server based text files. For example: Let's say there is a text file on the server named AG and its contents is PF: PF-01, PF-02, PF-03, etc.. I want to pull this information and populate the HTML DOM before it is seen by the user. A was ##!#$*& golden with PHP, then found out my host has fopen() shut off. So here I am.
Thanks for you help.
JS - plantSeed.js
var pageExecute = {
fileContents:"Null",
pagePrefix:"Null",
slides:"Null",
init:function () {
$.ajax({
url: "./seeds/Ag.txt",
success: function (data){
pageExecute.fileContents = data;
}
});
}
};
HTML - HEAD
<script type="text/javascript">
pageExecute.init();
</script>
HTML - BODY
<script type="text/javascript"> alert(pageExecute.fileContents); </script>
Try this:
var pageExecute = {
fileContents:"Null",
pagePrefix:"Null",
slides:"Null",
init: function () {
$.ajax({
url: "./seeds/Ag.txt",
async: false,
success: function (data){
pageExecute.fileContents = data;
}
});
}
};
Try this:
HTML:
<div id="target"></div>
JavaScript:
$(function(){
$( "#target" ).load( "pathToYourFile" );
});
In my example, the div will be filled with the file contents. Take a look at jQuery .load() function.
The "pathToYourFile" cand be any resource that contains the data you want to be loaded. Take a look at the load method documentation for more information about how to use it.
Edit: Other examples to get the value to be manipulated
Using $.get() function:
$(function(){
$.get( "pathToYourFile", function( data ) {
var resourceContent = data; // can be a global variable too...
// process the content...
});
});
Using $.ajax() function:
$(function(){
$.ajax({
url: "pathToYourFile",
async: false, // asynchronous request? (synchronous requests are discouraged...)
cache: false, // with this, you can force the browser to not make cache of the retrieved data
dataType: "text", // jQuery will infer this, but you can set explicitly
success: function( data, textStatus, jqXHR ) {
var resourceContent = data; // can be a global variable too...
// process the content...
}
});
});
It is important to note that:
$(function(){
// code...
});
Is the same as:
$(document).ready(function(){
// code
});
And normally you need to use this syntax, since you would want that the DOM is ready to execute your JavaScript code.
Here's your issue:
You've got a script tag in the body, which is asking for the AJAX data.
Even if you were asking it to write the data to your shell, and not just spout it...
...that's your #1 issue.
Here's why:
AJAX is asynchronous.
Okay, we know that already, but what does that mean?
Well, it means that it's going to go to the server and ask for the file.
The server is going to go looking, and send it back. Then your computer is going to download the contents. When the contents are 100% downloaded, they'll be available to use.
...thing is...
Your program isn't waiting for that to happen.
It's telling the server to take its time, and in the meantime it's going to keep doing what it's doing, and it's not going to think about the contents again, until it gets a call from the server.
Well, browsers are really freakin' fast when it comes to rendering HTML.
Servers are really freakin' fast at serving static (plain-text/img/css/js) files, too.
So now you're in a race.
Which will happen first?
Will the server call back with the text, or will the browser hit the script tag that asks for the file contents?
Whichever one wins on that refresh is the one that will happen.
So how do you get around that?
Callbacks.
Callbacks are a different way of thinking.
In JavaScript, you perform a callback by giving the AJAX call a function to use, when the download is complete.
It'd be like calling somebody from a work-line, and saying: dial THIS extension to reach me, when you have an answer for me.
In jQuery, you'll use a parameter called "success" in the AJAX call.
Make success : function (data) { doSomething(data); } a part of that object that you're passing into the AJAX call.
When the file downloads, as soon as it downloads, jQuery will pass the results into the success function you gave it, which will do whatever it's made to do, or call whatever functions it was made to call.
Give it a try. It sure beats racing to see which downloads first.
I recommend not to use url: "./seeds/Ag.txt",, to target a file directly. Instead, use a server side script llike PHP to open the file and return the data, either in plane format or in JSON format.
You may find a tutorial to open files here: http://www.tizag.com/phpT/fileread.php

Categories

Resources