I'm new here and I ask for your understanding
I am downloading from the script :
echo '<div id="xx">';
if ($nazwa == "1234") {
$nazwa_color = "red";
} else {
$nazwa_color = "black";
}
echo '<div style="padding-left:0px;float:left;margin-left:1px;"><input type="text" autocomplete="off"
style="font-family:Tahoma;text-indent:2px;text-align:left;font-size:12px;width:500px;height:29px;background-color : White ; color : ' . $nazwa_color . ';border-width:1px;border-style:ridge;border-color:rgb(208,208,208);"
name="nazwa" value="b" class="wyk_edit"></div>';
echo'</div>';
And in javascript :
$(this).parent().parent().parent().find(".xx").load("setup-wyklady/wyk_edit_proces.php #xx");
does not address the condition 'if'. Why?
Thanks, but not working. Maybe I show all.
This is the portion of the file that you want to replace the method of load:
$wyk_query1 = mysql_query("SELECT * FROM nazwy_wyklady WHERE id_wykladu <> 9999 ORDER BY nr") or die('Błąd zapytania');
while($wyk=mysql_fetch_array($wyk_query1)){ //begin loop
$id_wykladu=$wyk['id_wykladu'] ;
$nr=$wyk['nr'] ;
$nazwa=$wyk['nazwa'] ;
echo '<form action="../wyklady/setup-wyklady/wyk_edit_proces.php" method="post"> ';
echo '<div style="float:left;width:590px;margin-top:2px;background:none" >';
echo '<div style="padding-left:0px;float:left;margin-left:1px;"><input type="text" readonly="readonly"
style="font-family:Tahoma;text-indent:2px;text-align:center;font-size:12px;width:30px;height:29px;background-color : White ; color : black;border-width:1px;border-style:ridge;border-color:rgb(208,208,208);"
name="nr" value="'.$nr.'" class="wyk_edit_nr"></div>';
if($nazwa=="1234")
{
$nazwa_color = "red" ;
}
else
{
$nazwa_color = "black" ;
}
echo '<div style="padding-left:0px;float:left;margin-left:1px;" class="xx"><input type="text" autocomplete="off"
style="font-family:Tahoma;text-indent:2px;text-align:left;font-size:12px;width:500px;height:29px;background-color : White ; color : '.$nazwa_color.';border-width:1px;border-style:ridge;border-color:rgb(208,208,208);"
name="nazwa" value="'.$nazwa.'" class="wyk_edit"></div>';
echo '<div style="float:left;margin-left:15px;margin-top:1px;" >
<input style="display:none;cursor:pointer;width:25px;height:25px;background-color:White;color:rgb(193,135,107);" id="edit_button" title="zatwierdź zmiany" value="" class="wyk_edit_button"></div>' ;
echo '<input type="hidden" name="id_wykladu" value="'.$id_wykladu.' " class="wyk_edit_id"> ';
echo '</div>'; // 2a
echo '</form> ';
} //end of loop
and a script that loads (wyk_edit_proces.php):
$wyk_query1 = mysql_query("SELECT * FROM nazwy_wyklady WHERE id_wykladu ='$id_wykladu1'") or die('Błąd zapytania');
$wyk=mysql_fetch_array($wyk_query1) ;
$id_wykladu=$wyk['id_wykladu'] ;
$nr=$wyk['nr'] ;
$nazwa=$wyk['nazwa'] ;
echo '<form action="../wyklady/setup-wyklady/wyk_edit_proces.php" method="post"> ';
echo '<div style="float:left;width:590px;margin-top:2px;background:none" >';
echo '<div style="padding-left:0px;float:left;margin-left:1px;"><input type="text" readonly="readonly"
style="font-family:Tahoma;text-indent:2px;text-align:center;font-size:12px;width:30px;height:29px;background-color : White ; color : black;border-width:1px;border-style:ridge;border-color:rgb(208,208,208);"
name="nr" value="'.$nr1.'" class="wyk_edit_nr"></div>';
if($nazwa=="1234")
{
$nazwa_color = "red" ;
}
else
{
$nazwa_color = "black" ;
}
echo '<div style="padding-left:0px;float:left;margin-left:1px;"><input type="text" autocomplete="off"
style="font-family:Tahoma;text-indent:2px;text-align:left;font-size:12px;width:500px;height:29px;background-color : White ; color : '.$nazwa_color.';border-width:1px;border-style:ridge;border-color:rgb(208,208,208);"
name="nazwa" value="b" class="wyk_edit"></div>';
echo '<div style="float:left;margin-left:15px;margin-top:1px;" >
<input style="display:none;cursor:pointer;width:25px;height:25px;background-color:White;color:rgb(193,135,107);" id="edit_button" title="zatwierdź zmiany" value="" class="wyk_edit_button"></div>' ;
echo '<input type="hidden" name="id_wykladu" value="'.$id_wykladu.' " class="wyk_edit_id"> ';
echo '</div>';
echo '</form> ';
and javascript:
<script>
//-----------------------------------------------------------------ajax - wykłady
$(document).ready(function(){
$(".wyk_edit_button").click(function () {
var id_wykladu1 = $(this).parent().parent().parent().find(".wyk_edit_id").val();
var nr1 = $(this).parent().parent().parent().find(".wyk_edit_nr").val();
var nazwa1 = $(this).parent().parent().parent().find(".wyk_edit").val().trim();
// alert(id_wykladu1 + " " + nr1 + " " + nazwa1)
if(nazwa1 == "")
{
alert("puste");
}
else
{
$.ajax({
type : "POST",
url : "setup-wyklady/wyk_edit_proces.php",
data : {
id_wykladu : id_wykladu1,
nr : nr1,
nazwa : nazwa1
},
context: this,
success : function() {
$(this).parent().parent().parent().find(".wyk_edit").load("setup-wyklady/wyk_edit_proces.php", function(){
alert("Done");
});
if (!$(".popup:visible").length) {
$(".popup").fadeIn(1);
}
},
complete : function(r) {
},
error: function(error) {
}
});
}
});
$(".popup .bg, .popup .container").click(function() {
$(".popup").fadeOut(250);
});
});
</script>
What you think about async:false ?
It's because the jQuery .load-Method works asynchronus as mentioned in this article. Try to use the invoked callback-function:
$(randomstuff).load("test",function()
{
alert("I'm done");
}
Related
I'm trying to make htmlRows to work. When I select productcode I want to trigger func Choise() and fill price and name.
<script>
// get Product Code
<?php
$connect = new PDO("mysql:host=localhost;dbname=praktika", "root", "");
function fill_productCode($connect)
{
$output = '';
$query = "SELECT * FROM services";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
foreach ($result as $row) {
$output .= '<option value="' . $row["code"] . '">' . $row["code"] . '</option>';
}
return $output;
}
?>
var count = $(".itemRow").length;
$(document).on('click', '#addRows', function() {
count++;
var htmlRows = '';
htmlRows += '<tr>';
htmlRows += '<td><input class="itemRow" type="checkbox"></td>';
htmlRows += '<td><select id="selectUsers" onChange="Choice();" type="text" name="productCode[]" class="form-control" autocomplete="off"><option value="">Select</option><?php echo fill_productCode($connect); ?></select></td>';
// htmlRows += '<td><input type="text" id="serviceName" name="productName[]" class="form-control" autocomplete="off"></td>';
htmlRows += '<td><input type="text" id="productName_' + count + '" name="productName[]" class="form-control" autocomplete="off"></td>';
htmlRows += '<td><input type="number" name="quantity[]" id="quantity_' + count + '" class="form-control quantity" autocomplete="off"></td>';
htmlRows += '<td><input type="number" name="price[]" id="price_' + count + '" class="form-control price" autocomplete="off"></td>';
htmlRows += '<td><input type="number" name="total[]" id="total_' + count + '" class="form-control total" autocomplete="off"></td>';
htmlRows += '</tr>';
$('#invoiceItem').append(htmlRows);
});
var serviceName = new Array();
var price_1 = new Array();
var ful = new Array();
serviceName[0] = "";
price_1[0] = "";
ful[0] = "";
serviceName[1] = "Serverių instaliavimas";
price_1[1] = "544.99";
ful[1] = "Buddy Smith";
serviceName[2] = "Sąskaitų skaitmenizavimas";
price_1[2] = "111";
ful[2] = "Libbie Smith";
serviceName[3] = 4;
price_1[3] = "asmith";
ful[3] = "Andy Smith";
function Choice() {
//x = document.getElementById("users");
y = document.getElementById("selectUsers");
//x.value = y.options[y.selectedIndex].text;
document.getElementById("serviceName").value = serviceName[y.selectedIndex];
document.getElementById("price_1").value = price_1[y.selectedIndex];
document.getElementById("ful").value = ful[y.selectedIndex];
}
</script>
As mentioned in the comment, it is best to move PHP script to their own page.
PHP - getServices.php
<?php
$connect = new PDO("mysql:host=localhost;dbname=praktika", "root", "");
$statement = $connect->prepare("SELECT * FROM services");
$statement->execute();
$result = $statement->fetchAll();
$output = "";
foreach ($result as $row) {
$output .= '<option value="' . $row["code"] . '">' . $row["code"] . '</option>' . "\r\n";
}
echo $output;
?>
You can then GET this via AJAX when needed.
$.get("getServices.php", function(h){
$("#selectUsers").html(h);
});
This would make a GET Request and the PHP would output the HTML back to the request.
It would be better to set this more like an API. Where a GET request can get JSON data back and then manipulate as needed with jQuery.
jQuery
$(function() {
function getData(page) {
var results;
$.getJSON(page, function(data) {
results = data;
});
return results;
}
function addRow(tObj) {
var c = $("tbody tr", tObj).length;
var newRow = $("<tr>");
$("<td>").appendTo(newRow); // 0
$("<input>", {
class: "itemRow",
type: "checkbox"
}).appendTo($("td", newRow));
$("<td>").appendTo(newRow); // 1
var sUser = $("<select>", {
id: "selectUsers",
name: "productCode[]",
class: "form-control",
autocomplete: "off"
}).appendTo($("td", newRow).eq(1));
$("<option>").html("Select User").appendTo(sUser);
// Populate User Options
$.each(getData("getUsers.php"), function(i, u) {
$("<option>", {
value: u.code
}).html(u.name).appendTo(sUser);
});
$("<td>").appendTo(newRow); // 2
$("<input>", {
type: "text",
id: "productName_" + (c + 1),
name: "productName[]",
class: "form-control",
autofill: "off"
}).appendTo($("td", newRow).eq(2));
$("<td>").appendTo(newRow); // 3
$("<input>", {
type: "number",
id: "quantity_" + (c + 1),
name: "quantity[]",
class: "form-control quantity",
autofill: "off"
}).appendTo($("td", newRow).eq(3));
$("<td>").appendTo(newRow); // 4
$("<input>", {
type: "number",
id: "price_" + (c + 1),
name: "price[]",
class: "form-control price",
autofill: "off"
}).appendTo($("td", newRow).eq(4));
$("<td>").appendTo(newRow); // 5
$("<input>", {
type: "number",
id: "total_" + (c + 1),
name: "total[]",
class: "form-control total",
autofill: "off"
}).appendTo($("td", newRow).eq(5));
tObj.append(newRow);
}
$(document).on('click', '#addRows', function() {
addRow($("#invoiceItem"));
});
});
This would be potential PHP code:
PHP - getUsers.php
<?php
$connect = new PDO("mysql:host=localhost;dbname=praktika", "root", "");
$statement = $connect->prepare("SELECT * FROM users");
$statement->execute();
$result = $statement->fetchAll();
$output = array();
foreach ($result as $row) {
array_push($output, $row);
}
header('Content-Type: application/json');
echo json_encode($output);
$statement = null;
$connect = null;
?>
I'm working on a chat box and it's working fine but when we enter the text message and sent it after the message is sent it won't clear automatically. It will remain there even after posting the text, we need to clear it manually.
I have tried to change some code but couldn't solve the issue.
Code which I'm using in this.
<div class="row">
<div class="pull-left">
<h3><?php echo sprintf($this->lang->line("conv_with"), $user["username"]); ?></h3>
</div>
</div>
<div class="row">
<div class="main_container clearfix">
<div class="ibox-content-no-bg">
<div class="chat-discussion">
<?php
$last_conv = $last_conv->result_array();
$last_conv = array_reverse($last_conv);
foreach($last_conv as $message):
$activity_thumb = $message["thumb_url"];
if($message["thumb_url"] == "" || $message["photostatus"] == 0) {
$activity_thumb = base_url() . "images/avatar.png";
}
?>
<?php
if($message["user_id"] == $this->session->userdata("user_id"))
$align_message = "left";
else
$align_message = "right";
?>
<div class="chat-message clearfix <?php echo $align_message; ?>" data-id="<?php echo $message["id"]; ?>">
<?php
if($message["gender"] == 0) {
$gender_user_color = "male_color";
} else {
$gender_user_color = "female_color";
}
?>
<a class="nailthumb-msg-container" href="<?php echo base_url("user/profile/".$message["user_id"]) ?>"><img width="62" alt="" src="<?php echo $activity_thumb; ?>" class="message-avatar"></a>
<div class="message">
<a class="message-author <?php echo $gender_user_color; ?>" href="<?php echo base_url("user/profile/".$message["user_id"]) ?>"><?php echo $message["username"] ?></a>
<span class="message-date text-muted pm-date" title="<?php echo $message["date"]; ?>Z"></span>
<span class="message-content">
<?php echo $message["content"]; ?>
</span>
<span class="message-date-mob text-muted pm-date" title="<?php echo $message["date"]; ?>Z"></span>
</div>
</div>
<?php
endforeach;
?>
</div>
<div class="chat-message-form">
<div class="form-group">
<p class="lead emoji-picker-container">
<textarea id="pm-write" class="form-control message-input pm-write-answer-textarea" placeholder="<?php echo $this->lang->line("enter_message_here_placeholder"); ?>" name="message" data-emojiable="true"></textarea>
</p>
</div>
<div class="btn-reply-placeholder">
<a class="btn btn-primary btn-send-reply" href="#" data-user-id="<?php echo $user["uid"]; ?>" data-conv-id="<?php echo $current_conv->id; ?>"><?php echo $this->lang->line("send_reply_btn"); ?></a>
</div>
</div>
</div>
</div>
</div>
AJAX
$(document).ready(function() {
$('.nailthumb-msg-container').nailthumb();
$(".pm-date").timeago();
$(".message").emoticonize();
$(".chat-discussion").scrollTop(100000);
window.setInterval(function(){
var last_message_id = $(".chat-message:last").attr("data-id");
// Live refresh
$.ajax({
url: base_url + "pm/refresh_conv",
type: 'POST',
data: {conv_id : conv_id, last_message_id: last_message_id},
success: function(data) {
$.each(data.last_messages, function(i, item) {
var message = item;
var avatar = "";
if(message.thumb_url == null || message.photostatus == 0) {
avatar = base_url + "images/avatar.png";
} else {
avatar = base_url + message.thumb_url;
}
if(message.gender == 0) {
var gender_user_color = "male_color";
} else {
var gender_user_color = "female_color";
}
if(message.user_id == user_id) {
var msg_dir = "left";
} else {
var msg_dir = "right";
}
var block_msg = '<div class="chat-message ' + msg_dir + '" data-id="' + message.mid + '">';
block_msg += '<a class="nailthumb-msg-container" href="' + base_url + 'user/profile/' + message.user_id + '"><img width="62" alt="" src="' + avatar + '" class="message-avatar" /></a>';
block_msg += '<div class="message">';
block_msg += '<a class="message-author ' + gender_user_color + '" href="' + base_url + 'user/profile/' + message.user_id + '">' + message.username + '</a>';
block_msg += '<span class="message-date text-muted pm-date" title="' + message.date + 'Z"></span>';
block_msg += '<span class="message-content">';
block_msg += message.content;
block_msg += '</span>';
block_msg += '</div>';
block_msg += '</div>';
$(".chat-message").last().after(block_msg);
$('.nailthumb-msg-container').nailthumb();
$(".pm-date").timeago();
$(".message").emoticonize();
$(".chat-discussion").scrollTop(100000);
});
}
});
}, 2000);
$(".btn-send-reply").click(function(e) {
e.preventDefault();
$(':input[name="pmwrite"]').val(null);
var conv_id = $(this).attr("data-conv-id");
var user_id = $(this).attr("data-user-id");
var content = $(".emoji-wysiwyg-editor").html();
$(this).html('<i class="fa fa-circle-o-notch fa-spin"></i>');
$(this).addClass("disabled");
var that = $(this);
$.ajax({
url: base_url + "pm/send_reply",
type: 'POST',
data: {conv_id : conv_id, content: content, user_id : user_id},
success: function(data) {
var res = data.result;
if(res == 999) {
alert(not_logged_in_str);
that.html(send_reply_str);
that.removeClass("disabled");
} else if(res == 998) {
alert(write_something_str);
that.html(send_reply_str);
that.removeClass("disabled");
} else if(res == 500) {
alert(cant_demo_mode_str);
that.html(send_reply_str);
that.removeClass("disabled");
} else if(res == 997) {
alert(conv_not_exist_str);
that.html(send_reply_str);
that.removeClass("disabled");
} else if(res == 996) {
alert(user_blocked_you_str);
that.html(send_reply_str);
that.removeClass("disabled");
} else {
var avatar = "";
if(data.user.thumb_url == null || data.user.photostatus == 0) {
avatar = base_url + "images/avatar.png";
} else {
avatar = base_url + data.user.thumb_url;
}
$(".pm-write-answer-textarea").val("");
if(data.user["gender"] == 0) {
var gender_user_color = "male_color";
} else {
var gender_user_color = "female_color";
}
$('.nailthumb-msg-container').nailthumb();
$(".pm-date").timeago();
that.html(send_reply_str);
that.removeClass("disabled");
$(".chat-discussion").scrollTop(100000);
}
}
});
});
String.prototype.replaceArray = function(find, replace) {
var replaceString = this;
for (var i = 0; i < find.length; i++) {
replaceString = replaceString.replace(find[i], replace[i]);
}
return replaceString;
};
});
I expect the textarea to be cleared after someone send t the message but actual is the text will remain in textarea even after the message is sent.
I assume that this $(".emoji-wysiwyg-editor") is your element for your content. since this is the one you called in
var content = $(".emoji-wysiwyg-editor").html();
Try clearing this element after success by using this code since you're using a jquery here.
$(".emoji-wysiwyg-editor").html('');
Just add this line at the start of your AJAX success() function
$('#pm-write').empty();
Using pure Javascript
document.getElementById('pm-write').innerHTML = "";
It would look like this
$.ajax({
url: base_url + "pm/send_reply",
type: 'POST',
data: {conv_id : conv_id, content: content, user_id : user_id},
success: function(data) {
var res = data.result;
$('#pm-write').empty(); //Clean the textarea
//Other code
}
});
Using javascript, you can easily achieve this by setting an event listener on the text-area like this
document.addEventListener("DOMContentLoaded", function() {
var submitBtn = document.getElementsByClassName("btn-send-reply")[0];
submitBtn.addEventListener("click", function(){
document.getElementsByName("message")[0].value = "";
});
});
or in jQuery
$(document).ready(function(){
$('.btn-send-reply').click(function(){
$( "input[name*='message']" ).val("");
})
})
I really need some help i have been working on this all night and just cant get my function to work i have tried every thing and now i am at the point where it has to to handed in in a hour.
The
<input type="button" value="Sub" onclick = "alert('The text will be show!!'); return false;"/>
I put there works but when i try call my functions noting.
Any help would very much appreciated.
<!DOCTYPE html>
<html>
<style>
</style>
<head>
<script>
var score = 0;
function DoTotals() {
window.alert("sometext");
alert('sometext');
}
function getScore() {
window.alert("sometext");
alert("sometext");
alert('sometext');
var inputs = document.querySelectorAll("input");
for (int i = 0; i < inputs; i++) {
if (inputs[i].type == "radio" && inputs[i].checked && inputs[i].value == "correct") {
score += 1;
} else {
var userInputString = inputs[i].value;
var correctAnswer = inputs[i].getAttribute('data-correct');
if (userInputString != null && correctAnswer != null) {
if (userInputString.toUpperCase() == correctAnswer.toUpperCase()) {
score += 1;
}
}
}
}
document.getElementById("score").innerHTML = "You Scored " + score;
score = 0;
}
</script>
</head>
<body>
<input type="button" value="Sub" onclick="alert('The text will be show!!'); return false;" />
<table border="2">
<?php //Open the file with the questions $questionFile=f open( "testFile.txt", 'r'); $radioGroupId=0; //while the reader has npt reached the end of the file while(!feof($questionFile)){ //get line for text file $line=f gets($questionFile); echo '<tr>';
//If this line is a multiple choice question if(strpos($line, '#MC') !==f alse){ //break the line into substrings $breakDownLine=e xplode( ';',$line); //insert each element of the array into the table for ($i=0;$i<count($breakDownLine);$i++){ if($i==0){
//Remove the MC indicator $question=s tr_replace( "#MC", "",$breakDownLine[$i]); echo '<td style="border:2px solid red;">'; echo $question. '</td>'; } else{ echo '<td style="border:2px solid black;">'; if(strpos($breakDownLine[$i], '*')!=false){ $answerRemove=s
tr_replace( "*", "",$breakDownLine[$i]); echo $answerRemove. '<input type="radio" name="var'.$radioGroupId. '" value="correct">'; } else{ echo $breakDownLine[$i]. '<input type="radio" name="var'.$radioGroupId. '" value="incorrect">'; } } } } //If
this line is a True / False question else if(strpos($line, '#TF') !==f alse){ //break the line into substrings $breakDownLine=e xplode( ';',$line); for ($i=0;$i<count($breakDownLine);$i++){ if($i==0){ //Remove the MC indicator $question=s tr_replace(
"#TF", "",$breakDownLine[$i]); echo '<td style="border:2px solid red;">'; echo $question. '</td>'; } else{ echo '<td style="border:2px solid black;">'; if(strpos($breakDownLine[$i], '*')!=false){ $answerRemove=s tr_replace( "*", "",$breakDownLine[$i]);
echo $answerRemove. '<input type="radio" name="var'.$radioGroupId. '" value="correct">'; } else{ echo $breakDownLine[$i]. '<input type="radio" name="var'.$radioGroupId. '" value="incorrect">'; } } } } else if(strpos($line, '#FIB') !==f alse){ echo
'<td style="border:2px solid red;">'; while (true){ $pos=s trpos($line, "["); $pos2=s trpos($line, "]"); $pos3=$ pos2-$pos; $subAnswer=s ubstr($line,$pos+1,$pos3-1); if ($pos2===f alse) { echo $line; break; // no more blanks i.e. no more [. } else { $out=s ubstr($line,0,$pos); echo
$out; $line=s ubstr($line,$pos2+1,strlen($line)); echo '<input type="text" data-correct="'.$subAnswer. '">'; } } } echo '</tr>'; $radioGroupId++; } ?>
</table>
<button onClick="DoTotals()">Click me</button>
<p id="score"></p>
</body>
</html>
Instead of
for (int i = ...
write:
for (var i = ...
I have the following code that shuffles a selection I have in my database. Rather than having the results display all at one, I want to display a result one at a time with a delay between the results.
ie:
If I have 10 items in my database, I want one item to display, then a 3 second delay, then the second item to display, then a 3 second result, all the way until the last item (#10). Then possibly some sort of animation to it, like flying into the screen or the look of an item coming from a bag or something. (think picking a numbered order from 10 out of a bag).
I have been told that setInterval() could be an approach, but I have no idea how I could make this work with my code or if that is even the right approach.
How could I do this?
Here is how I shuffle the db results.
<form method="post">
<?php
foreach ($array as $result) {
$shuffle_firstname = htmlentities($result['firstname']);
$shuffle_lastname = htmlentities($result['lastname']);
$shuffle_id = htmlentities($result['id']);
$shuffle_username = htmlentities($result['username']);
$shuffle_email = htmlentities($result['email']);
?>
<div class="shuffle_results"><?php echo $shuffle_firstname . ' ' . $shuffle_lastname; ?></div>
<input type="hidden" name="firstname[]" value="<?php echo $shuffle_firstname; ?>">
<input type="hidden" name="lastname[]" value="<?php echo $shuffle_lastname; ?>">
<input type="hidden" name="id[]" value="<?php echo $shuffle_id; ?>">
<input type="hidden" name="username[]" value="<?php echo $shuffle_username; ?>">
<input type="hidden" name="email[]" value="<?php echo $shuffle_email; ?>">
<?php
}
?>
<input type="submit" value="Finalize Draft Order" name="insert">
</form>
UPDATE:
HTML File
$query = mysqli_query($con, "SELECT * FROM users WHERE `group` = 3");
echo 'Users to be given draft order: <br>';
$array = array();
while ($row = mysqli_fetch_assoc($query)) {
$array[] = $row;
echo $row['firstname'] . ' ' . $row['lastname'] . '<br>';
}
?>
<form method="POST" name="form">
<input type="submit" value="Create Draft Order" name="shuffle">
Shuffled results: <br>
<div id="results"></div>
<form method="post">
<input type="submit" value="Finalize Draft Order" name="insert">
</form>
<img id='paperBag' src="http://www.thecuriouscaterpillar.co.uk/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/b/a/bag_to_white.jpg" width="200px" />
//Test Shuffle
var displayResults = function(data){
var i = 0;
var interval = setInterval(function(){
if( i <= data.length){
console.log( data[i] );
//i++;
$('#results').append('<div class="result" style="display:none;">' +
'<div class="shuffle_results">' + data[i].firstname + ' ' + data[i].lastname + '</div>' +
'<input type="hidden" name="firstname[]" value="' + data[i].firstname + '">' +
'<input type="hidden" name="lastname[]" value="' + data[i].lastname + '">' +
'<input type="hidden" name="id[]" value="' + data[i].id + '">' +
'<input type="hidden" name="username[]" value="' + data[i].username + '">' +
'<input type="hidden" name="email[]" value="' + data[i].email + '">' +
'</div>');
$('.result').fadeIn(200);
i++;
} else {
clearInterval(interval);
}
}, 3000);
};
$(function(){
$('form').on('submit', function(e){
e.preventDefault();
$.post('shuffle_results.php', function(data){
var o = $.parseJSON(data);
displayResults(o);
});
});
});
//End test shuffle
PHP file
<?php
$con = mysqli_connect("localhost", "", "", "");
$query = mysqli_query($con, "SELECT * FROM users WHERE `group` = 3");
$array = array();
while ($row = mysqli_fetch_assoc($query)) {
$array[] = $row;
if (isset($_POST['shuffle'])) {
shuffle($array);
}
}
echo json_encode($array);
?>
You could try something like this: This is just a test using faux data in the fiddle. Is this close to what you are looking for?
Client (using ctwheels's CSS)
<form method="POST">
<input type="submit" value="Shuffle" name="shuffle">
</form>
<div id="#results"></div>
<script>
var displayResults = function(data){
var i = 0;
var interval = setInterval(function(){
if( i <= data.length){
$('#results').append('<div class="result" style="display:none;">' +
'<div class="shuffle_results">' + data[i].firstname + ' ' + data[i].lastname + '</div>' +
'<input type="hidden" name="firstname[]" value="' + data[i].firstname + '">' +
'<input type="hidden" name="lastname[]" value="' + data[i].lastname + '">' +
'<input type="hidden" name="id[]" value="' + data[i].id + '">' +
'<input type="hidden" name="username[]" value="' + data[i].username + '">' +
'<input type="hidden" name="email[]" value="' + data[i].email + '">' +
'</div>');
var $this = $('.shuffle_results:last');
$this.show().animate({
'left': 0 + 'px',
'bottom': $(document).height() - (lineheight * array.length) + 'px'
}, {
duration: time
});
i++;
} else {
clearInterval(interval);
}
}, 3000);
};
$(function(){
$('form').on('submit', function(e){
e.preventDefault();
$.getJSON('path-to-your-script.php', function(data){
displayResults(data);
});
});
});
</script>
Server
<?php
$con = mysqli_connect("localhost", "", "", "");
$query = mysqli_query($con, "SELECT * FROM users WHERE `group` = 3");
$array = array();
while ($row = mysqli_fetch_assoc($query)) {
$array[] = $row;
}
echo json_encode($array);
?>
One way you can do this is by hiding all the results using CSS and then one by one show the values and animate using jQuery and CSS animate.
The code below hides all the items in shuffle_results by default (in CSS).
Then the jQuery iterates through each item in that class and shows the element, then animates its left and bottom properties to give it the correct positioning. The duration is set with time.
The rotation animations are made with CSS keyframes.
JSFiddle
JS
var time = 3000;
var lineheight = 24;
var angle = 90;
$('.shuffle_results').each(function (i) {
var i = i;
var $this = $(this);
setTimeout(function () {
$this.show()
.animate({
'left': 0 + 'px',
'bottom': $(document).height() - (lineheight * (i + 1)) + 'px'
}, {
duration: time,
queue: false
});
}, time * i);
});
CSS
.shuffle_results {
display:none;
position:absolute;
left:70px;
bottom:100px;
z-index:-1;
-webkit-animation:spin 3s linear;
-moz-animation:spin 3s linear;
animation:spin 3s linear;
}
#-moz-keyframes spin {
0% {
-moz-transform: rotate(110deg);
}
100% {
-moz-transform: rotate(0deg);
}
}
#-webkit-keyframes spin {
0% {
-webkit-transform: rotate(110deg);
}
100% {
-webkit-transform: rotate(0deg);
}
}
#keyframes spin {
0% {
-webkit-transform: rotate(110deg);
transform:rotate(110deg);
}
100% {
-webkit-transform: rotate(0deg);
transform:rotate(0deg);
}
}
#paperBag {
position:absolute;
bottom:0px;
left:0px;
z-index:1;
}
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="shuffle_results">Michael Jackson</div>
<div class="shuffle_results">Bob Saget</div>
<div class="shuffle_results">Indiana Jones</div>
<div class="shuffle_results">Elmo</div>
<div class="shuffle_results">Elmer J. Fudd</div>
<img id='paperBag' src="http://www.thecuriouscaterpillar.co.uk/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/b/a/bag_to_white.jpg" width="200px" />
EDIT
To use this with AJAX, you can do something like the following for JS
var time = 3000;
var lineheight = 24;
var angle = 90;
var array = ["Michael Jackson", "Bob Saget", "Indiana Jones", "Elmo", "Elmer J. Fudd"]; //For testing purposes. Shows how it adds one item at a time. This 'mimicks' your AJAX script
var i=0;
var interval = setInterval(function () {
j=i;
i++;
if(array.length<=i) window.clearInterval(interval);
// Where array.length is the count returned from PHP (or you can return a boolean value and check if it's true or false. Something like this:
//if(clearInt === true)
//{
// window.clearInterval(interval);
//}
//else
//{
// Do stuff below
$('#paperBag').before("<div class='shuffle_results'>"+array[j]+"</div>");
// Where array[j] represents the value returned from ajax
var $this = $('.shuffle_results:last');
$this.show()
.animate({
'left': 0 + 'px',
'bottom': $(document).height() - (lineheight * (j + 1)) + 'px'
}, {
duration: time
});
}, time);
So you should have something similar to this: (note that this is untested - feel free to edit this answer if you encounter any bugs from it). To prevent duplicate results you can send the array from your JS function to your PHP function and subtract one array from the other to get the remaining values (use the database row's unique index and populate the JS array with those values and then subtract an array with all the values in your PHP script from it to get the remaining values. (using array_diff perhaps: http://php.net/manual/en/function.array-diff.php)
var time = 3000;
var lineheight = 24;
var angle = 90;
var array = [];
var interval = setInterval(function () {
$getJSON("something.php", {array: array}, function(result)
{
if(result.clearInterval === true)
{
window.clearInterval(interval);
}
else
{
array.push(result.firstName+" "+result.lastName);
$('#paperBag').before("<div class='shuffle_results'>"+result.firstName+" " +result.lastName+"</div>");
var $this = $('.shuffle_results:last');
$this.show()
.animate({
'left': 0 + 'px',
'bottom': $(document).height() - (lineheight * array.length) + 'px'
}, {
duration: time
});
}
});
}, time);
I am creating a wordpress theme with theme options in wordpress. I like to add a dynamic add and remove textbox using jquery inside the theme settings page. My query is,
theme_settings.php
<?php
function theme_settings_init(){
register_setting( 'theme_settings', 'theme_settings' );
}
function add_settings_page() {
add_menu_page( __( 'Theme Settings' ), __( 'Theme Settings' ), 'manage_options', 'settings', 'theme_settings_page');
}
//add actions
add_action( 'admin_init', 'theme_settings_init' );
add_action( 'admin_menu', 'add_settings_page' );
//start settings page
function theme_settings_page() {
if ( ! isset( $_REQUEST['updated'] ) )
$_REQUEST['updated'] = false;
?>
<div>
<div id="icon-options-general"></div>
<h2><?php _e( 'Theme Settings' ) //your admin panel title ?></h2>
<?php
//show saved options message
if ( false !== $_REQUEST['updated'] ) : ?>
<div><p><strong><?php _e( 'Options saved' ); ?></strong></p></div>
<?php endif; ?>
<form method="post" action="options.php">
<?php settings_fields( 'theme_settings' ); ?>
<?php $options = get_option( 'theme_settings' ); ?>
<div id='TextBoxesGroup'>
<?php
$counter = 1;
while (get_option('textbox'.$counter) && $counter <= 10) {
echo '<div id="TextBoxDiv'.$counter.'">
<input type="textbox" id="theme_settings[textbox'.$counter.'] name="theme_settings[textbox'.$counter.']" >
</div>';
$counter++;
}
?>
</div>
<input type='button' value='Add Button' id='addButton'>
<input type='button' value='Remove Button' id='removeButton'>
<p><input name="submit" id="submit" value="Save Changes" type="submit"></p>
</form>
</div><!-- END wrap -->
<?php
}
and my javascript file is:
$(document).ready(function(){
var counter = 2;
$("#addButton").click(function () {
if(counter>10){
alert("Only 10 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
$('<div id="TextBoxDiv'+counter+'"></div>').append(
'<input type="text" name="theme_settings[textbox' + counter +
']" id="theme_settings[textbox' + counter + ']" value="" >').appendTo('#TextBoxesGroup');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function () {
if(counter==1){
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
$("#getButtonValue").click(function () {
var msg = '';
for(i=1; i<counter; i++){
msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
}
alert(msg);
});
});
Now my question is, In the theme settings page, the add action and remove action works very fine but while saving the theme setting options the added textbox dissappears. It happens while refreshing the page too.
Please anyone help me how to keep those added textbox remains same if saving the theme options page.
Use .append() instead of .after().html(). This way your code goes inside the corresponding div element. I made use of jQuery also.
newTextBoxDiv.after().html(
'<input type="text" name="theme_settings[textbox' + counter +
']" id="theme_settings[textbox' + counter + ']" value="" >');
should be
$('<div id="TextBoxDiv'+counter+'"></div>').append(
'<input type="text" name="theme_settings[textbox' + counter +
']" id="theme_settings[textbox' + counter + ']" value="" >').appendTo('#TextBoxesGroup');
To make the text boxes appear you need a while loop like this:
$counter = 1;
while (get_option('textbox'.$counter) && $counter <= 10) {
echo '<div id="TextBoxDiv'.$counter.'">
<input type="textbox" id="theme_settings[textbox'.$counter.'] name="theme_settings[textbox'.$counter.']" >
</div>';
$counter++;
}
When you save them you could do this:
$counter = 0;
while (isset($_POST['theme_settings']['textbox'.$counter']) && $counter <= 10) {
update_option('textbox'.$counter, $_POST['theme_settings']['textbox'.$counter']);
$counter++;
}
// now remove the rest of them if they were previously set
// for example we now set only 5 of them and there were 10 before
// continue with counter from where we left in the previous while loop
while ($counter <= 10) {
update_option('textbox'.$counter, false);
$counter++;
}
EDIT:
function theme_settings_page() {
$updated = false;
if (isset($_REQUEST['updated'])) {
update_option('theme_settings', $_POST['theme_settings']);
$updated = true;
}
// ....
if ($updated) {
echo '<div><p><strong>';
_e( 'Options saved' );
echo '</strong></p></div>';
}
$counter = 1;
$options = get_option('theme_settings');
while (isset($options['textbox'.$counter])) {
echo '<div id="TextBoxDiv'.$counter.'">
<input type="textbox" id="theme_settings[textbox'.$counter.'] name="theme_settings[textbox'.$counter.']" value="'.$options['textbox'.$counter].'" />
</div>';
$counter++;
}
echo '<input type="hidden" name="updated" value="1" />';
// the rest of your form
}