add option to select dynamically using jqtransform - javascript

I am using the plugin jqtransform to dynamically add options to a select using Ajax. Here I leave my script. Could you tell me what I have to do to see my new options?
<script type="text/javascript" >
var path = '<?php echo base_url() ?>';
$(document).on('ready', function() {
cargarJugadores();
$('#equipos').change(cargarJugadores);
});
function cargarJugadores() {
var codEquipo = $('#equipos').val();
$.getJSON(path + 'traspasos/devuelveJugadoresPorId', {id: codEquipo}, function(resp) {
console.log("->", resp);
$('#jugadores').empty();
$.each(resp, function(indice, valor) {
option = $('<option></option>', {
text: valor,
value: indice
});
$('#jugadores').append(option);
});
});
$('#jugadores').jqTransSelect(true);
}
</script>

Related

Not found ID When made in an external select db with ajax for use function click js

I'm designing an admin panel full Ajax and i have a problem...
In a Page i select information db with ajax like this :
html
<body>
<div id="loadbox"></div>
<script src="jquery.js"></script>
<script src="script.js"></script>
</body>
js
$(document).ready(function() {
show_all();
});
function show_all() {
work = "select";
$.ajax({
type: "POST",
url: "server.php",
data: "work=" + work,
success: function(data) {
$("#loadbox").html(data);
}
});
}
and server.php file :
$pdo = new PDO('mysql:host=localhost;dbname=test','root','');
if(isset($_POST['work'])){
$work = $_POST['work'];
if ($work == 'select') {
$query = $pdo->query("SELECT * FROM t1");
while ($s = $query->fetch()) {
$name = $s['name'];
$family = $s['family'];
echo '<div id="xRight">'.$name.'</div>';
echo '<div id="xLeft">'.$family.'</div><br>';
}
}
}
Now I need to use the id xRight for this cod :
$("#xRight").click(function(){
$(this).addClass("vv");
});
But because div and id made in server.php file . id to be not found for use
How can I fix this problem ?!
i think it's working for you
$(document).on("click","#xRight",function(event) {
// $(this).addClass("vv");
$(event.target).addClass("vv");
});
Try This
$("#parent_container_of_xRight").on('click','#xRight',function(){
//my cod js
});
Write the code :-
$("#xRight").click(function(){
//my cod js
});
inside document.ready function . For example :-
$( document ).ready(function() {
$("#xRight").on("click",function(){
//my cod js
});
});

Change checkbox + label jquery

