Ajax call not working second time - javascript

I have this ajax/php structure that works perfectly when selecting one image. But, if I click on "selecteer" to perform the same code for the second time, no images are shown. The "ajax" page does load correctly though.
Basically what I have;
Article page: This page shows 10 buttons "Selecteer". Under these 10 buttons you have a div where some images are shown after pressing Selecteer. When clicking on one of those images, the clicked image is selected and will be shown solely.
Javascript: This script binds the click events, and performs the ajax loading aswell as the image showing.
Images page: this page is loaded by ajax and is shown in a div inside the article page.
EDIT:
I did some testing. The second time the div is loaded with an ajax call (the images page) it does "Create" all the images with the createImage function. Yet I only see the search bar and the "zoek" button. So the real problem is: the images aren't showing the second time!
The code (I left some things out which I think are irrelevant)
article:
<?php for($i = 0; $i < constant("MAX_PICS"); $i++) { ?>
<button <?php echo"id='select_portal$i' class='select_portal_class'";?> type="button">Selecteer</button>
<div <?php echo"id='dialog_form$i'";?> style="display:none; position:absolute; width:auto; height:auto; margin-left: auto; margin-right: auto; z-index:1;"></div>
<div <?php echo"id='selected_image$i'";?> style="display:block; width:auto; height:auto">
<?php if(isset($_GET['edit_artikel'])) { ?><img src="../images/<?php $beeldbank = Beeldbank::find_by_portal_id($artikel->portal_id); echo $beeldbank[0]->imagelib_id; ?>/<?php echo $artikel->portal_id;?>" id="selid" width="125" /> <?php } else {?>
<img src="../images/icons/no_image_found.png" alt="No image available" <?php echo"id='selid$i'";?> width="125" /> <?php } ?>
<input type="hidden" <?php echo"id='portal_id$i'";?> name="portal_id" value="<?php if(isset($_GET['edit_artikel'])) { echo $artikel->portal_id; } ?>" />
</div>
<div id="selected_portal"></div>
javascript:
$(document).ready(function() {
(function() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = document.location.protocol + '//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js';
var script2 = document.createElement('script');
script2.type = 'text/javascript';
script2.src = document.location.protocol + '//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js';
document.getElementsByTagName('head')[0].appendChild(script);
document.getElementsByTagName('head')[0].appendChild(script2);
})();
$( ".select_portal_class" ).each(
function( intIndex ){
$(this).bind('click', function() {
loadAjaxFrame(intIndex);
});
}
);
});
function loadAjaxFrame(id)
{
var dialog = $("#dialog_form"+id);
//alert(dialog.attr('id'));
dialog.css("display", "block");
dialog.css("top", "auto");
dialog.css("left", "auto");
dialog.css("right", "auto");
dialog.css("backgroundColor", "white");
document.getElementById(dialog.attr('id')).style.visibility = 'visible';
tempDialogID = id;
if(!ajaxLoad){
dialog.load("imglib.php");
ajaxLoad = true;
}
}
function showImage()
{
var portal = $("#portal_id"+tempDialogID);
var dialog = $("#dialog_form"+tempDialogID);
var selid = $("#selid"+tempDialogID);
alert(tempDialogID);
var img = document.getElementById(selid.attr('id'));
img.src = imgname;
var portal_id = document.getElementById(portal.attr('id'));
portal_id.value= imgid;
document.getElementById(dialog.attr('id')).style.visibility = 'hidden';
dialog.unload();
ajaxLoad = false;
}
function create_image(src,alt) {
var img = document.createElement("img");
var objTo = document.getElementById('imagesDiv');
img.src = src;
img.alt = alt;
img.className= "imgid";
$(img).height(imageHeight);
$(img).width(imageWidth);
$(img).bind('click', 'span', function () { imgid = alt; imgname = src; showImage(); });
objTo.appendChild(img);
}
$('#formpie').on('submit', function(e) {
e.preventDefault();
var dialog = $("#dialog_form"+tempDialogID);
$.ajax({
type : 'POST',
url : "imglib.php",
data : $(this).serializeArray(),
success: function(data) {
dialog.html(data);
}
});
});
And finally the images page:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
<script type="text/javascript" src="javascripts/SelectImage.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var photos = <?php echo json_encode($photoSources); ?>;
var photoAlts = <?php echo json_encode($photoAlts); ?>;
var photoTags = <?php echo json_encode($photoTags); ?>;
var photoCount= <?php echo $total_count; ?>;
photoCount = photoCount/10;
photoCount = Math.ceil(photoCount);
function buttonClicked(id){
var page = id;
photoPage = page*10;
minCount = photoPage-10;
maxCount = photoPage;
jQuery("#imagesDiv").html("");
createButtons();
$( "#imagesDiv" ).append( " <br/>");
populateDiv();
}
function createButtons() {
var i = 1;
var button= "";
while(i <= photoCount)
{
var button = document.createElement("BUTTON");
var buttonName= document.createTextNode(i);
button.appendChild(buttonName);
button.id = i;
jQuery(button).bind('click', { id: i}, function(event) {
var data = event.data;
buttonClicked(data.id);
});
var objTo = document.getElementById('imagesDiv');
objTo.appendChild(button);
i++;
}
}
$(".moreButton").click(function() {
maxCount += 10;
minCount += 10;
jQuery("#imagesDiv").html("");
populateDiv();
});
function populateDiv() {
for(var i = minCount;i < maxCount; i++)
{
if(i < <?php echo $total_count ?>)
{
create_image("../"+photos[i],photoAlts[i]);
$( "#imagesDiv" ).append( "<p style=\"display:inline; padding-left:10px;\">" + photoTags[i] + "</p><br/>" );
}
}
}
createButtons()
$( "#imagesDiv" ).append( " <br/>");
populateDiv();
});
</script> <?php
if(isset($_POST['submit'])) {
$artikel->portal_id = $_POST['portal_id'];
}?>
<fieldset>
Afbeelding zoeken
<form id="formpie" name="zoek" action="" method="POST">
<input type="hidden" name="zoek" value="zoek" id="zoek"/>
<input type="text" name="tags" size="31" id="tags"/>
<input type="submit" name="zoek" id="search" value="Zoek" />
</form>
<div id="imagesDiv" style="width:800px; height:780px;">
<label for="portal_id"></label>
</div>
</fieldset>
<div id="selected_img_div" style="display:none; width:auto; height:auto;">
<?php if($selected_image == NULL) { echo "No image selected"; }
else { echo '<img src="images/'.$selected_image.' class="selimgid"/>'; } ?>
</div>

