"Data-loading" button not getting disabled in twitter bootstrap - javascript

I'm working on twitter bootstrap "data-loading" button.Below posted is my code.The button has to get disabled once it exceeds the page-limit.I was able to do it with normal button that doesnot contain "data-loading" option.Below posted is my code
<head>
<style type="text/css">
* {
font-family:"Times New Roman", Times, serif;
}
</style>
<script>
$(document).ready(function(){
var track_click =0;
var y = <?php echo $y; ?>;
$('#ram').load("fetch_pages.php", {'page':track_click}, function(){track_click++;
});
$('.load_more').on("click",function()
{
if(track_click<=y)
{
$.post('fetch_pages.php',{'page': track_click},function(data){
$('.load_more').show();
$('#ram').append(data);
$("html, body").animate({scrollTop: $("#hi").offset().top}, 500);
track_click++;
}).fail(function(xhr, ajaxOptions, thrownError) {
alert(thrownError); //alert any HTTP error
$(".load_more").show(); //bring back load more button
});
if(track_click >= y-1)
{
$('.load_more').attr('disabled','disabled');
}
}
});
});
$(function() {
$(".btn").click(function(){
var btn = $(this)
btn.button('loading')
setTimeout(function(){
btn.button('reset')},100);
});
});
</script>
</head>
<?php
include 'config.inc.php';
$query = "select count(*) from posts";
$exec = mysqli_query($connecDB,$query);
$ref = mysqli_fetch_array($exec);
echo $item_per_page;
$y=$ref[0];
$k=ceil($y/$item_per_page);
?>
<body>
<div align="center">
<button class=" load_more btn btn-primary" name = "test" id="hi">load
More</button>
</div>
<div id = "ram">
</div>
</body>
</html>

Try using prop instead of attr:
$('.load_more').prop('disabled',true);
If that doesn't solve your problem, you need to check what's in track_click and y, which we can't really do for you without some sort of actual data.
EDIT:
I put your code in jsbin and it seems to run fine with hard coded variables and without the post, so I think it's something wrong with some other part of your code.

Related

Return current response from PHP file while AJAX request is working [duplicate]

