Ajax with bootstrap.TbSelect2 (Yii) - php

I have a Select whose contents are changed when another Select is changed.
On change ajax runs a function in my controller to do this:
$this->renderPartial("_townsselect", array('country'=>$country));
It gets $country from a $_GET.
_townselect.php
$towns= $this->townsselect($country);
$this->widget('bootstrap.widgets.TbSelect2', array(
'name'=>'clienttown',
'asDropDownList' => true,
'data' => $towns
));
townsselect() creates an array structured as: $towns[town-id]='TownName'
When the page is loaded normally it also runs the previous renderPartial with $country set manually as a default.
So it is calling the same code both times. However on page load the Tbselect2 is shown correctly (correct styling, includes js support which gives it a search box, etc...), but when I use ajax a standard Select is used with limited styling. In fact the code produced is different:
Result after page load
<div class="select2-container" id="s2id_clienttown" style="width: 220px">
<a href="#" onclick="return false;" class="select2-choice" tabindex="-1">
<span>Accrington</span>
<abbr class="select2-search-choice-close" style="display:none;"></abbr>
<div>
<b></b>
</div>
</a>
<div class="select2-drop select2-with-searchbox select2-drop-active select2-offscreen" style="display: block;">
<div class="select2-search">
<input type="text" autocomplete="off" class="select2-input" tabindex="-1">
</div>
<ul class="select2-results"></ul>
</div>
</div>
<select name="clienttown" id="clienttown" style="display: none;">
<option value="Select">Select</option>
...
</select>
</div>
Where as after the ajax only the Select is generated.
Temporary Solution
I managed to get this working in some form. Instead of recreating the whole select box I have altered the JQuery code to clear all options inside the Select and refill it with the new list.
The new list comes comes from a JSON string returned by the ajax. Which is processed as follows:
var towns = $.parseJSON(resp);
$('#clienttown option:gt(0)').remove(); //remove all options, but leave default 'Select A Town' option
var sel = $('#clienttown');
$.each(towns, function(id, town){
sel.append($("<option></option>").attr("value", id).text(town));
});
I've put this here in case it helps someone else trying to achieve a similar thing.
Howver I would still be interested to know why yiibooster/bootstrap does not work when rendered after ajax. And if there is a way to make it work, as this solution wont work unless the input is first rendered on page load.

I know this is old but have you tried the following to get the after Ajax rendering to work.
// Notice the ,false, true at the end of renderpartial
$this->renderPartial("_townsselect", array('country'=>$country), false, true);

Related

Dynamically update dropdown based on previous selection with PHP PDO

This has been answered before, however I'm asking again for two reasons: I can't find any resources that utilize PDO, and regardless of that, all of the ones I've found consist of code without any comments or explanations, which makes it hard to interpret and adapt them to my use case.
I need to be able to make a dropdown dynamically update itself based on the selection of the previous one, and if I change that selection, it should re-update itself without having to submit the form or reload the page.
I've updated the code with what I've learned and found so far, but it's still not working properly. Everything works up to the point where the second dropdown should begin loading values.
HTML:
<div class="form-group row">
<label class="col-sm-2 form-control-label" onchange="productorInfo(this.value);">Codigo Productor (*)</label>
<div class="col-sm-4">
<select name="vendedor_codigo">
<?php foreach ($dd_productor_result as $dd_productor_display) : ?>
<option value="<?= $dd_productor_display['vendedor_codigo']; ?>">
<?= $dd_productor_display['vendedor_codigo']; ?>
</option>
<?php endforeach; ?>
</select>
</div>
<label class="col-sm-2 form-control-label">Nombre (*)</label>
<div class="col-sm-4">
<select id="ajax-vendedor" name="vendedor_nombre">
<?php foreach ($ajax_productor_result as $dd_productor_display) : ?>
<option placeholder="Seleccione codigo" value="<?= $dd_productor_display['vendedor_nombre']; ?>">
<?= $dd_productor_display['vendedor_nombre']; ?>
</option>
<?php endforeach; ?>
</select>
</div>
</div>
Ajax script:
function productorInfo(id) {
$.ajax({
type: "GET",
url: "/controller/produccion/db_ajax_update.php",
data: "mainid =" + id,
success: function (result) {
$("#ajax-vendedor").html(result);
}
});
};
First dropdown PHP code:
$dd_productor = "SELECT vendedor_codigo FROM lista_productores";
$productor_stmt = $pdo->prepare($dd_productor);
$productor_stmt->execute();
$dd_productor_result = $productor_stmt->fetchAll();
Second dropdown (ajax call):
if(isset($_GET['mainid'])){
productorInfo($_GET['mainid']);
$prod_value = productorInfo($_GET['mainid']);
}
$ajax_productor = "SELECT vendedor_nombre FROM lista_productores WHERE vendedor_codigo = {$prod_value}";
$productor_stmt = $pdo->prepare($ajax_productor);
$productor_stmt->execute();
$ajax_productor_result = $productor_stmt->fetchAll();
The onchange call should be on the select element not on the label
<label class="col-sm-2 form-control-label">Codigo Productor (*)</label>
<select name="vendedor_codigo onchange="productorInfo(this.value)">
But also it occurs to me you may not quite understand the process. Your ajax call won't be fired when the page loads so this bit:
<select id="ajax-vendedor" name="vendedor_nombre">
<?php foreach ($ajax_productor_result as $dd_productor_display) : ?>
<option placeholder="Seleccione codigo" value="<?= $dd_productor_display['vendedor_nombre']; ?>">
<?= $dd_productor_display['vendedor_nombre']; ?>
</option>
i would think is giving you undefined variable warnings (unless you are setting $ajax_productor_result initially in some way)
Responses from ajax are usually drawn in .js via success: function
(result) {
$("#ajax-vendedor").html(result);
}
from the looks of this though - unless there is more code that what has been posted, you are passing the .html() function an array or database rows so it's never going to display anything.
so you need to
1)draw a select with no options in it on pageload (or default options if you have them)
2)return a response that the success function can make use e.g. a json string which jquery can the parse
3)format the data in jquery into the <options> and then user the .html() function to update the select
4)if you want this to happen when the page initially loads then add in a document ready call to the productorInfo(id) function - this would be relevant if you are setting the initial select value in some way (so it may not be relevant to you)