If you load content dynamically and you want bind actions to them you shouldn't use the .bind(), .click() and .on([action], function(){}) functions. Because these functions can be only bind into elements which rendered at page loading.
So you should use that function:
$('body').on([action], [selector], function(){});
[action]: what type of binding do you want (ie: click, submit,...)
[selector]: select the element what you want to bind (ie: '.moreButton')
For example, instead of that code:
$(".moreButton").click(function() {
maxCount += 10;
minCount += 10;
jQuery("#imagesDiv").html("");
populateDiv();
});
Use this code:
$('body').on('click' , '.moreButton', function() {
maxCount += 10;
minCount += 10;
jQuery("#imagesDiv").html("");
populateDiv();
});

Try changing to,
$('body').on('submit','#formpie', function(e) {
e.preventDefault();
var dialog = $("#dialog_form"+tempDialogID);
$.ajax({
type : 'POST',
url : "imglib.php",
data : $(this).serializeArray(),
success: function(data) {
dialog.html(data);
}
});
});

$('#formpie').on('submit', function(e) {
e.preventDefault();
var dialog = $("#dialog_form"+tempDialogID);
$.ajax({
type: 'POST',
url: "imglib.php",
data: $(this).serializeArray(),
success: function(data) {
dialog.html(data);
urlRefresh();
}
});
});
replace your code with it. I think there is a problem on url refresh. so Try it.

maybe you are using functions or events with new content?
if you are doing that, maybe you have the same problem like this
https://stackoverflow.com/a/26559809/2043592

