I have a Google Chrome extension for exporting entries from a website. I can't get all entries by one query and I'm using a parameter for paging, i.e. '...&p=' + pageNumber++. I do this with connecting to my web server and this is not a problem with PHP. But I found that I can generate pdf files directly using jsPDF and I decided to get rid of the server side help.
Now I want to fetch the entries with jQuery Ajax. The problem is that I don't know in advance how many pages I have to fetch.
My current solution is:
function runRecursionTest(url, pageNumber){
var currentUrl = url + '?p=' + pageNumber;
$.getJSON("http://query.yahooapis.com/v1/public/yql?"+
"q=select%20*%20from%20html%20where%20url%3D%22"+
encodeURIComponent(currentUrl)+
"%22&format=json'&callback=?"
).done(function(data) {
if(data.results[0]){
data = filterData(data.results[0]);
$('#export-target-list').append($(data).find('#entry-list').html());
runRecursionTest(url, pageNumber++);
} else {
alert('Stop! Last page: '+(pageNumber-1));
}
});
}
It seems logical, huh? But suprisingly it fails. Too much requests are sent even when I have 1 page only. Can't stop it.
Any ideas?
Related
So I made a website that displays FPS information stored in a mysql database. For each second of gameplay I have a pair of number(fps)-image(screenshot).
I display the numbers in a line chart made with JavaScript. The behaviour desired is when I click on a bullet in the chart, the screenshot for that particular second is displayed in a div on the page.
I have to mention that the screenshots are stored in the database and they are very low in size. I display then using PHP like this:
$query = "SELECT `image` FROM `logs` WHERE `session_id`=".$_GET['session']." AND `second`=".$second;
$sth = $mysqli->query($query);
$result=mysqli_fetch_array($sth);
if (!empty($result))
echo ' <img id="screen" src="data:image/jpg;base64,'.base64_encode($result['image']).'"/>';
The method I'm using now is when I click on a bullet in the chart (action recorded in JS), I send it as a GET parameter and read it with PHP afterwards, like this:
window.location.href = url + "?second=" + second;
This method obviously will refresh my page. The problem is, the chart I made also has a zoom/scroll option and that resets whenever the page is refreshed, making the experience very bad for the user.
Is there any method to display the screenshots without refreshing the page, for this particular case (where I have to query the database for each click/picture)? Maybe there is a better way of approaching this problem?
Thanks.
I think you've got 2 solutions which are Ajax or Websocket depending your needs.
AJAX
Ajax permit to asynchronously, only when you need, call the server and get datas from an URL which could be a webservice or PHP page... Perhaps, it's the better solution in your case.
To make it easy, you can use JQuery library by donwloading the script and insert it in your HTML :
<script src="jquery-3.0.0.min.js"></script>
To call the server, using JQuery :
$.ajax({
url: url + "/yourphppage.php",
data: "parameter=" + yourOptionelParameter,
async: false,
success: function(data) {
refreshYourChart(data);
},
error: function() {
alert("Your error");
},
contentType: 'charset=utf-8'
});
Or if your prefer pure javascript.
Now, you just have to work on the presentation of your data, on the server side. It could be what you want HTML, TXT, JSON, XML...
Websocket
Websocket is like a permanent tunnel opened between your server and the client. Each side can ask or send datas in real time.
It seems to be a library server side :
http://socketo.me/
And client side, it's very easy :
Nice documentation on mozilla website
Hope it helps. Good luck.
To change a picture source, as I see the easiest way is using an ajax call, so you can send any kind of parameters to your server, and in return your will get your new picture source.
$.get('urlToYourServer.com?parameter=1', function(data){
$('#img').attr('src', data.imgSrc);
})
I have a news project with comment feature. Any one who add a comment can see his comment immediately without reloading the page ( using ajax ). The problem is that when user1 ( for example ) comment on post1 , only user1 can see his comment immediately but all other users need to reload the page to see the comment of user1. How can I solve this problem ?
The code I am using to get the comment :
$(function () {
$("#AddComment").click(function () {
var CommentText = document.getElementById("CommetForm").innerHTML;
var UserName = document.getElementById("UserName").innerHTML;
var PostId = document.getElementById("PostId").innerHTML;
$.ajax({
url: '/PostComment/AddComment',
type: 'POST',
dataType: 'json',
cache: false,
data: { "PostId": PostId, "CommentText": OrignalCommentText },
success: function (data)
{
if (data == "P") // Commet Stored on database successfully
{
document.getElementById("PostComments-" + PostId).innerHTML +=
"<li>" +
"<div class='media'>" +
"<div class='media-body'>" +
"<a href='' class='comment-author'>"+UserName+"</a>" +
"<span class='CommetText' id='CommentText-" + PostId + "'>" + CommentText + "</span>" +
"</div>" +
"</div>" +
"</li>";
}
else // Some Error occur during storing database
{
document.getElementById("CommentError-" + PostId).innerHTML = "\nSomething went wrog, please try agin";
}
}
});
});
});
And This code for storing comment in database :
private SocialMediaDatabaseContext db = new SocialMediaDatabaseContext();
[HttpPost]
public JsonResult AddComment(string PostId, string CommentText)
{
try
{
Users CurrentUser = (Users)Session["CurrentUser"];
PostComment postcomment = new PostComment();
CommentText = System.Uri.UnescapeDataString(CommentText);
postcomment.PostId = int.Parse(PostId);
postcomment.CommentFromId = CurrentUser.UserId;
postcomment.CommentText = CommentText;
postcomment.CommentDate = DateTime.Now;
db.PostComments.Add(postcomment);
db.SaveChanges();
return Json("P");
}
catch
{
return Json("F");
}
}
I suggest you use SignalR for this. http://www.asp.net/signalr/overview/getting-started/introduction-to-signalr
TL;DR Use can use setInterval or Websockets to accomplish this. Below I explain how.
First of all, we need to understand what is behind this Publish/Subscribe pattern. Since you want to build a real-time application, you may create a function that asks to your server if some data was added since last time it was checked.
USING WindowTimers.setInterval()
Here is the simplest way to accomplish this in my point of view, assuming that's your first time and you never worked with websockets before. For instance, in your client-side project you create a function within a setInterval setInterval( checkNewData, time). Your method checkNewData() will make an ajax requisition to your server, asking if some data was added recently:
function checkNewData() {
// ajax call
// On response, if found some new comment, you will inject it in the DOM
}
Then, in your server-side method, get the timestamp of its call and verify in your database if there are some data. Something like this:
// Method written in PHP
public function ajax_checkNewData() {
$time = time();
// Asks to your model controller if has something new for us.
// SELECT comment FROM comments WHERE timestamp > $time
// Then return its response
}
You will use the response that came from your controller method ajax_checkNewData() to write on your comments-container.
USING WEBSOCKETS (beautiful way)
Now, there are another way to do this, using WebSockets. HTML5 WebSocket represents the first major upgrade in the history of web communications. Before WebSocket, all communication between web clients and servers relied only on HTTP. Now, dynamic data can flow freely over WebSocket connections that are persistent (always on), full duplex (simultaneously bi-directional) and blazingly fast. Amongst different libraries and frameworks, you can use socket.io. I believe this will solve your real-time application problem pretty good, but I am not sure how much of your project you will need to change to suit this solution.
Check it out the simple chat tutorial from SocketIo page and see for yourself if it fits to your needs. Its pretty neat and would be a good challenge to implement using it. Since its event-driven, I believe you wont have problems implementing it.
For further information check it out:
REFERENCES
Get Started: Chat application - http://socket.io/get-started/chat/
Websockets - http://en.wikipedia.org/wiki/WebSocket
WebSockets - https://developer.mozilla.org/en/docs/WebSockets
Good luck!
You could write a JavaScript code which makes ajax call to a servlet that checks for updates in the database.
Return a flag to the success function of the ajax call and If the state has changed or any comment added to the database, you can reload the page or refresh the consisting of the comments with the new comments.
It's not posting on other pages, because the user1 page is making an AJAX call, so it loads correctly. However, the other pages don't 'know' they are supposed to reload via AJAX. You need some kind of timed loop running that checks for any changes. Either of the above answers should work for it.
You could use SignalR for this, you can send realtime messages to the server, here is a sample to know how to implement SignalR in ASP.NET MVC
https://github.com/WaleedChayeb/SignalRChatApp
I have come across a situation that doesn't make much sense to me. Just as some background information, I'm using the Laravel framework. The page in question calls a query when the page is requested using Laravel's '->with('var', $array)' syntax. This query (which I will post later) works perfectly fine on page load, and successfully inserts dummy data I fed it.
I call this same query via an Ajax $.post using jQuery, on click of a button. However, when I do this $.post and call this query, I get an Internal Server Error every time. Everything is exactly the same, information passed included; the only difference seems to be whether or not it is called on page load or via the $.post.
Here is the error:
Below is the code that performs the query on page load:
routes.php sends the HTTP get request to a file called AppController.php
routes.php
AppController.php
The page is then made with the following array acquired from DeviceCheckoutController.php
Which then goes to DeviceCheckout.php
I am able to echo $test on the page, and it returns the ID of a new row every time the page is reloaded (which obviously mean the 'insertGetId' query worked). However, I hooked this query up to the page load just to test. What I really want to happen is on click of a button. Here is the code for that:
$("#checkoutFormbox").on('click', '#checkoutButton', function() {
var checkoutInformation = Object();
var accessories = [];
var counter = 0;
var deviceName = checkoutDeviceTable.cell(0, 0).data();
$(".accessoryCheckbox").each(function() {
//add accessory ID's to this list of only accessories selected to be checked out
if($(this).val() == "1")
{
accessories[counter] = $(this).data('id') + " ";
}
counter++;
});
checkoutInformation['deviceID'] = $(".removeButton").val(); //deviceID was previously stored in the remove button's value when the add button was clicked
checkoutInformation['outBy'] = '';
checkoutInformation['outNotes'] = $("#checkOutDeviceNotes").val();
checkoutInformation['idOfAccessories'] = 2;
checkoutInformation['dueDate'] = $("#dueDate").val();
if($("#studentIdButton").hasClass('active'))
{
checkoutInformation['renterID'] = 0;
checkoutInformation['emplid'] = 1778884;
console.log(checkoutInformation);
$.post("http://xxx.xxx.xxx.xxx/testing/public/apps/devicecheckout-checkoutdevices", {type: "checkoutDeviceForStudent", checkoutInformation: checkoutInformation}, function(returnedData) {
alert(returnedData);
});
}
});
Which is also then routed to AppController.php, specifically to the 'checkoutDeviceForStudent' part of the switch statement:
And then back to that query that is shown previously in DeviceCheckout.php
Finally, here is my DB structure for reference:
Any explanation as for why this would be happening? Also, any Laravel or other general best practice tips would be greatly appreciated as I'm inexperienced in usage of this framework and programming overall.
Sorry for such a long post, I hope there is enough information to diagnose this problem. Let me know if I need to include anything else.
Edit: Included picture of error at the top of the page.
Everything is exactly the same, information passed included
No, it isn't. If it was exactly the same you wouldn't be getting the error you're getting.
These sorts of issues are too difficult to solve by taking guesses at what the problem might be. You need to
Setup your system so Laravel's logging errors to the laravel.log file
Setup you PHP system so errors Laravel can't handled are logged to your webserver's error log (and/or PHP's error log)
Put Laravel in debug mode so errors are output the the screen, and the view the output of your ajax request via Firebug or Chrome
Once you have the actual PHP error it's usually pretty easy to see what's different about the request you think is the same, and address the issue.
I found a resolution to my problem after some advice from a friend; much easier than I anticipated and much easier than any solution that has been offered to me here or other places.
Essentially, what I needed to do was place a try, catch clause in my model function, and then if an exception is encountered I store that in a variable, return it, and use console.log() to view the exception. Here is an example to emulate my point:
public function getUserFullname($userID)
{
try
{
$myResult = DB::connection('myDatabase')->table('TheCoolestTable')->select('fullName')->where('userID', '=', $userID)->get();
return $myResult;
}
catch(Exception $e)
{
$errorMessage = 'Caught exception: ' . $e->getMessage();
return $errorMessage;
}
}
And then on the View (or wherever your model function returns to), simply console.log() the output of your POST. This will display the results of the successful query, or the results of the Exception if it encountered one as opposed to an unhelpful Internal Server Error 500 message.
I'm writing a system in HTML5 and Javascript, using a webservice to get data in database.
I have just one page, the index.html, the other pages i load in a <div>
The thing is, i have one page to edit and add new users.
When a load this page for add new user, i do this:
$("#box-content").load("views/motorista_add.html");
But, i want send a parameter or something else, to tell to 'motorista_add.html' load data from webservice to edit an user. I've tried this:
$("#box-content").load("views/motorista_add.html?id=1");
And i try to get using this:
function getUrlVar(key) {
var re = new RegExp('(?:\\?|&)' + key + '=(.*?)(?=&|$)', 'gi');
var r = [], m;
while ((m = re.exec(document.location.search)) != null)
r.push(m[1]);
return r;
}
But don't work.
Have i an way to do this without use PHP?
This won't work. Suppose your are loading the motorista_add.html in a page index.html. Then the JS code, the function getUrlVar(), will execute on the page index.html. So document.location that the function will get won't be motorista_add.html but index.html.
So Yes. To do the stuff you are intending, you need server side language, like PHP. Now, on the server side, you get the id parameter via GET variable and use it to build up your motorista_add.php.
You can pass data this way:
$("#box-content").load("views/motorista_add.html", { id : 1 });
Note: The POST method is used if data is provided as an object (like the example above); otherwise, GET is assumed. More info: https://api.jquery.com/load/
I'm trying to get some json data in my application, but it won't come in the result function.
function myLoad(){
output.innerHTML = 'in the load';// + items;
var myJsonUrl = 'http://....be/.../lineup.php';
$.getJSON(myJsonUrl, function(data) {
output.innerHTML = "IN THE FUNCTION";
});
output.innerHTML = 'END load';
}
In mu output div I can see 'in the load' so it stops at the .getJSON part.
I've included the right jquery libraries (jquery mobile and jquery1.4) and the json from the specified url validates.
What am i doing wrong?
EDIT:
In chrome it works sigh.
I was testing it in Eclipse web browser since I'm working for an Android application.
Apperantly that browser s**ks.
Thx for the idea Sir Troll
=> still can't answer my own question
I might be a bit late in answering this but was working on phonegap and had similar issue. You would need to add the URL in your phonegap.plist file under ExternalHost Array.
I added that and I am now getting JSON data from an external URL.
Hope this helps.
Are you sure you're not getting the data? Your example would most likely overwrite END load with IN THE FUNCTION, since the callback will be executed after the function finishes.
So output.innerHTML would get the values like this:
1. "in the load".
--> Ajax request start
2. "end load"
--> Ajax request finishes
3. "in the function"
I would suggest trying to output data in the callback, and remove the innerHTML changes from outside the callback function.
Is the jsonUrl in the same domain as your script? I'm not really sure, but I think you cannot do cross-domain requests with AJAX scripts.
Update:
Is the php script sending json headers?
header('Content-type: application/json')