<form enctype="multipart/form-data" action="upload.php" method="POST">
<input name="uploaded" type="file" />
<input type="submit" value="Upload" />
</form>
<?php
if(isset($_REQUEST['submit'])){
$target = "data/".basename( $_FILES['uploaded']['name']) ;
move_uploaded_file($_FILES['uploaded']['tmp_name'], $target);
}
?>
I know Javascript, AJAX and JQuery etc very well and I believe an upload progress bar can be created using PHP, AJAX and Javascript etc.
I am surprised how to get the size of upload (meaning each second I want to know, how much of the file is uploaded and how much is remaining, I think it should be possible using AJAX etc) file during upload is in process.
Here is link to the PHP manual but I didn't understand that:
http://php.net/manual/en/session.upload-progress.php
Is there any other method to show the upload progress bar using PHP and AJAX but without use of any external extension of PHP? I don't have access to php.ini
Introduction
The PHP Doc is very detailed it says
The upload progress will be available in the $_SESSION superglobal when an upload is in progress, and when POSTing a variable of the same name as the session.upload_progress.name INI setting is set to. When PHP detects such POST requests, it will populate an array in the $_SESSION, where the index is a concatenated value of the session.upload_progress.prefix and session.upload_progress.name INI options. The key is typically retrieved by reading these INI settings, i.e.
All the information you require is all ready in the PHP session naming
start_time
content_length
bytes_processed
File Information ( Supports Multiple )
All you need is to extract this information and display it in your HTML form.
Basic Example
a.html
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css"
rel="stylesheet" type="text/css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script type="text/javascript">
var intval = null;
var percentage = 0 ;
function startMonitor() {
$.getJSON('b.php',
function (data) {
if (data) {
percentage = Math.round((data.bytes_processed / data.content_length) * 100);
$("#progressbar").progressbar({value: percentage});
$('#progress-txt').html('Uploading ' + percentage + '%');
}
if(!data || percentage == 100){
$('#progress-txt').html('Complete');
stopInterval();
}
});
}
function startInterval() {
if (intval == null) {
intval = window.setInterval(function () {startMonitor()}, 200)
} else {
stopInterval()
}
}
function stopInterval() {
if (intval != null) {
window.clearInterval(intval)
intval = null;
$("#progressbar").hide();
$('#progress-txt').html('Complete');
}
}
startInterval();
</script>
b.php
session_start();
header('Content-type: application/json');
echo json_encode($_SESSION["upload_progress_upload"]);
Example with PHP Session Upload Progress
Here is a better optimized version from PHP Session Upload Progress
JavaScript
$('#fileupload').bind('fileuploadsend', function (e, data) {
// This feature is only useful for browsers which rely on the iframe transport:
if (data.dataType.substr(0, 6) === 'iframe') {
// Set PHP's session.upload_progress.name value:
var progressObj = {
name: 'PHP_SESSION_UPLOAD_PROGRESS',
value: (new Date()).getTime() // pseudo unique ID
};
data.formData.push(progressObj);
// Start the progress polling:
data.context.data('interval', setInterval(function () {
$.get('progress.php', $.param([progressObj]), function (result) {
// Trigger a fileupload progress event,
// using the result as progress data:
e = document.createEvent('Event');
e.initEvent('progress', false, true);
$.extend(e, result);
$('#fileupload').data('fileupload')._onProgress(e, data);
}, 'json');
}, 1000)); // poll every second
}
}).bind('fileuploadalways', function (e, data) {
clearInterval(data.context.data('interval'));
});
progress.php
$s = $_SESSION['upload_progress_'.intval($_GET['PHP_SESSION_UPLOAD_PROGRESS'])];
$progress = array(
'lengthComputable' => true,
'loaded' => $s['bytes_processed'],
'total' => $s['content_length']
);
echo json_encode($progress);
Other Examples
Tracking Upload Progress with PHP and JavaScript
PHP-5.4-Upload-Progress-Example
This is my code its working fine Try it :
Demo URL (broken link)
http://codesolution.in/dev/jQuery/file_upload_with_progressbar/
Try this below code:
HTML:
<!doctype html>
<head>
<title>File Upload Progress Demo #1</title>
<style>
body { padding: 30px }
form { display: block; margin: 20px auto; background: #eee; border-radius: 10px; padding: 15px }
.progress { position:relative; width:400px; border: 1px solid #ddd; padding: 1px; border-radius: 3px; }
.bar { background-color: #B4F5B4; width:0%; height:20px; border-radius: 3px; }
.percent { position:absolute; display:inline-block; top:3px; left:48%; }
</style>
</head>
<body>
<h1>File Upload Progress Demo #1</h1>
<code><input type="file" name="myfile"></code>
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="uploadedfile"><br>
<input type="submit" value="Upload File to Server">
</form>
<div class="progress">
<div class="bar"></div >
<div class="percent">0%</div >
</div>
<div id="status"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
(function() {
var bar = $('.bar');
var percent = $('.percent');
var status = $('#status');
$('form').ajaxForm({
beforeSend: function() {
status.empty();
var percentVal = '0%';
bar.width(percentVal)
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal)
percent.html(percentVal);
},
complete: function(xhr) {
bar.width("100%");
percent.html("100%");
status.html(xhr.responseText);
}
});
})();
</script>
</body>
</html>
upload.php :
<?php
$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>
May I suggest you FileDrop.
I used it to make a progess bar, and it's pretty easy.
The only downside I met, is some problems working with large amounts of data, because it dosen't seem to clear up old files -- can be fixed manually.
Not written as JQuery, but it's pretty nice anyway, and the author answers questions pretty fast.
While it may be good fun to write the code for a progress bar, why not choose an existing implementation. Andrew Valums wrote an excellent one and you can find it here:
http://fineuploader.com/
I use it in all my projects and it works like a charm.
First of all, make sure you have PHP 5.4 installed on your machine. You didn't tag php-5.4 so I don't know. Check by calling echo phpversion(); (or php -v from the command line).
Anyway, assuming you have the correct version, you must be able to set the correct values in the php.ini file. Since you say you can't do that, it's not worth me launching into an explanation on how to do it.
As a fallback solution, use a Flash object uploader.
XMLHTTPREQUSET2
var xhr = new XMLHttpRequest();
xhr.open('GET', 'video.avi', true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
if (this.status == 200) {
var blob = this.response;
/*
var img = document.createElement('img');
img.onload = function(e) {
window.URL.revokeObjectURL(img.src); // Clean up after yourself.
};
img.src = window.URL.createObjectURL(blob);
document.body.appendChild(img);
/*...*/
}
};
xhr.addEventListener("progress", updateProgress, false);
xhr.send();
function updateProgress (oEvent) {
if (oEvent.lengthComputable) {
var percentComplete = oEvent.loaded / oEvent.total;
console.log(percentComplete)
} else {
// Unable to compute progress information since the total size is unknown
}
}

how to acess form with external js files? how to hide sensitive content of js from client?

I'm using emailjs to send email through my free subdomain website.There are two problems with it
1). My emailjs account-id, service-id and template-id is getting public so anybody can access it and send email through it.
2). to solve it I used following code but it steel appears in browser "inspect Element"(Developer tool).
<?php echo "
<script>
(function(){
emailjs.init(my user id);
})();
</script>" ; ?>
<?php
echo "<script src='js/formfilled.js'></script>";
?>
now my form submiting button is like this
<button onclick="email();">
Send
</button>
now my formfill file is like this
var myform = $("form#myform");
function email(){
var service_id = "default_service";
var template_id = "xxxxxxxxx";
myform.find("button").text("Sending...");
emailjs.sendForm(service_id,template_id,"myform")
.then(function(){
alert("Sent!");
myform.find("button").text("Send");
}, function(err) {
alert("Send email failed!\r\n Response:\n " + JSON.stringify(err));
myform.find("button").text("Send");
});
}
problem is that when I click the button rather than sending an email it reload the page .
Sorry if it is too silly i am totally beginner and Thanks in advance.
UPDATE
it is working if i put the code in the same file(not using external js)
code:--
<head>
<script type="text/javascript">
(function(){
emailjs.init("xxxxxxxxxxxxxxxxxxxxx");
})(); </head>
</script>
<body>
<!-- form is here-->
<script>
var myform = $("form#myform");
myform.submit(function(event){
event.preventDefault();
// Change to your service ID, or keep using the default service
var service_id = "default_service";
var template_id = "xxxxxxxxxxxxxxxxxxx";
myform.find("button").text("Sending...");
emailjs.sendForm(service_id,template_id,"myform")
.then(function(){
alert("Sent!");
myform.find("button").text("Send");
}, function(err) {
alert("Send email failed!\r\n Response:\n " + JSON.stringify(err));
myform.find("button").text("Send");
});
return false;
});
</script>
</body>
but if i put this code in formfilled.js it is not working.
what would be the reason behind it?
Answer:
to use
event.preventDefault();
and loading the file before the button is loaded.

