Jump to content

imgrooot

Members
  • Posts

    383
  • Joined

  • Last visited

  • Days Won

    1

Everything posted by imgrooot

  1. I am trying out a new script for image upload and resize using ajax method. All the ones I've found so far process the php file through the form action="". Since I am inserting other data into the database and calling the other php code directly on the same page as a the html form, I would like to know if there is another way I can run that specific image upload php code through ajax. This is one the scripts I have looked at . http://www.sanwebe.com/2012/05/ajax-image-upload-and-resize-with-jquery-and-php This is what their html form looks like. <form action="processupload.php" method="post" enctype="multipart/form-data" id="MyUploadForm"> <input name="image_file" id="imageInput" type="file" /> <input type="submit" id="submit-btn" value="Upload" /> <img src="images/ajax-loader.gif" id="loading-img" style="display:none;" alt="Please Wait"/> </form> <div id="output"></div> I would like to process the "processupload.php" above through the ajax code below and leave the form action="" empty, as I am running other php code on the same page to insert other data as well. How would you do that? <script> $(document).ready(function() { var options = { target: '#output', // target element(s) to be updated with server response beforeSubmit: beforeSubmit, // pre-submit callback success: afterSuccess, // post-submit callback resetForm: true // reset the form after successful submit }; $('#MyUploadForm').submit(function() { $(this).ajaxSubmit(options); // always return false to prevent standard browser submit and page navigation return false; }); }); function afterSuccess() { $('#submit-btn').show(); //hide submit button $('#loading-img').hide(); //hide submit button } //function to check file size before uploading. function beforeSubmit(){ //check whether browser fully supports all File API if (window.File && window.FileReader && window.FileList && window.Blob) { if( !$('#imageInput').val()) //check empty input filed { $("#output").html("Are you kidding me?"); return false } var fsize = $('#imageInput')[0].files[0].size; //get file size var ftype = $('#imageInput')[0].files[0].type; // get file type //allow only valid image file types switch(ftype) { case 'image/png': case 'image/gif': case 'image/jpeg': case 'image/pjpeg': break; default: $("#output").html("<b>"+ftype+"</b> Unsupported file type!"); return false } //Allowed file size is less than 1 MB (1048576) if(fsize>1048576) { $("#output").html("<b>"+bytesToSize(fsize) +"</b> Too big Image file! <br />Please reduce the size of your photo using an image editor."); return false } $('#submit-btn').hide(); //hide submit button $('#loading-img').show(); //hide submit button $("#output").html(""); } else { //Output error to older browsers that do not support HTML5 File API $("#output").html("Please upgrade your browser, because your current browser lacks some new features we need!"); return false; } } //function to format bites bit.ly/19yoIPO function bytesToSize(bytes) { var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']; if (bytes == 0) return '0 Bytes'; var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024))); return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i]; } </script>
  2. Ahh yes, so that's what you were saying before. Makes sense. Thank you so much for help me out.
  3. That's great. It works. One last thing. How would you add my original date string into your new option value? I tried it like this and it gives me error like this. Parse error: syntax error, unexpected '$expiry_n' (T_VARIABLE), expecting identifier (T_STRING) foreach($expiry_options as $arr){ $sel = !empty($_POST['expiry_date']) && $_POST['expiry_date'] == $arr ? 'selected' : '';\ $date = date('Y-m-d H:i:s'); $expiry_n = date("Y-m-d H:i:s", strtotime("$date + $arr")); ?><option value="<?php echo $expiry_n; ?>" <?php echo $sel; ?>><?php echo $arr; ?></option><?php }
  4. Your options input code works great. That solves that problem. For the expiry date. I should mention that I also have expiry dates listed in hours as well. Like this. <select name="expiry_date"> <?php $date = date('Y-m-d H:i:s'); $expiry_1 = date("Y-m-d H:i:s", strtotime("$date + 12 hours")); $expiry_2 = date("Y-m-d H:i:s", strtotime("$date + 24 hours")); $expiry_3 = date("Y-m-d H:i:s", strtotime("$date + 1 week")); $expiry_4 = date("Y-m-d H:i:s", strtotime("$date + 2 weeks")); ?> <option value="0">Expires In</option> <option value="<?php echo $expiry_1; ?>" <?php if(empty($_POST['expiry_date'])) {} else { if($_POST['expiry_date'] == $expiry_1) { echo 'selected'; } } ?> >1 week</option> <option value="<?php echo $expiry_2; ?>" <?php if(empty($_POST['expiry_date'])) {} else { if($_POST['expiry_date'] == $expiry_2) { echo 'selected'; } } ?> >2 weeks</option> <option value="<?php echo $expiry_3; ?>" <?php if(empty($_POST['expiry_date'])) {} else { if($_POST['expiry_date'] == $expiry_3) { echo 'selected'; } } ?> >1 week</option> <option value="<?php echo $expiry_4; ?>" <?php if(empty($_POST['expiry_date'])) {} else { if($_POST['expiry_date'] == $expiry_4) { echo 'selected'; } } ?> >2 weeks</option> </select>
  5. 1. That was a mistake when I was adding the code in the message. My normal expiry_date has many more fields, so I simplified it to only 2 options. But rest assured, they have correct variables. Normally I would get the data list from the db, but in this case I have no other option. I need to insert an expiry date into the db and this is the best method I found that worked. 2. I did follow the instruction on the provided link. It works..in a sense that I can get a new row of the inputs data by clicking + or delete it with -. Still have the same issue regarding them disappearing after submit. Just to make it clear, this is the for loop I am using. for($i = 0; $i < count($_POST['option_title']); $i++) { if(trim($_POST['option_title'][$i]) != '' && trim($_POST['option_quantity'][$i]) != '' && trim($_POST['option_retail_price'][$i]) != '' && trim($_POST['option_discount_price'][$i]) != '') { $insert_options->execute(array( $get_item_id, $_POST['option_title'][$i], $_POST['option_quantity'][$i], $_POST['option_retail_price'][$i], $_POST['option_discount_price'][$i] )); } }
  6. There are two parts to my question. Part 1. I have a form. You know when you submit a form and if there is an error, the form will reset the input values unless you have the them "selected"? Well I have an issue with one of those inputs. Here is the code. For some reason the input value doesn't get selected on form reset. It inserts to the database fine. <fieldset> <label>Expiry Date</label> <select name="expiry_date"> <?php $date = date('Y-m-d H:i:s'); $expiry_1 = date("Y-m-d H:i:s", strtotime("$date + 1 week")); $expiry_2 = date("Y-m-d H:i:s", strtotime("$date + 2 weeks")); ?> <option value="0">Expires In</option> <option value="<?php echo $expiry_1; ?>" <?php if(empty($_POST['expiry_date'])) {} else { if($_POST['expiry_date'] == $expiry_1) { echo 'selected'; } } ?> >1 week</option> <option value="<?php echo $expiry_2; ?>" <?php if(empty($_POST['expiry_date'])) {} else { if($_POST['expiry_date'] == $expiry_1) { echo 'selected'; } } ?> >2 weeks</option> </select> </fieldset> This is another example of select drop down. But this one below works fine. // this select option's input values get selected on form reset. <fieldset> <label>City</label> <select name="city_id"> <option value="0">Select City</option> <?php $get_city = $db->prepare("SELECT city_id, city_name FROM cities WHERE city_id > :city_id"); $get_city->bindValue(':city_id', 0); $get_city->execute(); $result_city = $get_city->fetchAll(PDO::FETCH_ASSOC); if(count($result_city) > 0){ foreach($result_city as $row) { $get_city_id = intval($row['city_id']); $get_city_name = $row['city_name']; ?><option value="<?php echo $get_city_id; ?>" <?php if(empty($_POST['city_id'])) {} else { if($_POST['city_id'] == $get_city_id) { echo 'selected'; } } ?> ><?php echo $get_city_name; ?></option><?php } } else {} ?> </select> </fieldset> Part 2. This relates to my previous topic. I am trying to do the same thing as above, which is show input values on form reset. But this is slightly more complicated as it is an array. Looking at the code, you can see that you can add more fields through jquery. That all works. Inserting their values from multiple groups of fields into the db also works fine. But once again, if the form resets or submits, only the 1st group of fields show the selected values in the input fields. The 2nd or 3rd group of fields generated through the jquery disappear after submit. But again, their values do insert into the db fine. Here's the html and jquery code. <div id="options-parent"> <h2>Add Options</h2> <button class="add_field_button">Add More Fields</button> <div class="options-child-row"> <div class="option-float"> <label>Quantity</label> <input type="number" name="option_quantity[]" multiple min="1" max="1000000" step="1" value="<?php if(!empty($_POST['option_quantity'])) { echo $_POST['option_quantity'][0]; } else {}; ?>" /> </div> <div class="option-float"> <label>Retail Price</label> <input type="number" name="option_retail_price[]" multiple min="5" max="1000000" step="1" value="<?php if(!empty($_POST['option_retail_price'])) { echo $_POST['option_retail_price'][0]; } else {}; ?>" /> </div> <div class="option-float"> <label>Discount Price</label> <input type="number" name="option_discount_price[]" multiple min="1" max="1000000" step="1" value="<?php if(!empty($_POST['option_discount_price'])) { echo $_POST['option_discount_price'][0]; } else {}; ?>" /> </div> </div> </div> <script> $(document).ready(function() { var max_fields = 20; //maximum input boxes allowed var wrapper = $("#options-parent"); //Fields wrapper var add_button = $(".add_field_button"); //Add button ID var x = 1; //initlal text box count $(add_button).click(function(e){ //on add input button click e.preventDefault(); if(x < max_fields){ //max input box allowed x++; //text box increment $(wrapper).append( '<div class="options-child-row">'+ '<div class="option-float">'+ '<label>Quantity</label>'+ '<input type="number" name="option_quantity[]" min="1" max="1000000" step="10" value="" />'+ '</div>'+ '<div class="option-float">'+ '<label>Retail Price</label>'+ '<input type="number" name="option_retail_price[]" min="1" max="1000000" step="10" value="" />'+ '</div>'+ '<div class="option-float">'+ '<label>Discount Price</label>'+ '<input type="number" name="option_discount_price[]" min="1" max="1000000" step="10" value="" />'+ '</div>'+ '</div>' ); //add input box } }); $(wrapper).on("click",".remove_field", function(e){ //user click on remove text e.preventDefault(); $(this).parent('.options-child-row').remove(); x--; }) }); </script> What do you think?
  7. I take it it's something like this? If so, it doesn't work. $insert_options = $db->prepare("INSERT INTO item_options(item_id, option_title, option_quantity, option_retail_price, option_discount_price) VALUES(?,?,?,?,?)"); for($i = 0; $i < count($_POST['option_title']) && $i < count($_POST['option_quantity']) && $i < count($_POST['option_retail_price']) && $i < count($_POST['option_discount_price']); $i++) { $insert_options->execute(array( $get_item_id, $_POST['option_title'][$i], $_POST['option_quantity'][$i], $_POST['option_retail_price'][$i], $_POST['option_discount_price'][$i] )); }
  8. Got it. I have the solution now. I have to add array_filter to it like this. !empty(array_filter($_POST['option_title']))
  9. I have one more question "benanamen". The code seems to always insert in the db, even if I don't require it. For eg. I have it set so that if input fields are not empty, it insert. If not, do nothing. But it still inserts for some reason. What do you think is going on? if(!empty($_POST['option_title']) && !empty($_POST['option_quantity']) && !empty($_POST['option_retail_price']) && !empty($_POST['option_discount_price'])) { $insert_options = $db->prepare("INSERT INTO item_options(item_id, option_title, option_quantity, option_retail_price, option_discount_price) VALUES(?,?,?,?,?)"); for($i = 0; $i < count($_POST['option_title']); $i++) { $insert_options->execute(array( $get_item_id, $_POST['option_title'][$i], $_POST['option_quantity'][$i], $_POST['option_retail_price'][$i], $_POST['option_discount_price'][$i] )); } } else { echo 'do nothing.'; }
  10. Ahh I see. I will check out set_exception_handler. Thanks for clearing it up.
  11. I am only showing part of my real code. This record id is needed my case. $record_id = $_GET['record_id']; As for this. Can you please explain why having only $_POST is better than isset method? if(isset($_POST['submit']) As for the try/catch block. Are you saying to do something like this instead? for ($i = 0; $i < count($_POST['title']); $i++) { try { $insertStmt->execute(array( $record_id, $_POST['title'][$i], $_POST['description'][$i] )); echo 'Your post was a success.'; } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; echo 'Your post was a failure.'; } }
  12. Alright so I have it working now. For future reference, here's the entire code based on what "benanamen" wrote. // get record id from url parameter $record_id = $_GET['record_id']; if(isset($_POST['submit']) { $insertStmt = $db->prepare("INSERT INTO datatable (record_id, title, description) VALUES (?,?,?)"); for ($i = 0; $i < count($_POST['title']); $i++) { $insertStmt->execute(array( $record_id, $_POST['title'][$i], $_POST['description'][$i] )); if($insertStmt == true) { echo 'success'; } else { echo 'false'; } } } <form action="" method="post"> <input type="text" name="title[]" value="" /> <input type="text" name="title[]" value="" /> <input type="text" name="description[]" value="" /> <input type="text" name="description[]" value="" /> <input type="submit" name="submit" value="Post" /> </form>
  13. Got it. Last question. Do I subsitute the $_POST fields with my title and description I have from input values? Like this. for ($i = 0; $i < count($_POST['field1']); $i++) { $insertStmt->execute(array( $_POST['record_id'], $_POST['title'][$i], $_POST['description'][$i] )); } } If so, does the "count($_POST['field1'])" stays the same or what?
  14. Well that's a unique approach. One more thing. What if I want to insert a unique non array field in the same stmt as the array fields? Like this. Where would I add that in your code? $_POST['record_id'];
  15. For eg. I have this code. Right now it only inserts 1 row with 1 value each. How can I make it in a array so that it inserts 2 rows with 2 different values each? <?php $title = $_POST['title']; $desc = $_POST['description']; $insert = $db->prepare("INSERT INTO record(title, description) VALUES(:title, :description)"); $insert->bindParam(':title', $title); $insert->bindParam(':description', $desc); if($insert->execute()) { echo 'success.'; } else { echo 'failed.'; } ?> <input type="text" name="title[]" value="" /> <input type="text" name="title[]" value="" /> <input type="text" name="description[]" value="" /> <input type="text" name="description[]" value="" />
  16. Ahh yes. I had it in the footer originally. I didn't think it mattered if I put it in the header or footer, but apparently it does. It works now. Thank you so much Ch0cu3r. Your simple steps really made it clear for me to understand. Other wise I would be chasing in circles from all the other tutorials.
  17. Can you please double check your above code? It's giving me an error "ReferenceError: Timer is not defined". Which is this line. new Timer($('.<?php echo $counterName; ?>'), <?php echo $timeLeft; ?>);
  18. That does work. One last thing. I am retrieving multiple records from the db. Each of the records have their own unique countdown timer. Right now, it's only showing the countdown timer for the newest record created, while the rest of the records(that are not expired) show 00:00:00. So I was wondering, what can I do so that the countdown works for all the records? Here is the setup of foreach loop. foreach($rows as $row) { $target_date = $row['target_date']; $timeLeft = (strtotime($target_date) - time()) * 1000; ?> <input type="hidden" class="target-date" value="<?php echo $timeLeft; ?>" /> <div id="counter"> <span class="hour">00</span> <span class="min">00</span> <span class="sec">00</span> </div> <?php }
  19. Ahh yes that does work. Now my question is, since you are using two dates to find the difference in time left, how can I properly add the php date into the javascript "targetDate"? I can't seem to get it to work. Here is the full code. // this is the date format when adding to mysql db $target_date = date('Y-m-d H:i:s'); // this is how the date looks in the html when getting the value from the db <input type="hidden" class="target-date" value="2015-10-17 00:17:21" /> // this is the variable I am using to get the above input value to the javascript/jquery var getDate = $(".target-date").val(); // so all together, this is what the code looks like, with your code included. <script> $(document).ready(function(){ var getDate = $(".target-date").val(); // get todays date today = new Date(); // the target date, this will get the date/time for 8PM 16th October 16th 2015 targetDate = new Date(2015, 9, 16, 20); // subtract the two dates to get the difference in millisecons var timeLeft = targetDate - today; var timer = new Timer($('#counter'), timeLeft); }); </script>
  20. Simply put, I would like the countdown timer to NOT reset if the page is refreshed. From what I know, I have to use cookies for that. Can you tell me how I can incorporate a cookie in the following code? I am using this example. http://www.onextrapixel.com/2011/12/01/creating-a-groupon-like-count-down-timer/ The setup is like this. <html> <head> <!-- 1 --> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script> <script type="text/javascript" src="timer.js"></script> <!-- 3 --> <script> $(document).ready(function(){ var timeLeft = 12796000; // this is in milliseconds. var timer = new Timer($('#counter'), timeLeft); }); </script> <!-- 4 --> <style> div#counter{ margin: 100px auto; width: 305px; padding:20px; border:1px solid #000000; } div#counter span{ background-color: #00CAF6; padding:5px; margin:1px; font-size:30px; } </style> </head> <body> <!-- 2 --> <div id="counter"> <span class="hour">00</span> <span class="min">00</span> <span class="sec">00</span> </div> </body> </html> timer.js function Timer(container, timeLeft) { // get hour, minute and second element using jQuery selector var hoursContainer = $(container).find('.hour'); var minsContainer = $(container).find('.min'); var secsContainer = $(container).find('.sec'); // hold time left var currentTimeLeft = timeLeft; // 1 second = 1000 ms var secondsForTimer = 1000; // hold ID value return by setInterval() var timerInterval; // call setInteval() only when timeLeft is greater than 0 if (currentTimeLeft == 0) { return; } else { //Call setInterval()function and store ID value to timerInterval. timerInterval = setInterval(countdown, secondsForTimer); } //function being passed to setInterval() function countdown() { currentTimeLeft = parseInt(currentTimeLeft - secondsForTimer); if (currentTimeLeft == 0) { //stop calling countdown function by calling clearInterval() clearInterval(timerInterval); return; } else { //calculate hours left var wholeSeconds = parseInt(currentTimeLeft / 1000,10); var wholeMinutes = parseInt(currentTimeLeft / 60000,10); var wholeHours = parseInt(wholeMinutes / 60,10); //calculate minutes left var minutes = parseInt(wholeMinutes % 60,10); //calculate seconds left var seconds = parseInt(wholeSeconds % 60,10); //prefix 0 to hour, min and second counter $(hoursContainer).text((wholeHours < 10 ? "0" : "") + wholeHours + (wholeHours <=0 ? " hr" : " hrs")); $(minsContainer).text((minutes < 10 ? "0" : "") + minutes + (minutes <=0 ? " min" : " mins")); $(secsContainer).text((seconds < 10 ? "0" : "") + seconds + (seconds <=0 ? " sec" : " secs")); } } }
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.