I had same problem and it got resolved after adding below code in head tag.
<meta charset="UTF-8">
<meta http-equiv="cache-control"
content="no-cache, must-revalidate, post-check=0, pre-check=0" />
<meta http-equiv="cache-control" content="max-age=0" />
<meta http-equiv="expires" content="0" />
<meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 G`enter code here`MT" />
<meta http-equiv="pragma" content="no-cache" />

Related

Making Ajax calls execute more than once

I am trying to load an changed image into a modal box with ajax. For example, the photo changes to the selected one when I click "Make Profile Picture" but it keeps the old one showing in the modal box unless I refresh the page. Is there a way to have ajax execute not just on page load but perhaps execute always to check the photo is the new one?
Here is the code I have in place:
PHP -
public function getprofileimageAction()
{
$layout = $this->layout();
$layout->setTerminal(true);
$view_model = new ViewModel();
$view_model->setTerminal(true);
$params = $this->identity();
$dir = #array_diff(#scandir(getcwd() . '/public/images/profile/' . $params . '/current/', 1), array('.', '..'));
if (!$dir) {
// set default avatar
$string_img = "<img src=\"/images/profile/defaults/avatar2.png\" class=\"w3-round w3-border\" onclick=\"document.getElementById('a-modal').style.display='block'\"
style=\"width: 200px; height: 200px;\" alt=\"Avatar\" id=\"avatar\">";
} else {
$string_img = "<img src=\"/images/profile/$params/current/$dir[0]\" class=\"w3-round w3-border\" onclick=\"document.getElementById('a-modal').style.display='block'\"
style=\"width: 200px; height: 200px;\" alt=\"Avatar\" id=\"avatar\">";
}
$data = array(
'profile_photo' => $string_img
);
echo $data['profile_photo'];
return $view_model;
}
JavaScript/jQuery -
var replaced_src;
var replace;
$.ajax({
type: "POST",
url: "/members/profile/get-profile-image",
}).done(function(data) {
$("#profile-pic").html(data);
replaced_src = $("#avatar").attr('src');
replace = replaced_src.replace(/(defaults)/g, '');
// fix this so it loads the changed image.
$('#current-photo').html("<img src='" + replace + "' alt='Avatar' class='w3-center w3-round w3-border' style='height: 280px; width: 400px;'>");
}).fail(function(data) {
alert("Error loading image");
});
This is the event click to change the profile picture
$('#make-profile-photo').on('click', function() {
$.ajax({
type: "POST",
url: "/members/profile/change-profile-picture",
data: { image: $('#other-photo').attr('src') }
}).done(function() {
document.getElementById('p-modal').style.display = 'none';
$('#profile-pic').load('/members/profile/get-profile-image');
});
});
HTML -
<div class="w3-modal" id="a-modal">
<div class="w3-modal-content w3-card-4 w3-theme-d2 w3-round" style="width: 432px;">
<div class="w3-container">
<p class="w3-center w3-small">
<span onclick="document.getElementById('a-modal').style.display = 'none'" class="w3-closebtn">×</span>
Current Profile Picture
</p>
<br>
<p id="current-photo" class="w3-center">
<br>
</p>
<script type="text/javascript">
var modal = document.getElementById('a-modal');
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = 'none';
}
}
</script>
<div class="w3-clear"></div>
</div>
</div>
</div>
So basically what I am asking is if there is a way to reload the changed image so $('#current-photo') will display it without having to refresh the page.
Hope that makes sense
Thanks!
If it helps, here is a screenshot of my issue:
http://imgur.com/a/DkPhQ

Disable rating stars after once rated js

