PHP - Ajax Triggering Long Job
is it possible to get an ajax call to execute a php script that will continue running even if the user leaves my site? i have used cron jobs and tokens to do in past but this can result in 1 min delay.
Similar TutorialsHello, I have been banging my head against the walla and trouble shooting this for days now. It seems so simple, yet there is something going on that I can't figure out. Thanks so much in advance for the help I am currently limiting comments and replies to comments on my social network. I have successfully done so except on the replies for one page, I can not get php to display an error with a simple if statement that should be firing when the submit button is hit. It's important to know that I have TWO pages being used. The main structural page and then the content page that is included in the structural page. Here is the code: Code: [Select] [code]if(isset($_POST['sub_comment_reply'])) { if($_POST['reply'] == "" ) { $valid = false; $error_msgs_reply[] = "Whoops! You forgot to write your reply."; }else{ $query = "SELECT COUNT(*) FROM `CysticAnswers_replies` WHERE `FromUserID` = $auth->id AND `date` = CURDATE()"; $result = mysql_query($query, $connection); $post_count = mysql_result($result, 0); $max_reply_per_day = 5; $error_msgs_replies_max[] = "Whoops! You have reached your limit of replies for the day."; if($post_count >= $max_reply_per_day){ $valid = false; } else { $query = "INSERT INTO `CysticAnswers_replies` ( `QuestionCommentID`, `FromUserID`, `comment`, `status`, `date`, `time` ) VALUES ( '" . mysql_real_escape_string($_POST['comment']) ."', '" . $auth->id ."', '" . mysql_real_escape_string($_POST['reply'])."', 'active', '" . date("Y-m-d") . "', '" . date("G:i:s") . "')"; mysql_query($query, $connection); } // this is from the page that is included, to echo the error but the if is not triggering <?php if(isset($_POST['sub_comment_reply']) && $post_count >= $max_reply_per_day && $valid = false) { foreach($error_msgs_replies_max as $msg) { ?> <div id="error_x"> <?php echo $msg; ?> </div> <?php } }?>[/code] The below isn't triggering the second if statement: if($_GET['admincp']!=""){ echo '<div class="center"><a href="./index.php?admincp">Admin CP</a>'; if($_GET['do']=="edit"){ (isset($_GET['id']) ? ' &#187; <a href="./index.php?admincp=users&do=edit">Edit Users</a>' : ''); } elseif($_GET['view']=="accounts"){ (isset($_GET['id']) ? ' &#187; <a href="./index.php?admincp=investors&view=accounts">View Accounts</a>' : ''); } echo '</div>'; } When a user is at index.php?admincp=users&do=edit&id=someid they should see Admin CP >> Edit Users When a user is at index.php?admincp=investors&view=accounts&id=someid they should see Admin CP >> View Accounts Right now only Admin CP shows up. can someone please help me with this I'm trying to make it so that when the page loads just the condition below will happend unless the if statment happends. so I need two if statments that work off of one condition? so i was thinking of using OR but i would need a if statement that says the page is being loaded what this code does it displays someones profile when search is hit but i want it to display the persons own profile soon as the page is loaded first Code: [Select] <?php if(isset($_POST['search'])) { // searches goaulds then displays them $search3 = "SELECT goauld,id FROM users WHERE goauld='".mysql_real_escape_string($_POST['goaulds'])."'"; $search2 = mysql_query($search3) or die(mysql_error()); WHILE($search1 = mysql_fetch_array($search2)){ $grab_goauld = $search1['goauld']; echo '<table width="300" height="5" border="1" align="center">'; echo '<th><center>Goauld Statistics</center></th>'; echo "<tr><td height='340'>$grab_goauld</td></tr>"; } } echo '</table>'; ?> First of all, I apologize for my "newbieness" in advance. I've got a form processing script that is working fine except for one section of code, snippets of which is shown below:
//default values $formResponse = "How are you really doing? Use this to find out!"; $imgSource = "blue.png"; If ($country == "United States") { //US zip code query $sql = "SELECT location, revParData FROM zipData WHERE zipCode = '$zipCode' LIMIT 1"; mysql_select_db('db'); $retval = mysql_query( $sql, $conn ); if(! $retval ) { $formResponse = "It looks like you entered an invalid zip code. Please try again!"; $imgSource = "yellow.png"; } else { $sql = "SELECT location, revParData FROM zipData WHERE zipCode = '$zipCode' LIMIT 1"; mysql_select_db('db'); $retval = mysql_query( $sql, $conn ); while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) { $location = $row['location']; $revParData = $row['revParData']; } }What I thought would happen is this: If the zip code entered by the end user does not exist in the table, the $formResponse and $imgSource values would be the "... invalid zip code" and "yellow.png" values. If a valid zip code is entered, it completes the second query. In fact, it works fine if a zip code that exists in the table is entered, but shows the default values for $formResponse and $imgSource if a zip code that doesn't exist in the database is entered. I can't figure out why it is doing this... if anyone can point out my coding error, it would be appreciated. Cheers! Mike Right now I redirect to index page after I delete a record. However I am looking to make it so that I can delete a record without redirecting the page. I know this can be accomplised using Ajax. I have spent countless hours before trying to make it work, but it did not work.
So here is a basic setup I created. Can you please update it with ajax code so that I can see how it's done properly?
<!DOCTYPE HTML> <html lang="en"> <head> <meta charset="UTF-8"> <title>Home Page</title> </head> <body> <div class="record" > <a href="record.php?id=<?php echo $record_id ?>"><?php echo $record_name; ?></a> <div class="delete-record"> <a href="delete.php">Delete Record</a> </div> </div> </body> </html> Edited by man5, 18 August 2014 - 08:55 PM. Now I'm having this strange issue with my website I'm currently working on a tester system and I've encountered a problem that I'm unable to find the issue, tho I'm thinking my ajax php part of the script to be the thing causing it even tho it seems strange that it would cause it. The first part which is connected to where the problem occurs is the echo"<form>"; and from there, It should take you to index.php?page=tester&select=answer, now that is where it in the browser goes there tho it still shows the page stuff from the last page which is index.php?page=tester&select=applications, so it's like showing both &select=answer and &select=applications on the same page. <?php $q=$_GET["q"]; include'../config/connection.php'; $result = mysql_query("SELECT * FROM applications WHERE id = '$q'"); echo "<center><table border='1'> <tr> <th>Account Name</th> <th>Character Name</th> <th>Gender</th> <th>Skin Color</th> </tr>"; $row = mysql_fetch_array($result); echo "<tr>"; echo "<td>" . $row['name'] . "</td>"; echo "<td>" . $row['charactername'] . "</td>"; echo "<td>" . $row['gender'] . "</td>"; echo "<td>" . $row['race'] . "</td>"; echo "</tr></table></center>"; echo"<br/>"; echo"<table><tr> <th>Description</th> <th>Metagaming</th> <th>Powergaming</th></tr>"; echo"<tr>"; echo "<td><textarea readonly='readonly' style='width:22em; height:20em;'>".$row['description']."</textarea></td>"; echo "<td><textarea readonly='readonly' style='width:22em; height:20em;'>".$row['mg']."</textarea></td>"; echo "<td><textarea readonly='readonly' style='width:22em; height:20em;'>".$row['pg']."</textarea></td>"; echo"</tr></table><table><br/><center><h1>Answer</h1><br/><form action='index.php?page=tester&select=answer' method='post'>"; echo"<textarea name='why' style='height:10em; width:60em;'></textarea><br/>"; echo"<input type='submit' name='answer' value='Accept' /><a/>"; echo"<input type='submit' name='answer' value='Decline' /></center>"; echo"<input type='hidden' name='id' value='$q'/>"; echo"</form></table>"; ?> Now on &select=answer it included a page which the script of that include consist of the stuff below, it outputs that the query was successfully, and all that. <? if(!empty($_POST['why'])) { $why = mysql_real_escape_string($_POST['why']); $answer = trim($_POST['answer']); $id = $_POST['id']; if($answer == "Accept") { $query1 = mysql_query("UPDATE characters SET accepted = '1' WHERE id = '".$id."'"); echo"Successfully accepted"; $answer = 1; } elseif($answer == "Decline") { echo"Successfully declined"; $answer = 0; } $query = mysql_query("UPDATE applications SET answer = '$why' AND tester = '".$_COOKIE['Username']."' AND accepted = '$answer' AND answered = '1' WHERE cid = '".$id."'") or die('Could not connect: ' . mysql_error()); if($query) { echo"<br/>Query went through without problems"; header("Refresh: 5;url=index.php?page=tester"); } } ?> This is the ajax part javascript of it which gets the information for index.php?page=tester&select=applications Code: [Select] <script type="text/javascript"> function showApplication(str) { if (str==""||str==0) { document.getElementById("txtHint").innerHTML=""; return; } if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("txtHint").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","tester/applications.php?q="+str,true); xmlhttp.send(); } </script>If you need any more information feel free to ask for it. Thanks in advance. Hello, I've been trying this for hours now, looking at different examples and trying to change them to work for me, but with no luck... This is what I am trying to do: I have a simple form with: - 1 input field, where I can enter a number - 1 Submit Button When I enter a number into the field and click submit, I want that number to be send to the php file that is in the ajax call, then the script will take that number and run a bunch of queries and then return a new number. I want that new number to be used to call the php script via ajax again, until no number is returned, or something else is returned like the word "done" or something like that, at which point is simply makes an alert or populated a div with a message... The point is, that depending on the number entered it could take up to an hour to complete ALL the queries, so I want the script that is called to only run a fixed amount of queries at a time and then return the number it is currently at (+1), so that it can continue with the next number when it is called again. I would like to use jquery, but could also be any other way, as long as I get this to work. I already have the php script completed that needs to be called by the ajax, it returns a single number when being called. Thank you, vb Hi All, I am trying to call a javascript pop-up window via a link by echoing out the html via php but keep getting parse errors: Parse error: syntax error, unexpected ')', expecting ',' or ';' Here is the code in question: Code: [Select] echo "<td class=\"today\"> <a href=\"javascript:statusWindow('status.php?month=".$month."&day=".$day."&year=$year');\">"$day_num</a> </td>\n"; And here is the javascript function: Code: [Select] <script type="text/javascript"> function statusWindow(url){ status_popupWin = window.open(url, 'status', 'resizable=yes, scrollbars=yes, toolbar=no,width=400,height=400'); status_popupWin.opener = self; } </script> Any help is appreciated. Thanks, kaiman I would like to apply some addition functionality to a form which add news records into the database. Basicaly what i want is similar to what this forum does with the [ code ] [ /code ] but what i want for the user to be able to add [ quote ] [ /quote ] and when the post is viewed then that specific area of the acticle body will be formated diffrently. I hope this makes sence. Hey Folks This is a major long shot but is their a way that i can use php to upload one mp3 file and one doc file, then get the php script to place the mp3 file in one folder but also copy the mp3 file and make it into a zip file and place it into another folder as well as also make another copy of the mp3 file pair it with the doc file and make it into another zip file in yet another folder mp3->---------------------------->--mp3----------------->----mp3 into zip-------->--mp3 + doc into zip &---- > --Uploaded via php----->--placed in folder a--->----placed in folder b--->--placed in folder c doc-->---------------------------->--copied--------------->----mp3 copied--------->-- But thier is a catch the host i am using didn't activate ZipArchive() function so need a diferent way to make the zip file. Any Ideas people? because i have been pulling my hair out at this one please help Phil If I break up this long line of code will it still work correctly? Original... Code: [Select] define('WEB_ROOT', ENVIRONMENT === 'dev' ? 'http://localhost/example.org/' : 'http://example.org/'); Desired... Code: [Select] define('WEB_ROOT', ENVIRONMENT === 'dev' ? 'http://localhost/example.org/' : 'http://example.org/'); Or maybe... Code: [Select] define('WEB_ROOT', ENVIRONMENT === 'dev' ? 'http://localhost/example.org/' : 'http://example.org/'); Debbie Guys, why the following mysql stored procedure taking much more time comparing with firebird one?
1. MySQL stored procedure
CREATE DEFINER=`lxc`@`::1` PROCEDURE `insertData`(IN it INT) BEGIN declare i int Default 0; declare str char(4); declare p_hash int; myloop: loop set p_hash = round(rand() * 999); set str='book'; insert into test.users (name,password) VALUES (concat(str,'_',i+1),PASSWORD(p_hash)); set i = i+1; if (i = it) then leave myloop; end if; end loop myloop; endObject info: Table: users Columns: id int(10) UN PK AI name varchar(45) password char(41)Time: mysql> call insertData(10000); Query OK, 1 row affected (9 min 38.22 sec)2. Firebird Stored Procedure SET TERM ^ ; CREATE PROCEDURE INSERDATA ( IT integer ) --iteration number AS DECLARE VARIABLE i integer; BEGIN i = 0; while ( i < it ) do begin INSERT INTO PRODUCT( CODE,NAME,PASS) VALUES(:i, 'jazz_' || :i, fb_hash(round(rand() * 999))); i = i + 1; end END^ SET TERM ; ^ COMMIT;Object Info: Table: product columns CODE integer, NAME varchar(45), PASS CHAR(41)Time: ( for 10 000 records it takes less than 1 sec for execution) Executing statement... Statement executed (elapsed time: 0.063s). 31464 fetches, 11084 marks, 0 reads, 0 writes. 10000 inserts, 0 updates, 0 deletes, 5 index, 0 seq. Delta memory: 24264 bytes. PRODUCT: 10000 inserts. 0 rows affected directly. Total execution time: 0.151s Script execution finished.Do you see something wrong in mysql stored procedure code? jazz. Edited by jazzman1, 31 July 2014 - 03:21 PM. I keep getting this error, because people can track their support tickets by using a MD5 encrypted code upon submitting, and I'm wondering if maybe it's too long? Code: [Select] You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'by FROM replies WHERE replyto = 'c8c3455c5efadc80b05316c412ab61e6' ORDER BY id D' at line 1 Query: Code: [Select] $replies = mysql_query("SELECT message,by FROM replies WHERE replyto = '$id' ORDER BY id DESC") or die(mysql_error()); Hi I'm trying to figure out how to calculate how long since a datevariable I have stored is from whenever the page is loaded.. I currently have a stored datevariable in the format: YYYY-MM-DD H:m:s ... So basically what I wish to accomplish is figuring out whenever i load the page which has stored this variable, how much time has passed. I want it to show up as for example : '10 minutes ago'.. '1 hour 25minutes ago' if it's the same day.. if its more than 1 day old it's enough to show only the number of days.....'1week 3 days ago' etc etc I'm working on a site that provides database results. To get to the final report, I'm going through a few pages where the user selects specific options. This builds up arrays that need to be passed from one page to another. As a result the final page has a pretty lengthy variable list. Since I want to provide a link to certain customers where they don't have to go through all the option select stuff, I'm using the GET method on the final page. Due to all the arrays I need to pass, I'm hitting hyperlink address character limitations, and I fear I will eventually hit browser URL length limits. Is there any way to provide links to customers without using the GET method so I could keep the URL length down? I try to get how long my message was sent with this... $Now = strtotime ("now"); $dateEnvoi = $fetchDiscussion['dateEnvoi']; //my date from my DB $timeEnvoi = mktime($dateEnvoi); $TempsEnvoi = $dateNow - $dateEnvoi; and it try to get how long it was post ... same thing as on facebook... like the 26 minutes ago from FB how can i do it ? I've written a script thats going to take a really long time to execute... Whats the best way to do this as far as the server not timing out? My script is calculating some statistics based on other tables in the database and then storing them in another table. The results are going to be hundreds of thousands or maybe even millions of rows. Hello , I've this code its skip the weekend ,and I've a table for special events has field datetime. What I need when its come across this datetime skip it like it does with the weekend. there's the code Code: [Select] <?php$database_date = '2011-08-12, 07:00:00'; //this comes from your database, $updated_time = strtotime('+' . hoursLeft($database_date,7,16,24) . ' hours',strtotime($database_date)); //Handle the date:$new_date = date('m-d-Y, H:i:s',$updated_time); //this is when the email should be sent.echo date('m-d-Y, H:i:s',strtotime($database_date)) . '<br />' . $new_date . '<-- you should be emailing at this time!'; //just echo's it to the screen.function hoursLeft($time,$work_starts,$work_ends,$time_to_email,$skip_weekends = true) { //this function handles the count of how many hours you need to fulfill your task. $parts = explode(' ',$time); //split the time off of the date. list($hour, $minute, $second) = explode(':',$parts[1]); //get the hours, minutes, seconds. if($minute == 0) { //if the minutes is over 0, then return a full hour for it $hours = $work_ends - $hour; } else { //otherwise, take into account that this isn't a full hour. $hours = ($work_ends - 1) - $hour; } $day_count = 0; //original day count is 0; for($i = $work_ends,$count = $hours; $count <= $time_to_email; $i++) { //Start the increment at 16, the count at the current hours, keep the count below 25, increment on each loop. if($i > 24) { //if the increment is over 24, reset it to 0. $i = 0; ++$day_count; //increment day_count when i goes over 24 hour limit. if($skip_weekends == true) { //if you want to skip weekends $day = date('l',strtotime("+ {$day_count} days",strtotime($time))); //get the full text of the current day the hours are pointing to. if(in_array($day, array('Saturday','Sunday'))) { //and current day is in the weekend. $hours += 24; //add 24 hours to the count. continue; //restart loop, before any counting takes place. } } } if($i > $work_starts && $i <= $work_ends) { //if the increment is between 7 and 16, add to the count, which will break the loop at 24. $count += 1; } $hours += 1; //add to the hours, the loop breaks at a count of 24, which will give us the total hours to add to the updated_time above. } return $hours; //return hours}?> OUTPUT: Code: [Select] 08-12-2011, 07:00:0008-16-2011, 14:00:00<-- you should be emailing at this time!9 hours for Friday:9 hours for Monday:7 hours for Tuesday:= 24 hours. I'm waiting for your replys.. I have the following code on a page Code: [Select] <?PHP session_start();?> <HTML> <HEAD> <META http-equiv="Content-Type" content="text/html; charset=windows-1252"> <TITLE>Running Test Cricket</TITLE> </HEAD> <BODY> <?PHP echo "Time at start ".$_SERVER['REQUEST_TIME']; #This is our hourly updates for teams if it is due - it is set off by the variable 'teamUpdateTime' echo "<BR>1"; $updateTime=time(); #Get the current time and put it into the variable $teams = mysql_query("SELECT * FROM teams WHERE teamUpdateTime<'$updateTime'"); //Go through all the teams while($team = mysql_fetch_array($teams)) { echo "<BR>UPDATING - hourly - ".$team['name']; #Show the team we are updating include("../updates/hourly_update_team.php"); #Update all the teams that are due to be updated } echo "<BR>2"; mysql_close($sqldb); //Close the database echo "<BR>Time at end ".$_SERVER['REQUEST_TIME']; ?> </BODY></HTML>While the code is crude it is not for the public to see - it is for updating teams in an online game I am creating. What my problem is that the REQUEST_TIME at the start and end of the code are always outputted the same; the code is there to see how long the page takes to do. I sit there and count how long the page takes to activate (load, whatever the terminology is) and it can take up to 40 seconds - but the REQUEST_TIME tells me it takes 0 seconds so obviously something is wrong. My question is simple - how do I get this code to output the REQUEST_TIME when the code starts and when it finished, thus showing me how long it took for the page to load. I wish to do this to try and speed it up. James |