How to insert new data before old data rather than after

I perform the php script to show random data. I use ajax get to get data from the php script and continue getting data from the php script every 1 seconds. I also perform removal of the last row if the count is more or eqaul to 4. HOwever, my output is backward. I want to append new data before old data.
php script
<?php
$countryarr = array("UNITED STATES", "INDIA", "SINGAPORE","MALAYSIA","COLOMBIA","THAILAND","ALGERIA","ENGLAND","CANADA","CHINA", "SAUDI ARABIA");
$length = sizeof($countryarr)-1;
$random = rand(0,$length);
$random1 = rand(0,$length);
$random_srccountry = $countryarr[$random];
$random_dstcountry = $countryarr[$random1];
echo "<div>[X] NEW ATTACK: FROM [".$random_srccountry."] TO [".$random_dstcountry."] </div>";
?>
html code
<html>
<head>
<title>Add new data</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style>
#result {
width: 500px;
height:500px;
border-style: solid;
border-color: black;
}
</style>
</head>
<body>
<div id="result"></div>
<script>
var $auto_refresh = setInterval(function() {
var $count = $('#result div').length;
while ($count >= 4) {
$('result div:last-child').remove();
$count = $('#result div').length;
}
updateServer();
}, 1000);
//Remove last div if the count is more than 4
function updateServer() {
$.get({
url: 'randomData.php',
dataType: 'text',
success: randomdata
});
}
function randomdata(val) {
$('#result').append(val); //i want to insert before in other words new data appear at the top and old data remain down
}
</script>
</body>
</html>
I thought of using before or insertbefore to insert new data before the old data. I also used node to insert before.It does not work. Please help me. thank you..
You have to use prepend() from jquery :
function randomdata(val) {
$('#result').prepend(val);
}
EDIT
I noticed an other error : $('result div:last-child').remove(); should be $('#result div:last-child').remove();
That's probably why it don't change, when it's at 4 divs it doesn't delete and redo the count, so you get stuck inside the while ... The fix from below should solve the problem

Pass JavaScript function through Ajax to PHP file