Hi I want to put rating stars on my webpage.
Its is working fine. Rating is being added to database
But a user can rate again and again.
I want that stars should disable after rate once.
Here is my code. Kindly help me Thank you.
<!DOCTYPE html>
<html lang="en">
<head>
<link href="http://online-btw-berekenen.nl/rating/rating.css" rel="stylesheet" type="text/css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript" src="http://online-btw-berekenen.nl/rating/rating.js"></script>
<script language="javascript" type="text/javascript">
$(function() {
$("#rating_star").codexworld_rating_widget({
starLength: '5',
initialValue: '',
callbackFunctionName: 'processRating',
imageDirectory: 'images/',
inputAttr: 'postID'
});
});
function processRating(val, attrVal){
$.ajax({
type: 'POST',
url: 'rating.php',
data: 'postID='+attrVal+'&ratingPoints='+val,
dataType: 'json',
success : function(data) {
if (data.status == 'ok') {
alert('You have rated '+val+' to CodexWorld');
$('#avgrat').text(data.average_rating);
$('#totalrat').text(data.rating_number);
}else{
alert('Some problem occured, please try again.');
}
}
});
}
</script>
<style type="text/css">
.overall-rating{font-size: 14px;margin-top: 5px;color: #8e8d8d;}
</style>
</head>
<body style="background-color:black">
<h1>Give us star</h1>
<input name="rating" value="0" id="rating_star" type="hidden" postID="1" />
<div class="overall-rating">(Average Rating <span id="avgrat"><?php echo $ratingRow['average_rating']; ?></span>
Based on <span id="totalrat"><?php echo $ratingRow['rating_number']; ?></span> rating)</span></div>
</body>
</html>
Click and Hover funtion in javascript.
(function(a){
a.fn.codexworld_rating_widget = function(p){
var p = p||{};
var b = p&&p.starLength?p.starLength:"5";
var c = p&&p.callbackFunctionName?p.callbackFunctionName:"";
var e = p&&p.initialValue?p.initialValue:"0";
var d = p&&p.imageDirectory?p.imageDirectory:"images";
var r = p&&p.inputAttr?p.inputAttr:"";
var f = e;
var g = a(this);
b = parseInt(b);
init();
g.next("ul").children("li").hover(function(){
$(this).parent().children("li").css('background-position','0px 0px');
var a = $(this).parent().children("li").index($(this));
$(this).parent().children("li").slice(0,a+1).css('background-position','0px -28px')
},function(){});
g.next("ul").children("li").click(function(){
var a = $(this).parent().children("li").index($(this));
var attrVal = (r != '')?g.attr(r):'';
f = a+1;
g.val(f);
if(c != ""){
eval(c+"("+g.val()+", "+attrVal+")")
}
});
g.next("ul").hover(function(){},function(){
if(f == ""){
$(this).children("li").slice(0,f).css('background-position','0px 0px')
}else{
$(this).children("li").css('background-position','0px 0px');
$(this).children("li").slice(0,f).css('background-position','0px -28px')
}
});
function init(){
$('<div style="clear:both;"></div>').insertAfter(g);
g.css("float","left");
var a = $("<ul>");
a.addClass("codexworld_rating_widget");
for(var i=1;i<=b;i++){
a.append('<li style="background-image:url('+d+'/widget_star.gif)"><span>'+i+'</span></li>')
}
a.insertAfter(g);
if(e != ""){
f = e;
g.val(e);
g.next("ul").children("li").slice(0,f).css('background-position','0px -28px')
}
}
}
})(jQuery);
ok, in you click handler just remove the click event listener using the jquery off() method.
There are a few steps to disable to click and hover events AFTER a user has successfully selected (& recorded) a rating:
Add a line into your ajax success
success : function(data) {
if (data.status == 'ok') {
alert('You have rated '+val+' to CodexWorld');
$('#avgrat').text(data.average_rating);
$('#totalrat').text(data.rating_number);
$('.codexworld_rating_widget').addClass('already_set');
}else{...
Then add a function to disable each hover & click on the <li> in the "http://online-btw-berekenen.nl/rating/rating.js" script. See example below:
g.next("ul").children("li").hover(function(){
if ('.codexworld_rating_widget.alreadyset') {
$('.codexworld_rating_widget').off('click','li').off('hover','li');
}else{
// original script goes here
});
});
Anyways, I'm not able to test it without building a sandbox, so...hope it helps to point you in the right direction.

PHP Javascript - cannot change selector onclick to Remove preview file

I'm doing upload multiple files(use <input type="file" multiple/>) with preview image file and can remove the image preview and filedata successfully.
but the problem is, I cannot change the selector for onclick to remove filedata.
(If I change to other selector, it will only remove the preview image but the filedata still be uploaded to my folder)
The selector for click to remove that work successfully is .selFile but when
I want to change selector for onclick to .selFile2 it will not remove filedata)
these are my focus line of code. (To see my Full code, Please look on bottom)
var html = "<div><img src=\"" + e.target.result + "\" data-file='"+f.name+"' class='selFile'
title='Click to remove'> <span class='selFile2'>" + f.name + "</span><br clear=\"left\"/></div>";
..
I change from
$("body").on("click", ".selFile", removeFile);
to
$("body").on("click", ".selFile2", removeFile);
but it remove preview image only not remove filedata (it's still be uploaded to my folder)
..
And I try to change code in function removeFile(e)
from var file = $(this).data("file"); to var file = $('.selFile).data("file"); the result is It can remove only 1 filedata.
...
How could I do?
Here is my full code (2 pages)
firstpage.html (I use ajax to post form)
<!doctype html>
<html>
<head>
<title>Proper Title</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<style>
#selectedFiles img {
max-width: 200px;
max-height: 200px;
float: left;
margin-bottom:10px;
cursor:pointer;
}
</style>
</head>
<body>
<form id="myForm" method="post">
Multiple Files: <input type="file" id="files" name="files[]" multiple><br/>
<div id="selectedFiles"></div>
<input type="submit">
</form>
<script>
var selDiv = "";
var storedFiles = [];
$(document).ready(function() {
$("#files").on("change", handleFileSelect);
selDiv = $("#selectedFiles");
$("#myForm").on("submit", handleForm);
$("body").on("click", ".selFile", removeFile);
});
function handleFileSelect(e) {
var files = e.target.files;
var filesArr = Array.prototype.slice.call(files);
filesArr.forEach(function(f) {
if(!f.type.match("image.*")) {
return;
}
storedFiles.push(f);
var reader = new FileReader();
reader.onload = function (e) {
var html = "<div><img src=\"" + e.target.result + "\" data-file='"+f.name+"' class='selFile' title='Click to remove'> <span class='selFile2'>" + f.name + "</span><br clear=\"left\"/></div>";
selDiv.append(html);
}
reader.readAsDataURL(f);
});
}
function handleForm(e) {
e.preventDefault();
var data = new FormData();
for(var i=0, len=storedFiles.length; i<len; i++) {
data.append('files[]', storedFiles[i]);
}
var xhr = new XMLHttpRequest();
xhr.open('POST', 'upload.php', true);
xhr.onload = function(e) {
if(this.status == 200) {
console.log(e.currentTarget.responseText);
alert(e.currentTarget.responseText + ' items uploaded.');
}
}
xhr.send(data);
}
function removeFile(e) {
var file = $(this).data("file");
for(var i=0;i<storedFiles.length;i++) {
if(storedFiles[i].name === file) {
storedFiles.splice(i,1);
break;
}
}
$(this).parent().remove();
}
</script>
</body>
</html>
..
upload.php page
for($i=0;$i < count($_FILES["files"]["name"]);$i++)
{
if($_FILES["files"]["name"][$i] != "")
{
$tempFile = $_FILES['files']['tmp_name'][$i];
$targetFile = "upload/". $_FILES["files"]["name"][$i];
move_uploaded_file($tempFile,$targetFile);
}
}

PHP - Uploading multiple files with Javascript and PHP

its me again. Im currently trying to build an multiple file uploader for my site but dont know how to get/handle all files. I think showing you the code first will be a better explanation:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>NDSLR - Demo Upload</title>
</head>
<body>
<script type="text/javascript">
function fileChange()
{
//FileList Objekt aus dem Input Element mit der ID "fileA"
var fileList = document.getElementById("fileA").files;
//File Objekt (erstes Element der FileList)
var file = fileList[0];
//File Objekt nicht vorhanden = keine Datei ausgewählt oder vom Browser nicht unterstützt
if(!file) {
return;
}
var x = substr(file.name, -4);
document.getElementById("status").innerHTML = x;
/*
if (x != ".pdf") {
document.getElementById("fileA").files = null;
file = null;
fileList = null;
alert("Wrong Data");
return;
} */
document.getElementById("fileName").innerHTML = 'Dateiname: ' + file.name;
document.getElementById("fileSize").innerHTML = 'Dateigröße: ' + file.size + ' B';
document.getElementById("progress").value = 0;
document.getElementById("prozent").innerHTML = "0%";
}
var client = null;
function uploadFile()
{
//Wieder unser File Objekt
for(i=0;i < document.getElementById("fileA").files; i++) {
var file = document.getElementById("fileA").files[i];
//FormData Objekt erzeugen
var formData = new FormData();
//XMLHttpRequest Objekt erzeugen
client = new XMLHttpRequest();
var prog = document.getElementById("progress");
if(!file)
return;
prog.value = 0;
prog.max = 100;
//Fügt dem formData Objekt unser File Objekt hinzu
formData.append("datei", file);
client.onerror = function(e) {
alert("onError");
};
client.onload = function(e) {
document.getElementById("prozent").innerHTML = "100%";
prog.value = prog.max;
};
client.upload.onprogress = function(e) {
var p = Math.round(100 / e.total * e.loaded);
document.getElementById("progress").value = p;
document.getElementById("prozent").innerHTML = p + "%";
};
client.onabort = function(e) {
alert("Upload abgebrochen");
};
client.open("POST", "upload.php");
client.send(formData);
}
}
}
function uploadAbort() {
if(client instanceof XMLHttpRequest)
//Briecht die aktuelle Übertragung ab
client.abort();
}
</script>
<form action="" method="post" enctype="multipart/form-data">
<input name="file[]" type="file" multiple="multiple" id="fileA" onchange="fileChange();"/>
<input name="upload[]" value="Upload" type="button" accept=".dem" onclick="uploadFile();" />
<input name="abort" value="Abbrechen" type="button" onclick="uploadAbort();" />
</form>
<div id="status"></div>
<div id="fileName"></div>
<div id="fileSize"></div>
<div id="fileType"></div>
<progress id="progress" style="margin-top:10px"></progress> <span id="prozent"></span>
</div>
</body>
</html>
So this is my HTML Code and following up my upload.php:
<?php
if (isset($_FILES['datei']))
{
move_uploaded_file($_FILES['datei']['tmp_name'], 'upload/'.$_FILES['datei']['name']);
}
?>
My Problem currently is, that i dont know how to implement the multiple upload or better said, how to upload all files at all.
There are some tutorials in the internet, that you can simply find by googling "multiple file upload". Anyway here is one of the examples:
The HTML
<!-- IMPORTANT: FORM's enctype must be "multipart/form-data" -->
<form method="post" action="upload-page.php" enctype="multipart/form-data">
<input name="filesToUpload[]" id="filesToUpload" type="file" multiple="" />
</form>
Listing Multiple Files with JavaScript
//get the input and UL list
var input = document.getElementById('filesToUpload');
var list = document.getElementById('fileList');
//empty list for now...
while (list.hasChildNodes()) {
list.removeChild(ul.firstChild);
}
//for every file...
for (var x = 0; x < input.files.length; x++) {
//add to list
var li = document.createElement('li');
li.innerHTML = 'File ' + (x + 1) + ': ' + input.files[x].name;
list.append(li);
}
The input.files property provides an array of files for which you can check the length; if there's a length, you can loop through each file and access the file paths and names.
Receiving and Handling Files with PHP
if(count($_FILES['uploads']['filesToUpload'])) {
foreach ($_FILES['uploads']['filesToUpload'] as $file) {
//do your upload stuff here
echo $file;
}
}
PHP creates an array of the files uploaded with the given INPUT's name. This variable will always be an array within PHP.
Source
Demo
This is uploading using ajax. There are other ways such the use of iframe and jquery's $.load().
ajax_upload.js
Hmm... FormData is not IE-safe. So, you may want to resort to iframe & $.load().
function doUpload(fle_id, url_upld)
{
var upldLimit = 2000000; // 2mb by default;
if( $('#'+fle_id)[0] == undefined || $('#'+fle_id)[0].files.length == 0 ) {
alert('nothing to upload');
return;
}
// put files to formData
var tfSize = 0; // in bytes
var fd = new FormData();
$.each($('#'+fle_id)[0].files, function(i, file) {
fd.append(i, file);
tfSize = tfSize + file.size;
});
// you may check file size before sending data
if(tfSize > upldLimit) {
alert('File upload exceeded the '+(upldLimit/1000000)+' MB limit.');
return;
}
// actual data transfer
$.ajax({
url: url_upld,
cache: false,
data: fd,
type: 'POST',
contentType : false,
processData : false,
success: function(data){
alert(data);
},
error: function(jqXHR, textStatus, errorMessage) {
alert(errorMessage);
}
});
}
upload_form.html
Let's use jquery to make things simple.
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="ajax_upload.js"></script>
<script type="text/javascript">
$(function(){
$('form').submit(function(e){
if( e.preventDefault ) e.preventDefault(); // chrome/firefox
else e.cancelBubble(); // IE
// supply file input id and upload url
doUpload( 'fle', $(this).attr('action') );
});
});
</script>
Upload
<form action="ajax_upload.php"
method="post"
enctype="multipart/form-data"
accept-charset="utf-8"
>
<input type="file" id="fle" name="fle[]" multiple >
<button type="submit">Upload</button>
</form>
ajax_upload.php
<?php
if(count($_FILES) == 0) {
echo 'Nothing uploaded.';
exit;
}
$upldPath = 'E:/stack/upload/';
foreach($_FILES as $file) {
if ($file['error'] == UPLOAD_ERR_OK) {
try {
if( !move_uploaded_file( $file["tmp_name"], $upldPath . $file['name']) ) {
// abort even if one file cannot be moved.
echo 'Cannot upload one of the files.';
exit;
}
}
catch(Exception $e) {
echo 'Cannot upload the files.';
exit;
}
} else {
// abort even if one file has error.
echo 'Cannot upload one of the files.';
exit;
}
}
echo 'Upload successful!';
?>
Here is a simple approach to solving this issue.
This FormData append method works on IE 10 up and any other browser.
let files = []
let formData = new FormData
let filesInput = document.getElementById('files')
function prepareFiles() {
files = filesInput.files
}
function uploadFiles() {
// Arrange the files as form data to be sent to php
files = Array.from(files)
files.forEach(file => formData.append('files[]', file))
// See all selected files
console.log('Files')
console.log(formData.getAll('files[]'))
// Then send to php with jquery, axios e.t.c
console.log('Server response')
$.post('/pathtophpscript', formData, (response) => {
console.log(response)
}).catch(error => console.log(error))
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file" name="uploads" id="files" onchange="prepareFiles()" multiple>
<br/><br/>
<input type="submit" name="Upload" onclick="uploadFiles()">

How to repopulate checkboxes in form on refresh AND post the form values to page?

I am using an ajax script to repopulate checkboxes on a page when the page refreshes or is sent to another page and then back again. The script works fine as the checkboxes will still be checked after page refresh.
The problem I have is these checkboxes work as filters. So when clicked it POSTS to the page and my php script puts each value into a string for my query. When a page is refreshed the checkboxes stay checked but are not posting the values to the page. How can I make this Ajax script POST the values of the form after it repopulates my checked checkboxes on page refresh?
Here is Ajax script:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://cdn.jsdelivr.net/jquery.cookie/1.4.0/jquery.cookie.min.js"></script>
<script>
function handleButtonClick(button){
if ($(button).text().match("Check all")){
$(":checkbox").prop("checked", true)
} else {
$(":checkbox").prop("checked", false)
};
updateButtonStatus();
}
function updateButtonStatus(){
var allChecked = $(":checkbox").length === $(":checkbox:checked").length;
$("button").text(allChecked? "Uncheck all" : "Check all");
}
function updateCookie(){
var elementValues = {};
$(":checkbox").each(function(){
elementValues[this.id] = this.checked;
});
elementValues["buttonText"] = $("button").text();
$.cookie('elementValues', elementValues, { expires: 7, path: '/' })
}
function repopulateFormELements(){
var elementValues = $.cookie('elementValues');
if(elementValues){
Object.keys(elementValues).forEach(function(element) {
var checked = elementValues[element];
$("#" + element).prop('checked', checked);
});
$("button").text(elementValues["buttonText"])
}
}
$(":checkbox").on("change", function(){
updateButtonStatus();
updateCookie();
});
$("button").on("click", function() {
handleButtonClick(this);
updateCookie();
});
$.cookie.json = true;
repopulateFormELements();
</script>
And the PHP on same page that puts what is checked into a string for my query
if (isset($_POST["2kandunder"])) {
$arguments[] = "AND `2kandunder` = 'yes'";
}
if (isset($_POST["2kto4k"])) {
$arguments[] = "AND `2kto4k` = 'yes'";
}
if (isset($_POST["4kandup"])) {
$arguments[] = "AND 4kandup = 'yes'";
}
if(!empty($arguments)) {
$str = implode($arguments);
}
And html form
<form id="form" method="post" action="">
<input type="checkbox" name="2kandunder" class="checkbox" id="1" onchange="$('#form').submit();" <?=(isset($_POST['2kandunder'])?' checked':'')?>/> $2000 And Under
<input type="checkbox" name="2kto4k" class="checkbox" id="2" onchange="$('#form').submit();" <?=(isset($_POST['2kto4k'])?' checked':'')?>/> $2001 To $4000
<input type="checkbox" name="4kandup" class="checkbox" id="3" onchange="$('#form').submit();" <?=(isset($_POST['4kandup'])?' checked':'')?>/> $4001 And Up
I have tried adding the following to my ajax but I am totally new to ajax and it was a total guess. This code makes the page start blinking and the page will go to "page not found" after about 5 seconds.
$('#form').submit();
As you store the cookie, you can use it information in PHP as well to repopulate the query filter and the checkboxes on the form
<?php
$checkboxes = array('checkbox1' => false, 'checkbox2' => false, 'checkbox3' => false, 'checkbox4' => false, );
if (isset($_COOKIE['elementValues'])) {
/*
Cookie values are stored like JSON
*/
$raw = json_decode($_COOKIE['elementValues'], true); //cast to array
var_dump($raw);
foreach($raw as $input_name => $value) {
if (isset($checkboxes[$input_name])) {
$checkboxes[$input_name] = $value; //true/false
}
}
}
var_dump($checkboxes);
if (isset($_POST["checkbox1"]) || $checkboxes['checkbox1']) {
$arguments[] = "AND `2kandunder` = 'yes'";
}
if (isset($_POST["checkbox2"]) || $checkboxes['checkbox2']) {
$arguments[] = "AND `2kto4k` = 'yes'";
}
if (isset($_POST["checkbox3"]) || $checkboxes['checkbox3']) {
$arguments[] = "AND 4kandup = 'yes'";
}
$str = '';
if(!empty($arguments)) {
$str = implode(' ',$arguments);
}
echo 'QUERY FILTER : ' . $str;
?>
<!DOCTYPE html>
<html>
<head>
<title>Checkbox state - Coookies</title>
</head>
<body>
<form action="#" method="POST">
<?php
foreach($checkboxes as $input_name => $checked) {
echo '<input type="checkbox" id="'.$input_name.'" name="'.$input_name.'"'.($checked?' checked':'').' />';
}
?>
<input type="submit" />
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://cdn.jsdelivr.net/jquery.cookie/1.4.0/jquery.cookie.min.js"></script>
<script>
function handleButtonClick(button){
if ($(button).text().match("Check all")){
$(":checkbox").prop("checked", true)
} else {
$(":checkbox").prop("checked", false)
};
updateButtonStatus();
}
function updateButtonStatus(){
var allChecked = $(":checkbox").length === $(":checkbox:checked").length;
$("button").text(allChecked? "Uncheck all" : "Check all");
}
function updateCookie(){
var elementValues = {};
$(":checkbox").each(function(){
elementValues[this.id] = this.checked;
});
elementValues["buttonText"] = $("button").text();
$.cookie('elementValues', elementValues, { expires: 7, path: '/' })
}
$(":checkbox").on("change", function(){
updateButtonStatus();
updateCookie();
});
$("button").on("click", function() {
handleButtonClick(this);
updateCookie();
});
$.cookie.json = true;
</script>
</body>
</html>

Categories

Resources