I got multiple checkboxes and labels and when the answer is correct I want to change the background color of the selected checkbox and label
<input type="checkbox" id="a" class="check-with-label" />
<label for="a" class="question_box">
<?php echo $vraag[0]['A'] ?>
</label>
<input type="checkbox" id="b" class="check-with-label" />
<label for="b" class="question_box">
<?php echo $vraag[0]['B'] ?>
</label>
and when the user presses submit it calls an ajax call to a script to check if it is the correct answer or not.
$('#bottom').on('click', function(){
$('#antwoorden input:checked').each(function() {
var selected = $(this).attr('id');
//var selected_box = this;
selected = selected.toUpperCase();
var data = {
vraag_nummer : <?php echo $vraag[0]['id'] ?>,
antwoord : selected
};
console.log(data);
$.ajax({
type: 'POST',
url : 'includes/check_correct.php',
data: data,
success: function(data) {
if(data.correct){
this.css('background-color', 'green');
//selected_box.css('background-color', 'green');
} else {
this.css('background-color', 'red');
}
},
error: function(err) {
console.log('error');
console.log(err);
}
});
});
});
problem is I don't know how to call the correct box because when the user presses submit the this variable is now the submit button and not the checked box (There can only be one checkbox selected at the time_.
So the question is how do I replace the background color of the selected AND the correct box from
.check-with-label:checked + .question_box {
background-color: orange;
}
to
background-color:green
(and for incorrect red)
Try changing the label instead of this
You've already got the ID of the label
(var selected = $(this).attr('id');)
Which will probably return a/b/c/d and then use
$('label[for="'+selected+'"]').css('background-color', 'green'); //or red in the else statement
this styles the label for the selected id, in this case d
the code above basicly means:
$('label][for="d"].css('background-color','green'); //or red
but then using the chosen variable
Goodluck!
In success use selected_obj.css instead of this.selected and pass $(this) to selected_obj
$('#bottom').on('click', function(){
$('#antwoorden input:checked').each(function() {
var selected = $(this).attr('id');
var selected_obj = $(this);
//var selected_box = this;
selected = selected.toUpperCase();
var data = {
vraag_nummer : <?php echo $vraag[0]['id'] ?>,
antwoord : selected
};
console.log(data);
$.ajax({
type: 'POST',
url : 'includes/check_correct.php',
data: data,
success: function(data) {
if(data.correct){
selected_obj.css('background-color', 'green');
//selected_box.css('background-color', 'green');
} else {
selected_obj.css('background-color', 'red');
}
},
error: function(err) {
console.log('error');
console.log(err);
}
});
});
});
Try this
$('#bottom').on('click', function(){
$('#antwoorden .check-with-label').each(function() {
var selected = $(this).attr('id');
var isChecked = $(this).is(':checked'));
if (!isChecked) {
return;
}
var selected_obj = $(this);
//var selected_box = this;
selected = selected.toUpperCase();
var data = {
vraag_nummer : <?php echo $vraag[0]['id'] ?>,
antwoord : selected
};
console.log(data);
$.ajax({
type: 'POST',
url : 'includes/check_correct.php',
data: data,
success: function(data) {
if(data.correct){
selected_obj.css('background-color', 'green');
} else {
selected_obj.css('background-color', 'red');
}
},
error: function(err) {
console.log('error');
console.log(err);
}
});
});
});
After the page is rendered and displayed to user, PHP will no longer run. Therefore, in your $('#bottom').on('click' function, the PHP code won't work. The trick is to store that information when building the page, such as by writing it into a data attribute or some such.
Inside the AJAX success function the $(this) object is not available. Set it to a global variable and you will be able to access the value.
/* javascript/jQuery */
$('#bottom').on('click', function(){
$('#antwoorden input:checked').each(function() {
var selected = this.id; //faster, same result
$this = $(this);
selected = selected.toUpperCase();
var data = {
//change next line - PHP finished running
vraag_nummer : $this.attr('data-vn'),
antwoord : selected
};
console.log(data);
$.ajax({
type: 'POST',
url : 'includes/check_correct.php',
data: data,
success: function(data) {
if(data.correct){
$this.css('background-color', 'green');
} else {
$this.css('background-color', 'red');
}
},
error: function(err) {
console.log('error');
console.log(err);
}
});
});
});
<!-- HTML: -->
<input id="vraag_nummer" data-vn="<?php echo $vraag[0]['id'] ?>" type="text" />

Creating textarea and buttons dynamically

I am facing issues with creating a dynamic textarea and 'Add' and 'Edit' buttons for every new paragraph.
DEMO of what I have managed so far:
The 'Add' button is for creating new paragraphs. The user should see a textarea where they enter the content for new paragraph. The first time they click 'Add' button, the text on the button will change to 'Save', the second time they click 'Save' it should append the paragraph to the div and assign it a unique id, which will be used to reference it with the new 'Add' and 'Edit' buttons.
The 'Edit' button is for editing the paragraph from which the 'Edit' button was clicked. To make the paragraph editable I'm using jquery editable (jeditable). Below are appropriate links to jeditable plugin:
plugin documentation
jeditable live demo
All the paragraph load from the back-end. Using PHP to load paragraphs:
<div class="paragraphs">
<?php
foreach($notes['children'] as $overview) :
if ($overview['type'] == 'Paragraph') :
?>
<div id="block1">
<p class='edit1'><?php echo $overview['content']; ?></p>
<p>
<?php if (isset($subject) && $subject==true) : ?>
<div id="para1">
<p><textarea cols="40" rows="2" id="textarea1"></textarea></p>
<button id="add1" class="add1 success tiny">Add</button>
<button id="startEdit1" class="canEdit1 tiny">Edit</button>
</div>
<?php endif; ?>
</p>
</div>
<?php endif; ?>
<?php endforeach; ?>
</div>
The 'Add' and 'Edit' button functionality:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="<?php echo base_url(); ?>assets/teachers/js/jquery.jeditable.min.js"></script>
<script>
var $subject_id = "<?php echo $subject_id ?>";
var $teacher_id = "<?php echo $teacher_id ?>";
// Define our elements
var $lock = false;
//Make the elements editable
function makeThingsEditable() {
$editables.editable({
emptyMessage : '<em>Please write something...</em>',
callback : function( data ) {
$info.hide();
$info.eq(0).show();
}
});
}
function ajaxRequest(data, method_url, request_type) {
$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader('HTTP/1.1', '200');
}
});
var eurl = "<?php echo base_url(); ?>edit_flow/" + method_url;
var params = 'inputJson=' + data;
var post = $.ajax({
type: request_type,
url: eurl,
data: params,
success: function(result) {
console.log('result: '+result);
console.log('data: '+params);
},
async: false
});
//alert(post.responseText);
return post.responseText;
console.log(post.responseText);
}
// Edit paragraph button
// Button that toggles the editable feature
var i = 1;
var $editables = $('.edit'+i);
$('.canEdit'+i).click(function() {
if( $editables.is(':editable') ) {
//need to call save action here and pass in updated JSON
if ($(this).text() == 'Save changes')
{
var text = $(".edit"+i).text();
// ajax request
var datum = '{"subject_id":'+$subject_id+',"teacher_id":'+$teacher_id+',"editedContent":"'+text+'"}';
ajaxRequest(datum, 'editNotes', 'POST'); // POST request on editNotes
ajaxRequest(datum, 'loadNotes', 'GET'); // GET request on loadNotes
// jquery request
$.get( "<?php echo base_url(); ?>edit_flow/loadNotes", function( data ) {
var data = '{"subject_id":'+$subject_id+', "teacher_id":'+$teacher_id+', "editedContent":"'+text+'"}';
//console.log(data);
alert( data );
});
}
$editables.editable('destroy');
this.innerHTML = 'Edit';
i++;
} else {
makeThingsEditable();
this.innerHTML = 'Save changes';
// TODO h4kl0rd: make $editables selectable
}
});
// Add paragraph button
i = 1;
$('#textarea'+i).hide();
$('#add'+i).click(function(){
if ( $(this).text() == "Add" ) {
$('#textarea'+i).show();
$(this).text('Save');
$('#textarea'+i).focus(function() {
this.select();
});
}
else if ( $(this).text() == "Save" ) {
if ($('#textarea'+i).val() == ''){
alert('Enter something...');
} else {
$(this).text("Add");
$('#textarea'+i).hide();
var overview = $('#textarea'+i).val();
i++;
$('.paragraphs').append('<div id="block'+i+'"><p class="edit'+i+'">'+overview+'</p><div id="para'+i+'"><p><textarea cols="40" rows="2" id="textarea'+i+'"></textarea></p><button id="add'+i+'" class="add'+i+' success tiny">Add</button><button id="startEdit'+i+'" class="canEdit'+i+' tiny">Edit</button></div></div>');
}
}
});
</script>
Any help is appreciated.
change these:
$('.canEdit'+i).click(function() {
$('#add'+i).click(function(){
to these:
$(document).on('click', '.canEdit'+i, function() {
$(document).on('click', '#add'+i, function() {
What seemed to me is your buttons are dynamic and they can't take direct event binding. So instead you have to delegate the event to the closest static parent which is $('.paragraphs') or to $(document) itself because it is always available.
So if you are using closest static parent then you have to put your event handlers inside doc ready and if you are using $(document) then its not needed.
$(function(){
var i = 1;
var $editables = $('.edit'+i);
$('.paragraphs').on('click', '.canEdit'+i, function() {
// all your edit stuff
});
$('.paragraphs').on('click', '#add'+i, function() {
// all your addstuff
});
});

how to post the database value to next page using ajax

i am trying to post the database retrieved value to next page using ajax.i tried but it not posting, can any one guide me how to do it
php
connected with database
$sql = "SELECT * FROM `billingdatainputandexport` WHERE id='1'";
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);
//print $sql;
$billingmonth=$rows['billingmonth'];
i want to pass this billing month to selectsuppliercostprice.php.
javascript
$(document).ready(function() {
$("#supplier").on("change", function() {
var billingmonth='$billingmonth';
var supplier = document.getElementById("supplier").value;
var mcc = document.getElementById("mcc").value;
var mnc = document.getElementById("mnc").value;
$.post('selectsuppliercostprice.php', { org: supplier,mcc: mcc,mnc: mnc,billingmonth: billingmonth }, function(result) {
$('#suppliercost').html(result);
}
);
});
});
selectsuppliercostprice.php.
$billingmonth=$_POST['billingmonth'];
Can you try this,
PHP
$billingmonth=$rows['billingmonth'];
echo '<input type="hidden" id="billingmonth" name="billingmonth" value="'.$billingmonth.'">'; // added hidden input
Javascript:
$("#supplier").on("change", function() {
var billingmonth= $('#billingmonth').val();
...
});
The post variable is $_POST not $POST so ... that should be right:
$billingmonth = $_POST['billingmonth'];
Also in Javascript you have to print the billingmonth variable. Javascript can't handle php-variables:
var billingmonth='$billingmonth';
to
var billingmonth='<?php echo $billingmonth; ?>';
Here is the latest code : u missed i guess the php tag inside ur script tag now try :)
$(document).ready(function() {
$("#supplier").on("change", function() {
var billingmonth='<?php echo $billingmonth ?>';
var supplier = document.getElementById("supplier").value;
var mcc = document.getElementById("mcc").value;
var mnc = document.getElementById("mnc").value;
$.post('selectsuppliercostprice.php', { org: supplier,mcc: mcc,mnc: mnc,billingmonth: billingmonth }, function(result) {
$('#suppliercost').html(result);
}
);
});
});
make hidden field and store your value in that and read that value in javascaript and pass it with ajax
<input type="hidden" name="some_name" value="<?php echo $billingmonth?>" id="some_name"/>
javascript code
$(document).ready(function() {
$("#supplier").on("change", function() {
var billingmonth=document.getElementById('billingmonth').value;
var supplier = document.getElementById("supplier").value;
var mcc = document.getElementById("mcc").value;
var mnc = document.getElementById("mnc").value;
$.post('selectsuppliercostprice.php', { org: supplier,mcc: mcc,mnc: mnc,billingmonth: billingmonth }, function(result) {
$('#suppliercost').html(result);
}
);
});
});
if you don't want to use it anyother place than
var billingmonth= '<?php echo $billingmonth?>';
Just Try.
Store $billingmonth value into any hidden input.
<input type="hidden" name="billing_month" id="billing_month" value="<?php echo $billingmonth; ?>"/>
Retrieve $billingmonth value in jQuery ready function using Hidden input id.
$(document).ready(function() {
$("#supplier").on("change", function() {
var billingmonth=$("#billing_month").val();
var supplier = $("#supplier").val();
var mcc = $("#mcc").val();
var mnc =$("#mnc").val();
$.post('selectsuppliercostprice.php', { org: supplier,mcc: mcc,mnc: mnc,billingmonth: billingmonth }, function(result) {
$('#suppliercost').html(result);
}
);
});
});

jQuery AJAX with PHP to upload contents to MYSQL DB

I am looking for a jQuery AJAX script alongside a PHP script that allows for the storage of information on a button click. The function defined within the jQuery should take three variables, all of which are defined pre-method call. I have the basis of operation complete but at the end of all operations - after the button is clicked and some time has passed - no data is added to the appropriate mysql database.
Here is my jQuery function "store"
<script type="text/javascript">
function store(ud, ld, tp) {
$.ajax({
url: 'http://www.exampledomain.com/folder/store.php',
type: 'POST',
data: 'ud='+ud+'&ld='+ld+'&tp='+tp
success : function() {
alert("WORKED!");
},
error : function() {
alert("DIDN'T WORK!");
},
complete : function() {
}
});
}
</script>
Here is the store.php file (very basic I know, I have also yet to secure this script via sanitizing user input)
<?php
require ('../mysqli_connect.php');
$errors = 0;
if(isset($_POST['ud']) && is_numeric($_POST['ud'])) {
$ud = $_POST['ud'];
} else {
++$errors;
}
if(isset($_POST['ld']) && is_numeric($_POST['ld'])) {
$ld = $_POST['ld'];
} else {
++$errors;
}
if(isset($_POST['tp'])) {
$tp = strip_tags(stripslashes($_POST['tp']));
} else {
++$errors;
}
if($errors == 0) {
$q = "INSERT INTO table_name (column_1, column_2, column_3, column_4) VALUES ('$ld', '$ud', NOW(), '$tp')";
mysqli_query($mysqli, $q);
} else {
echo 'There was a problem!';
}
?>
Assume that I have onclick="store(3, 3, A)" as an attribute for a certain element. How can I fix this? If I remove the onclick attribute how do I pass the necessary parameters to the jQuery function? I appreciate any and all help!
<-- EDIT -->
New jQuery & AJAX Script ...
<script type="text/javascript">
function store(ud, ld, tp) {
$.ajax({
url: 'http://www.exampledomain.com/folder/store.php',
type: 'POST',
data: 'ud='+ud+'&ld='+ld+'&tp='+tp,
error : function() {
alert("error");
},
success : function(data) {
alert(data);
},
complete : function() {
alert("complete");
}
});
}
$(function () {
$("a.rec").on("click", function () {
var $this = $(this),
ud = $this.data("ud"),
ld = $this.data("ld"),
tp = $this.data("tp");
store(ud, ld, tp);
});
});
</script>
Revised PHP
<?php
if($_SERVER['REQUEST_METHOD'] === "POST"){
require ('../mysqli_connect.php');
$errors = 0;
if(isset($_POST['ud'])) {
$ud = $_POST['ud'];
} else {
++$errors;
}
if(isset($_POST['ld'])) {
$ld = $_POST['ld'];
} else {
++$errors;
}
if(isset($_POST['tp'])) {
$tp = $_POST['tp'];
} else {
++$errors;
}
if($errors == 0) {
$q = "INSERT INTO table_name (column_1, column_2, column_3, column_4) VALUES ('$ld', '$ud', NOW(), '$tp')";
mysqli_query($mysqli, $q);
} else {
echo 'There was a problem!';
}
} else {
$url = 'http://www.exampledomain.com/error.php';
ob_end_clean();
header("Location: $url");
exit();
}
?>
Now for my HTML
<li>
<div class="sample classes">
<a class="rec" data-ud="13" data-ld="10" data-tp="SCI">
<input type="submit" title="Something" value="Something" />
</a>
</div>
</li>
However, when this button is clicked, it still does not do anything!
As you said onclick is something you are going to want to avoid. This is how you do it.
$(function () { //This function will be ran when the page loads
$(".button-class").on("click", function () { //This will run when any button is clicked
var $this = $(this),
ud = $this.data("ud"),
ld = $this.data("ld"),
tp = $this.data("tp");
store(ud, ld, tp);
});
});
HTML
<input type="button" class="button-class" data-ud="3" data-ld="3" data-tp="A"/>
I find it easier to use JSON and pass variables in an object to the server:
<script>
(function(){
var store = function (ud, lrid, type) {
var data = {
ud:ud,
lrid:lrid,
type:type
};
$.ajax({
url: 'http://www.exampledomain.com/folder/store.php',
type: 'POST',
data: data,
success : function(data) {
alert(data);
},
error : function() {
alert("DIDN'T WORK!");
},
complete : function() {
}
});
};
$('#btn').on('click', function(){
store(1,2,3);
});
}());
</script>
Use this script to test you are getting the variables on the server side:
<?php
# Put this in http://www.exampledomain.com/folder/store.php to test it works
if($_SERVER['REQUEST_METHOD'] === "POST"){
if(
isset($_POST['ud']) &&
isset($_POST['lrid']) &&
isset($_POST['type'])
)
{
$var = $_POST['ud'] . ", ".$_POST['ud'] . ", ".$_POST['type'] ." passed successfully via ajax!";
echo json_encode($var);
}
}
?>

Categories

Resources