rebuild website for web 2.0 - php

I want to rebuild my own old ASP classic website to new standarts of web2.0 in PHP (as I understand it). On my main website page there are some areas that must show last updated things like: last threads on forum, last news, last talkbacks and etc. For now (on ASP version) I have all data loaded from DB to Application (memory) and page is reloaded every 4 minuts and each time taking data from Application. If data was changed (new talkback was added for example) Application object is set to null and data reloaded from DB.
My question is about best practices in web2.0: how should I make these areas been refreshed? I need to find the way to refresh only some parts of page. I thought about 2 ways:
1. put (again) data in memory, put iframes on page and reload them.
2. create data in XML file on server and load it from there each 4 minutes, when new thing added (like new talkback) recreate the XML file.
Is there some best practicies for solving such things?

You can replace the content of some divs with a html code got from an ajax request. For example:
<script type="text/javascript">
setInserval(function() {
$.ajax({
url: "response.php", // Page url
data: "querystring=1&ciao=2", // Your querystring
type: "POST", // Request type
dataType: "html", // Expected result
success: function(data) { // On success
$("#id_div").html(data); // Replace the content of #id_div with the response
}
}, 240000);
</script>
The page response.php must return the html to replace and require jQuery.

Related

Why my AJAX function blocks the header of PHP that I have on my page?

I am doing a program in PHP (MVC) in which I need to delete a row from the database when I click on a link on the View side. So, when I click on the link, the following ajax function it is called.
var deleteCar = function(id)
{
$.ajax({
type: "POST",
url: "http://localhost/project/car/deleteCar/" + id,
success: function(response){
}
});
}
but I do not want to send any data so it is the reason why I put it as above.
Then, in the Controller side I have the following method:
public function deleteCar($id)
{
//Here I call the function to delete the Car that I send by id. It works fine.
header('Location: http://localhost/project/car');
}
If I call directly the method deleteCar on the link without Ajax the header works properly but in the same moment I use Ajax to call it, I have to refresh the page to see the content that I have modified, I mean, that the Car have been deleted.
The code works fine, just I do not want to refresh the page after AJAX function had finished.
Thanks in advance!
I am guessing the use case is to allow the app to work when the user does not have JS enabled - so they just click the links and get a non-AJAX experience. In this case you probably want to redirect ONLY if the page was requested via GET, not POST. something like
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
header('Location: http://localhost/project/car');
}
is likely what you are looking for.
You will then have to actually remove the element representing the car from the DOM in your success handler, with something like:
var deleteCar = function(id)
{
$.ajax({
type: "POST",
url: "http://localhost/project/car/deleteCar/" + id,
success: function(response){
$('#car-row-' + id).remove();
}
});
}
(that won't be it exactly, it depends how the HTML of your page is setup how exactly you will do this).
I believe the key thing to understand here is - when your PHP function has completed it has removed the car from the database, but the browser still has the same HTML it got from the page originally. Just sending an AJAX request won't change that. If you want the HTML in the browser to change to reflect the new state of the database, you will NEED to do one of two things:
Refresh the page, so the entire thing is rebuilt by PHP based on the current database state
Use javascript to change the HTML in the browser, to reflect the changes you have made to the database state.
It is wrong on so many levels but it's difficult to put in words. It's subtle.
Long story short - think about jquery.ajax as of another virtual tab of you browser.
When you make ajax-request to the server - you create new virtual tab.
You php header could affect this virtual tab and redirect it where that header defined.
But it will redirect that virtual tab, not your current tab - if that makes sense.
What are your options? On success - make redirect with pure javascript.
success: function(response){
location.href = "http://localhost/project/car";
}
This would be the basic way to solve your problem.

Use $_FILES on a page called by .ajax

I have two .php pages that I'm working with. Index.php has a file upload form that posts back to index.php. I can access the $_FILES no problem on index.php after submitting the form.
My issue is that I want (after the form submit and the page loads) to use .ajax (jQuery) to call another .php file so that file can open and process some of the rows and return the results to ajax. The ajax then displays the results and recursively calls itself to process the next batch of rows.
Basically I want to process (put in the DB etc) the csv in chunks and display it for the user in between chunks. Im doing it this way because the files are 400,000+ rows and the user doesnt want to wait the 10+ min for them all to be processed.
I dont want to move this file (save it) because I just need to process it and throw it away and if a user closes the page while its processing the file wont be thrown away. I could cron script it but I dont want to.
What I would really like to do is pass the (single) $_FILES through .ajax OR Save it in a $_POST or $_SESSION to use on the second page.
Is there any hope for my cause?
Heres the ajax code if that helps:
function processCSV(startIndex, length)
{
$.ajax({
url: "ajax-targets/process-csv.php",
dataType: "json",
type: "POST",
data: { startIndex: startIndex, length: length },
timeout: 60000, // 1000 = 1 sec
success: function(data) {
// JQuery to display the rows from the CSV
var newStart = startIndex+length;
if(newStart <= data['csvNumRows']) {
processCSV(newStart, length);
}
}
});
}
processCSV(1, 2);
});
P.S. I did try this Passing $_FILES or $_POST to a new page with PHP but its not working for me :( SOS.
To clarify: My problem is that I want to access a $_FILE on a page that is called by ajax. The file is uploaded on index.php, the form as action="#" so it posts to index.php. After the post index.php sends an ajax call to process-csv.php and I need the file to be accessible on process-csv.php. I do not want to move the file because I don't want to have to clean up old files.
So I don't think you ever say your problem, but I'm guessing your problem is you are not able to ajax a file. The reason for this is because you can't actually get the file information in javascript because it's a security risk. There is a bunch of ways you can do this though. You can either use flash or an iframe to fake a ajax like file upload.
jQuery iframe file upload
I actually like the flash version though cause it gives you the ability to upload multiple files at once and still offers everything the iframe does as well as many more events.
http://code.google.com/p/swfupload/
With uploadComplete you can use to then put your processing code you have and uploadStart to use to pass a marker to say to link this session up with the file added to the database.
Also in your processing make sure you are always passing how far you have gotten, so it doesn't keep returning back the same rows each time.
I hope that helps.
Just construct the data rows in JavaScript then:
data: {
startIndex: startIndex,
length: length,
rows: variableWithRows.slice(startIndex, startIndex + length)
},
Inside PHP, all rows would be in $_POST['rows'] as array data.

jquery $.ajax request remains pending

I have made a simple chat application which uses long-polling approach using jquery,
function sendchat(){
// this code sends the message
$.ajax({
url: "send.php",
async: true,
data: { /* send inputbox1.value */ },
success: function(data) { }
});
}
function listen_for_message(){
// this code listens for message
$.ajax({
url: "listen.php",
async: true,
timeout:5000,
success: function(data) { // the message recievend so display that message and make new request for listening new messages
$('#display').html(data);
listen_for_message();
}
});
}
THIS SHOULD HAPPEN : after page loaded the infinite request for listen.php occurs and when user sends message, the code sends message to database via send.php.
PROBLEM is, using firebug i've found that send.php request which is performed after listen.php request, is remains pending. means the request for send message is remains pending.
The issue was because of session locking;
both send.php and listen.php files use session variables,
so session is locked in listen.php file and the other file (here send.php file) can't be served after the session frees from serving another file ( here listen.php).
How do I implement basic "Long Polling"?
the link above is a similar question that may help you.
it does not have to be on a database, it can be saved on a tmp file, but your problem is that you are choking the browser by performing too many requests, any one browser handles two requests at a time, which means you should really allow the browser to finish the first requests first then do the second one... and so on...
you do not need to do send.php and listen.php, because you can do it simply on one page both of them.
function check(){
$.ajax({
url : 'process.php',
data : {msg:'blabla'/* add data here to post e.g inputbox1.value or serialised data */}
type : 'post',
success: function (r){
if(r.message){
$('#result').append(r.message);
check();//can use a setTimeout here if you wish
}
}
});
}
process.php
<?php
$msg = $_POST['msg'];//is blabla in this case.
$arg['message'] = $msg;//or grab from db or file
//obviously you will have to put it on a database or on a file ... your choice
//so you can differentiate who sent what to whom.
echo json_encode($arg);
?>
obviously this are only guide lines, but you will exhaust your bandwidth with this method, however it will be alot better because you have only one small file that returns either 0 to 1 byte of information, or more if there is a message posted.
I have not tested this so don't rely on it to work straight away you need a bit of changes to make it work but just helps you understand how you should do it.
however if you are looking for long pulling ajax there are loads of scripts out there already made and fine tuned and have been test, bug fixed and many minds help built it, my advice is don't re-invent the wheel

Tell Controller On Another Domain There Is New Data

Currently I have two sites hosted on different domains.
SITE 1: I want to use as a CMS for content creation only.
(writing,editing,etc.)
SITE 2: I want to use for viewing content.
Theoretically, what I'd like to be able to do, is create multiple peices of content in SITE 1.
When I'm ready to publish these I'll press a 'publish' button, which will alert SITE 2 that there is new content and pass the values via JSONP.
SITE 2 will then pull in the data via JSON and do what it wants...(enter into DB, etc.)
...so yeah I'm stuck at the theoretical part. I'm not exactly sure where to go now but here's what I'm thinking.
There's a javascript function on SITE 1 that is called when I choose publish:
$.ajax({
type: "POST",
dataType: "jsonp",
data: postData,
url: 'http://site2.com/admin_json_controller.php',
success: function(data) {
// 'data' is a JSON object which we can access directly.
// Evaluate the data.success member and do something appropriate...
if (data.success == true){
alert('worked!');
}
else{
alert('did not work!');
}
}
});
This posts a json object to a php file on SITE 2. This file will simply be waiting for this post object. When it recognizes the post object...it will then enter the values into the database.
Does this make sense? I have a feeling I don't quite understand JSON yet but any help, questions, tips, pointers are much appreciated.
THANKS
To simplify things you have two options:
Use the same database for both domains.
Do a simple post to the other domain. Set the action of the form to script on the other domain. The other domain can access the variables via $_POST.

PHP reload page when adding forms (maybe needs ajax)

Sorry for maybe incorrect title for the topic, but this is the best that I came up with.
So, I'm building admin panel for a website.
I have a page, and in some part of the page, i'd like to refresh it and load another form.
let's say add a schedule, and somewhere down on the page I'd like to have this form displayed as soon as the link is clicked.
when a user saves it, I'd like that form to disappear and and in stead of that to have a list displaying all of the schedules.
I don't want to use frames - I'm not a supporter of frames. The panel is built using PHP.
Maybe this might be achived with Ajax? If yes -> How? any link to good example or tutorial.
yes this will be solved with ajax.
Here is a code example when the page is supposed to refresh
$('#button').click(function() {
$.ajax({
url: 'path/to/script.php',
type: 'post',
dataType: 'html', // depends on what you want to return, json, xml, html?
// we'll say html for this example
data: formData, // if you are passing data to your php script, needed with a post request
success: function(data, textStatus, jqXHR) {
console.log(data); // the console will tell use if we're returning data
$('#update-menu').html(data); // update the element with the returned data
},
error: function(textStatus, errorThrown, jqXHR) {
console.log(errorThrown); // the console will tell us if there are any problems
}
}); //end ajax
return false; // prevent default button behavior
}); // end click
jQuery Ajax
http://api.jquery.com/jQuery.ajax/
Script explained.
1 - User clicks the button.
2 - Click function initiates an XHR call to the server.
3 - The url is the php script that will process the data we are sending based on the values posted.
4 - The type is a POST request, which needs data to return data.
5 - The dataType in this case will be html.
6 - The data that we are sending to the script will probably be a serialization of the form element that is assigned to the variable formData.
7 - If the XHR returns 200, then log in the console the returned data so we know what we are working with. Then place that data as html inside the selected element (#update-menu).
8 - If there is an error have the console log the error for us.
9 - Return false to prevent default behavior.
10 - All done.

Categories