how to store dynamically created textbox value to db

i have a code for dynamically created textbox,radiobutton,checkbox..and my question is How can i save the dynamically created textbox checkbox ,radiobutton into MYSQL Database .
<div class="maindiv">
<div id="header"></div>
<div class="menu">
<button id="namebutton"><img src="images/name-img.png">Name</button>
<button id="emailbutton"><img src="images/email.png">Email</button>
<button id="addressbutton"><img src="images/contact-img.png">Address</button>
<button id="checkboxbutton"><img src="images/check-img.png">CheckBox</button>
<button id="radioaddbutton"><img src="images/radio-img.png">Radio</button>
<button id="reset">Reset</button>
</div>
<div class="InputsWrapper1">
<div id="yourhead">
<div id="your">
<h2 id="yourtitle">Your Form Title<img src="images/edit-form.png"></h2>
<h4 id="justclickid">Just Click on Fields on left to start building your form. It's fast, easy & fun.</h4>
</div>
</div>
<div id="InputsWrapper"></div>
</div>
</div>
here is the link for my code link ....and its working fine for me but not working in jsfiddle above link
I would suggest serializing your form's content into a string and simply storing that string in a field called something like form_data.
To do this, you would need to ensure that all of your elements that you want to save are nested within a <form> tag. Once you have that you can call the .serialize() function on your form element.
From the documentation:
The .serialize() method creates a text string in standard URL-encoded
notation. It can act on a jQuery object that has selected individual
form controls, such as <input>, <textarea>, and <select>:
$( "input, textarea, select" ).serialize();
It is typically easier, however, to select the <form> itself for
serialization
var form_string = $("#my_dynamic_form").serialize();
This serialization will give you a string in the following format:
single=Single&multiple=Multiple&multiple=Multiple3&check=check2&radio=radio2
As you can see, this string can be easily saved into the database in a single column. To decode the values in PHP (for example), you can use the parse_url() function:
$form_string = "single=Single&multiple=Multiple...";
parse_str($form_string, $form_data);
The $form_data will now contain the following data:
Array (
[single] => "Single"
[multiple] => "Multiple"
...
)

How to pass php variable to modal window