What I am trying to do:
I am working on a script intending to offer the user choices and depending on which choice they make, come up with a new choice. I have made two scripts for this, one for my HTML and the structure of my page and one for my PHP (getting the information from my server) and JavaScript (building the generated choices).
I am then using AJAX to communicate between these two scripts, or at least, that's what I am trying to do, but I am very new when it comes to AJAX and I cannot make it work.
I am trying to pass or somehow start the function 'generateProblems' from my page when one of the 3 buttons are pressed, preferably with the param 'id'.
Here's part of my index.html:
<div id="testpile" class="inner cover">
<div id="buttons">
<p><a id="rat" class="btn btn-default" role="button">Rationel</a></p>
<p><a id="emo" class="btn btn-default" role="button">Emotionel</a></p>
<p><a id="per" class="btn btn-default" role="button">Personel</a></p>
</div>
</div>
<div id="testdrop" class="mastfoot">
<p>Drop numbers here</p>
</div>
<script type="text/javascript">
$("#buttons").find(".btn").click(function() {
var id = this.id;
$("#testpile").load("include/responseget.php");
$.post("include/responseget.php", {
choice: "id",
});
});
</script>
And here's my PHP / Javascript:
<?php include 'login.php';
//Query til at finde information til generation af question
$stmt = $conn->prepare("SELECT DISTINCT ResponseTitle, ResponseText FROM response Limit 8;");
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc())
{
$rTitle_array[] = $row['ResponseTitle'];
$rText_array[] = $row['ResponseText'];
}
json_encode($rTitle_array);
json_encode($rText_array);
// close connection
mysqli_close($conn);
?>
<script type="text/javascript">
$(function() {
var phase = 0;
var rTitle = <?php echo json_encode($rTitle_array); ?>;
var rText = <?php echo json_encode($rText_array); ?>;
function generateProblems(param) {
var problemDef = param;
$("#buttons").hide();
var numbers = [1, 2, 3, 4, 5, 6, 7, 8];
for (var i = 0; i < 8; i++) {
$('<div>' + rTitle[i] + '</div>').data('number', rTitle[i]).attr('id', 'problem' + rTitle[i]).appendTo('#testpile').draggable({
containment: '.site-wrapper',
stack: '#testpile div',
cursor: 'move',
revert: true
});
$('<div>' + rText[i] + '</div>').data('number', rText[i]).attr('id', 'problem' + rText[i]).appendTo('#testpile');
}
$('#testdrop').droppable({
drop: handleDropEvent,
accept: '#testpile div'
});
function handleDropEvent(event, ui) {
var problemNumber = ui.draggable.data('number');
var problemCombination = problemDef + problemNumber;
ui.draggable.draggable('disable');
ui.draggable.draggable('option', 'revert', false);
phase++;
alert('ProblemCombination is "' + problemCombination + '", phase is "' + phase + '" ');
$("#testpile").children().hide();
generateProblems(problemCombination);
}
}
});
</script>
What am I doing wrong? The code worked pretty well before I split it up, but now clicking one of the buttons generate nothing.
This is not the right way to do. Keep your php away from html/js. You can't access to your html from another script which is not directly included in it.
Re-add your javascript part to index.html
In your php script return
something at the end like return json_encode($rTitle_array);
In your
jquery/ajax post, get the returned value and use it
A sample from the jquery doc:
var posting = $.post( url, { s: term } );
// Put the results in a div
posting.done(function( data ) {
var content = $( data ).find( "#content" );
$( "#result" ).empty().append( content );
});

Magento add to cart button not working

Yes, I've seen the other topics about this problem, but I couldn't solve the problem yet. So I do hope you can help me.
The problem is simple in my Magento shop www.koekentrommel.nl the add to cart button doesn't work. I'm a jquery newbie but I've tried the noconflict-code, but with no result. Can you please help? A shop without add to cart is as a car without tires...
Thanks a lot!
This is the view.phtml code:
<?php $_helper = $this->helper('catalog/output'); ?>
<?php $_product = $this->getProduct(); ?>
<script type="text/javascript">
var optionsPrice = new Product.OptionsPrice(<?php echo $this->getJsonConfig() ?>);
$.noConflict();
</script>
}.bind(productAddToCartForm);
productAddToCartForm.submitLight = function(button, url){
if(this.validator) {
var nv = Validation.methods;
delete Validation.methods['required-entry'];
delete Validation.methods['validate-one-required'];
delete Validation.methods['validate-one-required-by-name'];
// Remove custom datetime validators
for (var methodName in Validation.methods) {
if (methodName.match(/^validate-datetime-.*/i)) {
delete Validation.methods[methodName];
}
}
if (this.validator.validate()) {
if (url) {
this.form.action = url;
}
this.form.submit();
}
Object.extend(Validation.methods, nv);
}
}.bind(productAddToCartForm);
//]]>
</script>
Clearly your jQuery is conflicting with prototype. NoConflcit should have resolved it
You have 2 closing script tags, you need to delete the one after $.noConflict();
<script type="text/javascript">
$.noConflict();
</script> <-- Delete
}.bind(productAddToCartForm);
.....
</script>

Categories

Resources