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.
Related
i'm not sure whether Ajax is what I need as i'm rather stumped on where to start, but I'll describe what I would like to happen.
I have a PHP file (lets call it scan.php) that contains a For loop that iterates along an array, which holds details of local files stored in a directory on a PHP. For each item in the array (a path to a file), I would like it (presumably an ajax script?) to call another php file (lets call it info.php) and display whatever that PHP file outputs on screen, with info.php taking the filepath in that index of the array as an argument.
Within that info.php file are various (dynamically generated) divs which inserts a different value into the database depending on which div the user clicks on. When that user clicks on a div, it inserts a value into the database (via an ajax call that i've already got working) and then displays a message (i'm using a javascript window.alert). If that message is a success then the info.php function ends, an we return back to scan.php. Whatever echoed out by info.php is cleared and then the loop iterates round again.
Sorry it's a bit complex but I have no idea where to start. Could anybody give me any hints on how to get started? I've had a look at ajax but frankly I have no idea where to start and whether it's even possible to use ajax to delay the PHP for loop.
This was my script that I thought would display info.php, but it's not echoing anything into the "show" div - or anything at all:
function Search_file(path) {
$( "#show" ).empty();
var request = $.ajax({
url: "info.php?path="+path,
type: "GET",
dataType: "html"
});
$("#show").html(result);
request.done(function(data) {
alert("Next file");
});
}
AJAX is asynchronous, so you haven't received your result when you are setting your html. You need to move your 'show' code inside the done handler like so:
function Search_file(path) {
$("#show").empty();
var request = $.ajax({
url: "info.php?path="+path,
type: "GET",
dataType: "html"
});
request.done(function(data) {
$("#show").append(result);
alert("Next file");
});
}
I use jquery to set a get query to a php script which then queries the database and writes to the screen, but I can't get it to trigger the download, even with headers.
The steps are as follows:
create a link that the user clicks to download the data
javascript sends the query parameters to php
php queries the database and writes the file
client downloads the file
But I can't get step 4 to happen.
Step 1: (this is a table object that also contains the parameters:
d3.select("#some-div").append('a")
.attr("href", "javascript: void(0)")
.on("click", function() { this.saveAsCSV() };
Step 2: Javascript file to make query:
var saveAsCSV = function(params) {
var tmp_params = $.extend({}, params);
tmp_params['State'] = "NM";
$.get('php/get_data.php', tmp_params);
}
php to return query:
...
header("Content-type: application/text-csv");
header("Content-Disposition: attachment; filename=query_result.csv");
while($row = $result->fetchArray() {
print "$row";
}
...
It works fine in that it correctly queries and will print the data in the javascript function (so it will print it to console.log if I add that into the get return function), but I can't figure out what I should do differently to make it just download it directly.
One thing I've tried is to do the following on the params object:
var param_string = encodeURIComponent(JSON.stringify(params));
location.href = 'http://www.mysite.com"+param_string;
But that both takes the user away from the page and fails to download the data.
EDIT: I should clarify that the php file does output the query well in csv format. The problem seems to be that using the $.get() function does not trigger a download regardless of the php headers. Maybe I need to just provide a simple link with the parameters in the URL address, but I'm not sure how to get a javascript object into a URL format so that the php script can interpret it.
You could open a popup/new window/tab/whatever with your URL php/get_data.php?State=NM (perhaps additional parameters). It should download the output.
But your output might be wrong because you just print the variable $row which is an array. If you try to print an array that way it will just show Array.
You will need to properly output your rows. Unfortunately I don't know the CSV structure well enough to help you with that problem.
You can make an AJAX call for this using something like jQuery and it will pop up the download box while keeping the user on the page. Do something like this:
$.ajax({data: {download: 'query_result.csv'}, type: 'GET', url: 'download.php', cache: false });
I've tried this a few times for a previous employer and it always worked great. Although I did it mostly with .zip and .docx files.
I figured it out!
Basically, my encoding was wrong. I don't want to encode with
encodeURIComponent(JSON.stringify(params));
The result isn't readable by the php script. However, it works to just use $.param().
To summarize, the download is triggered by creating the URL link and then using location.href to link to it. Hence everything else is the same, but instead of the $.get() in step 2, I do:
var url_params = $.param(tmp_params);
location.href = url_params;
Which generates the download. Thanks!
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.
I am trying to get the image links from 9gag (what also works) and when I click on a button the image changes to the next one. The basic problem is that it works only once. I can then switch between the 1st and the 2nd image, though. This should be pretty simple, but I ´ve got no clue where the error is, so thanks in advance to anyone bothering to look at this.
<?php
$index = 0
$html = file_get_contents("http://www.9gag.com");
preg_match_all( '|http://d24w6bsrhbeh9d\.cloudfront\.net/photo/.+?\.jpg|', $html, $gags);
?>
<script>
function nextImg(){
<?php $index++;?>
pic.src='<?php echo $gags[0][$index];?>';
}
function prevImg(){
<?php $index--;?>
pic.src='<?php echo $gags[0][$index];?>';
}
</script>
You can't increment your PHP variables after the page has loaded. You are trying to increment them client-side with JavaScript. You are going to need to call that PHP using AJAX if you want to do this without refreshing the page, and even then you'll want to increment a javascript variable to keep track of where you are.
EDIT: I went a little nuts creating an ajax routine using PHP and JavaScript, specifically the jQuery library, which you will need to link to for this to work. You may also need to modify parts of the script to work with what you're trying to accomplish, but this certainly is a guide for running your ajax app as you're hoping to.
Start by making a PHP file with this script:
<?php
// Set content header to json
header('Content-Type: application/json');
// Get the index from the AJAX
$index = $_GET['index'];
// Grab file contents & parse
$html = file_get_contents("http://www.9gag.com");
preg_match_all( '|http://d24w6bsrhbeh9d\.cloudfront\.net/photo/.+?\.jpg|', $html, $gags);
// Send filename back to AJAX script as JSON
echo json_encode(array($gags[0][$index]));
?>
Then, in your HTML, include this jQuery to complete AJAX calls to your PHP script, and update the DOM with the data from the PHP script.
<script>
$(function() {
'use strict';
// Initiate index variable
var index = 0;
// Load initial image
loadImage(index);
// Add click event to a button with class of next-btn
$('.next-btn').click(function(e) {
e.preventDefault();
// Increment index to get next image
index++;
// Run AJAX function to retrieve image
loadImage(index);
});
// Add click event to a button with class prev-btn
$('.prev-btn').click(function(e) {
e.preventDefault();
// Decrement the index if it isn't 0
if (index > 0) {
index--;
}
// Run AJAX function to retrieve image
loadImage(index);
});
});
function loadImage(index) {
'use strict';
$.ajax({
type: 'GET',
url: 'your-php-script.php', // Filepath to your PHP script
data: 'index='+index, // Index is passed through GET request
dataType: 'json', // Return JSON
success: function (data) { // If the php script succeeds
// Change img with class of pic's src
// to the filename retrieved from php
$('.pic').attr('src', data[0]);
}
});
}
</script>
Configuring this for your needs will require some serious PHP and jQuery/JavaScript knowledge, as some debugging will likely be needed. Good luck!
EDIT 2:
I uploaded the working (tested, it works) source files to my website if you want to download. Please accept answer and let me know you grabbed the files...
http://www.wedgewebdesign.com/files/ajax-image-loader.zip
#Eric basically has it right but didn't really go into detail if you aren't familiar with the model...
PHP is a server side language in that it does all its processing on the web host server and once it is complete sends a static result back to the user. This means, whatever you see after the page is loaded within PHP is there to stay, unless you do one of two things:
1) Send a new request -- You provide different parameters, the page re-executes its logic and returns a new result to the user
2) Execute some form of clientside Javascript. Javascript is different from PHP in that it executes on the client (not the server) so you don't necessarily have to send responses back to the server unless you need more information. Javascript and PHP can be combined to create AJAX calls which allow the client to make asynchronous calls to the webserver for more data without reloading the entire page. The Javascript handles re-drawing the new information or updating the page which can appear seamless to the user.
What you therefore need is one of those two options. Either you provide 'next'/'previous' links to the user and the page is loaded differently each time or you create an AJAX call that fetches the url of the next image and then loads it.
Try assigning a variable to $gags[0][$index]. Something like
$imgsrc = $gags[0][$index];
and then
pic.src='<?php echo $imgsrc; ?>';
I'm trying to load or better reload a DIV with content from an included php file. so the file is included in the webadmin.php from the location webadmin/pages.php. Then i alter some data in the DB through serializing.
Now I would like to reload the pages.php from the callback of the serialize POST with load();. This all works fine up until the moment the data is supposed to be displayed in the div - i believe its because the php file is loaded from a different location, so the include paths for the DB Connection etc are probably wrong...
Should I really write an extra PHP File for jquery or is there a way to tell jquery where to load it from?
Its the first time I'm doing this - so bear with me for a moment on this one... Thanks!
I guess it wont be much use, but heres the load code:
$("#right").load("webadmin/pages.php");
You can use Firebug, then open Net tab to see if there are response from the AJAX call.
I never use $.load(), instead I use $.get or $.post:
$.get("webadmin/pages.php",
{ nbRandom: Math.random() },
function(data){
$("#right").html(data);
});
nbRandom is just to prevent caching in IE. Choose a name that not used in the pages.php
Make sure no error in Firebug, and the page structure is a valid HTML/XHTML. Some bug is occurred because imbalanced tags in page.
Is the load() function returning anything?
The script is not location dependent in terms of the DB includes, etc. Those includes are only relative to the PHP script itself. The ajax function is running client side, so imagine that it's calling the URL relative to the same place as the original page. So if your page is:
http://example.com/stuff/page.php
and you are calling the script at:
webadmin/pages.php
Then the URL the ajax load method is using is:
http://example.com/stuff/webadmin/pages.php
This is the exact same as if you are putting in an href for a link or a src for an image. If the script actually is at:
http://example.com/webadmin/pages.php
Then you need to change the load URL accordingly (same as if an image were in a lower directory) like so:
$("#right").load("../webadmin/pages.php");
$.get("webadmin/pages.php",
{ nbRandom: Math.random() },
function(data) { $("#right").html(data); }
);
this code is including php file with using jquery