I am making a simple page and I have found this little problem. I have this in my template:
<?php foreach ($this->vypis_serie as $value) : ?>
<div class="serie">
<div id="serie_header">
<?= $value['nazev_cviceni'] ?>
</div>
<div id="serie_info">
<p>Number of excercises: TODO</p>
<p>Sport type: <?= $value['typ'] ?></p>
<p>KCal summary: <?= $value['kcal'] ?></p>
</div>
<div class="button_upravit">Edit</div>
<div class="button_smazat">Delete</div>
</div>
<?php endforeach; ?>
basically it is a block that fills in information about particular exercise (it is a sport app). SO If I have 3 entries in DB, it will print this code three times with corresponding info.
The problem I have is with the edit button, which upon clicking opens modal window. It is made purely with CSS, so no Javascript.
When I click the button, it jumps to this code:
<div id="openModal_edit" class="modalDialog">
<div>
X
<div id="editace">
<form id="platba" action="serie/edit/" method="post" enctype="multipart/form-data">
<fieldset>
<legend>Edit serie</legend>
<ol>
<li>
<label for="name">Name of the series</label>
<input id="name" name="nazev_cviceni" type="text" required autofocus>
</li>
<li>
<label for="typ">Sport type</label>
<select name="typ">
<option value="Kolo">Bike</option>
<option value="Běhání" selected="selected">Running</option>
</select>
</li>
</ol>
</fieldset>
<fieldset>
<button type="submit">Save</button>
</fieldset>
</form>
</div>
</div>
</div>
But since I jump to div id and I am not using a new page where I could choose a controller and pass a variable, I need somehow to pass the variable (id of the exercise) to the modal window, so I can know which of the possible buttons I have clicked. Is there any way to do it, without the need to rewrite all other pages where I have used this modal window?
I can't use another foreach like in the first part, because the modal window is always a single object that appears, unlike all the entries on the page that are there as many times as there are entries in the DB.
Hope that it is understandable, sorry for my English :)
The simplest way to do this using a single modal window involves adding some javascript code to your page.
First, add the relevant information to the edit link, with a new data-serie-<name> for each piece of data you want to pass:
<a href="#openModal_edit" data-serie-name="<?= $value['nazev_cviceni'] ?>" ...>
Next, add an onclick event handler to that same link. This handler will extract the embedded data from the <a> element and inject it in the modal window. The dataset element provides access to the data-* attributes from javascript
// Example
onclick="serieName=this.dataset.serieName;document.querySelector('#openModal_edit input#name').value = serieName;return true;"

How do I refer to a php variable in jQuery?

I'm a complete beginner with jQuery and I have this bit of script here and I want to mix jQuery with PHP. I have Courses and in those Courses are Lessons. A Teacher is assigned to teach a Course. What I want is a link where if I press it a popup appears and in it shows the Lesson details or Course details. My problem is that I will be having multiple links and thus dialogs/modal windows in a page such that $l['id'] and $c['id'] will be different. How can I therefore use $l['id'] and $c['id'] in or with jQuery given that the jQuery script is inside the view file and I'm creating the actual content itself in the controller and passing it onto view. Sorry if I don't make sense cause I'm still quite confused about all this myself.
view.php
<script type="text/javascript">
$(function(){
// setup ul.tabs to work as tabs for each div directly under div.panes
$("#tabs").tabs();
$('#dialog').dialog({
modal: true
});
})
</script>
<h1>Student Hub: Courses for <?php echo $studentName;?></h1>
<div id="tabs">
<?php echo $content;?>
</div>
controller.php
This is in a foreach loop
<div class="lessonDetails">
<p>Lesson Details:<p>
<div id="lessonDialog'.$l['id'].'" title="Lesson Details">
'.$l['name'].'
</div>
</div>
<div class="courseDetails">
<p>Course Timetable & Resources<p>
<div id="courseDialog'.$c['id'].'" title="Course Details">
<p>'.$c['fullname'].'</p>
<p>'.$c['summary'].'</p>
<p>Upcoming Lessons: </p>
</div>
Technical answer is you don't as one is a server-side language and one is a client-side language; you can't access PHP variables via JavaScript (jQuery). You can, however, drop your PHP variables into your HTML page on generation, and then pick them up with JavaScript or jQuery.
Reading your scenario, I think your over-complicating things. Think of your application; don't think of the technical aspects, but more the way it should be laid out. I'm guessing you have a students controller, a lessons controller, and a courses controller. Those controllers will have actions, called view or similar, and then these actions will take an ID to display a particular student/course/lesson.
In your HTML page/view/template, you should have just vanilla URLs. JavaScript should then be used to enhance the website. So in your case, I would have mark-up it up similar to as follows:
<ul class="courses">
<?php foreach ($courses as $course): ?>
<li><?php echo $course->title; ?></li>
<?php endforeach; ?>
</ul>
I'd then, in an external JavaScript file, have a function that listens for a click on the <a> tag and instead of navigating to that URL, instead displays the page content in a pop-up/modal window.
<script>
$('.courses a').click(function(e) {
e.preventDefault();
// load external page and display it in a modal
});
</script>
This way, if for some reason JavaScript's not available then the user will be taken to the course details page. If they do have JavaScript, then they'll get a fancy modal pop-up.
Hope this helps. If you need anything clearing up then let me know, as I have wrote this in the early hours after a few JD and Cokes!
you can create in every link some extra attributes and using jQuery retrieve the information with the attr function $('a').attr('courses').
somethig like
<a href="#" class=".information" teacher="idTeacher" course="idCourse" >list </a>
then using jquery
$('.information').click(function(){
teacher= $(this).attr('teacher');
course=$(this).attr('course');
});
remember to use $('.information').live() if you are using some AJAX to get the data from the server and the parse it to create the links
You can place tags within your JavaScript code. Since that code is server side, it will "render" to your JavaScript client side code. So your JavaScript can access values stored by your PHP script.
Here's a solution using jQueryUI dialog. No ID's are required however should they be needed add them as a data attribute to that links
<p><a href="#courseInfo'.$c['id'].'" data-id="'.$c['id'].'" >Course Timetable & Resources</a><p>
This allows easily getting ID with jQuery data() method.
Dialog is created and destroyed each use. As noted in comments, no idea what content goes in dialog. I can easily adjust if it is ajax from href
$('.lessonDetails a, .courseDetails a').click(function(){
var $this=$(this);
/* if need the id associated to link*/
var id=$this.data('id');
var content= ''/* ??????? */
var title=$this.parent().next().attr('title')
loadDialog(title, content);
return false; /* stop browser following href*/
})
function loadDialog(title, content) {
var dialogOpts = {
modal: true,
title: title,
width: 800,
close: function() {
/* remove this dialog from DOM on close*/
$(this).remove()
}
};
$('<div>').append(content).dialog(dialogOpts);
}
Maybe you can create forms that have hidden values in it.
<?php foreach($lesson as $l): ?>
<form method="POST" action="">
<input type="hidden" name="lesson_id" value="<?php echo $l['id']; ?>" />
Click
</form>
<?php endforeach; ?>
javascript:
$(document).ready(function() {
$('.modal_window').click(function() {
var form = $(this).closest('form');
var lesson_id = $(form).find('input[name=lesson_id]').val();
// Do something with lesson_id
});
});
The idea is the same for courses.
****** Edit ********
Maybe you can try using input arrays. Assumming you have something like this
<input type="hidden" name="courses[]" value="1" />
<input type="hidden" name="courses[]" value="2" />
javascript:
var courses = $(form).find('input[name^=courses]');
$(courses).each(function() {
var course = $(this).val();
});

ajax js serialize not reading form elements

Have a form that is not being read by serialize() function.
<script type="text/javascript">
function submitTrans1(){
var formData = $('form1').serialize();
var options = {
method:'post',
postBody:'formData',
onCreate: function(){alert(formData)},
onSuccess: function(transport){alert("onSuccess alert \n" + transport.responseText);},
onComplete: function(){alert('complete');},
onFailure: function(){alert('Something went wrong...')}
}
new Ajax.Request('/clients/addTrans/<?=$clientID123?>/',options);
}
</script>
<?php
$datestring = "%Y-%m-%d";
$time = time();
$clid1 = $this->uri->segment(3);
?>
<form name="form1" id="form1">
<div id="addTransDiv" style="display:none">
<div class="">
<label for="transDesc" id="transDesc" value="sadf" class="preField">Description</label>
<textarea cols="40" rows="3" id="transDesc" value="" name="transDesc" class=""></textarea>
</div>
<div class="">
<label for="date" class="preField">Date</label>
<input type="date" id="transDate" name="date" value="<?=mdate($datestring, $time);?>" size="40" class=""/><br/>
</div>
<div class="">
<label for="userfile" class="preField">File</label>
<input type="file" name="transFile" id="userfile" size="20" /><br>
</div>
<input type="button" id="submitTrans" name="submitTrans" value="Submit" onclick="submitTrans1()">
</div>
</form>
Uh, I have an alert in the onSuccess parameter of the Ajax.Request that would ideally alert the variable assigned to the serialized form. However, when it alerts, it alerts nothing. I also have the processing url printing out the $_POST data just in case, but that as well returns an empty array in the responseText, so indeedidly nothing is being posted to the form.
Thx.
Edit1
it seems that the problem might be related to the fact that the form is inside a div. If I remove everything on the page except for the form and js, it works ok. But the form is in a div that is hidden by default and uses another function to be displayed. Is there some kind of magic needed to get form data via serialize if it's in a div?
Edit 2
Tried adding quotes and pound signs and all that other jazz. I am using web developer toolbar, firebug, etc... it isn't throwing any js errors and doesn't afraid of anything.
Try removing the quotes from around the variable name formData in the postBody field.
The web developer toolbar in Firefox is as useful as anything for debugging client-side javascript.
BTW, the snippet contains a few undefined items, like the JS function showTransAdd(), several PHP variables, the PHP function mdate(), and the inclusion of the prototype library.
Change this line:
var formData = $('form1').serialize();
to this:
var formData = $('#form1').serialize();
I had to change several other things to make a working copy, but I'm not sure about what all code you withheld or how your environment may differ. If that doesn't work, I can send you the full code snippet I used.
Erroneous table does the breaking.
I had the form within a table with no tr's or td's (not sure if the last part matters) and upon removing the table tags, everything is working.
The relevant js now looks like:
var formData = $('form1').serialize();
var options = {
method:'post',
postBody:formData,
[...]
I'd like to thank the Academy, and all those that helped me.

Categories