I have a drop down menu, that a user selects a criteria from, based on the criteria a form gets built.
What I am trying to do now is make sure they cannot build the same for twice, so for example, if the users selects appearance from a dropdown, I do not want them to be able to select appearance from the dropdown, while that form is built.
Does that make sense? Currently here is my code,
$('img.toggleadd').live({
click: function() {
var rowCount = $("#advanced_search > table > tbody > tr").length;
f(rowCount < 3) {
$.ajax({
url: site_url + 'ajax/row/empty',
success: function(data) {
console.log($(this));
$('#advanced_search table').append(data);
}
});
}
}
});
and the PHP
public function row($name) {
if ($this->input->is_ajax_request()) {
return $this->load->view('search/rows/'.$name);
}
}
$name relates to the name of a view which contains the corresponding form elements for the selected value.
As Jared mentioned, the solution could be something as simple as a boolean value indicating whether or not a request is in progress...
Take this code for example -
var request_in_progress = false;
$("#selector").on('change',function(){
if (!request_in_progress){
request_in_progress = true;
$.ajax('/path_to_ajax_module.php',{'data':data},function(response){
// handle the AJAX response
request_in_progress = false; // AJAX request complete.
},'json');
}
});
Related
My code igniter web page has side bar check boxes and news articles on main panel updated from database. when i select check box i want to pass check box ID to controller and return only relevant news articles according to check box value. How to do it? What is the mechanism using here?
example web site same as i expected
<?php
foreach ($data as $add) {
echo "<div>";
echo '<p class="target">' .$add->news_data. '</p>';
echo "</div>";
}
?>
To Do that ...You have to make an ajax call "onclick" of checkbox group and then on ajax call you have to fire query with the IDs which have been passed
So,set AJAX function
$("#sidebar input[type='checkbox']").click(function(e){
var values = [];
$( "input[name='post_type']:checked" ).each(function(){
values.push($(this).val());
});
var Type = values.join(", ");
$.ajax({
type: "POST",
url: "filterpost.php",
data: "typID="+Type ,
cache: false,
success: function(){
alert("success");//just to check only
}
});
});
Step 2:Now create filterpost.php file
Now get the post value at the other side
$id = $_POST['typID'];
and from here fire the appropriate query using "IN" keyword
Step 3:
and pass that data to the view after that.
I can't give you the whole example directly...just follow this steps
I hope you will get solution
$('input[type="checkbox"][name="change"]').change(function() {
if(this.checked) {
// some ajax request
}
});
Similarly with plain JavaScript:
// checkbox is a reference to the element
checkbox.onchange = function() {
if(this.checked) {
// some ajax request
}
};
And your function function return an JSON as your example
I'm trying when i submit a value to jqgrid box on multiple selected rows to Update the data of specific columns.My code is this but when i click OK in jqgrid nothing happens and function is not called :
jQuery(document).ready(function(){
jQuery('#list1').jqGrid('navButtonAdd', '#list1_pager',
{
'caption' : 'Resubmit',
'buttonicon' : 'ui-icon-pencil',
'onClickButton': function()
{
var str = prompt("Please enter data of Column")
var selr = jQuery('#list1').jqGrid('getGridParam','selarrrow');
$(selector).load('Updatestatus.php', {'string': str,'box[]' : selr })
},
'position': 'last'
});
});
The function that updates the column of the table:
function update_data($data)
{
// If bulk operation is requested, (default otherwise)
if ($data["params"]["bulk"] == "set-status")
{
$selected_ids = $data["cont_id"];
$str = $data["params"]["data"];
mysql_query("UPDATE out_$cmpname SET cont_status = '$str' WHERE cont_id IN ($selected_ids)");
die;
}
}
I'm new to jqgrid and Jquery.What can i do to call and execute this function when i click ok?
Thanks in advance!
You'll need a Ajax-call for this. I see you're using jQuery, have a look at http://api.jquery.com/load/
With this function, you can load PHP or HTML with jQuery to a certain element.
I am dynamically adding list items to a list in jQuery through an ajax call that is called every second.
Below is the code for the ajax call.
$.ajax({
url: 'php/update_group_list.php',
data: '',
dataType: 'json',
success: function(data) {
var id = data.instructor_id;
group_cnt = data.group_cnt,
group_name = data.group_name,
group_code = data.group_code;
for (i = current_row; i < group_cnt; i++)
{
//setInterval(function() { $('#group-list-div').load('php/group_list.php'); }, 5000);
$('#group-list').append("<li><a href='#' data-role='button' class='view-group-btns' id='"+group_code[i]+"' value='"+id+"' text='"+group_name[i]+"'>"+group_name[i]+"</a></li>");
$('#delete-group-list').append("<fieldset data-role='controlgroup data-iconpos='right'>" +
"<input id='"+group_code[i]+i+"' value='"+group_code[i]+"' type='checkbox' name='groups[]'>" +
"<label for='"+group_code[i]+i+"'>"+group_name[i]+"</label>" +
"</fieldset>");
}
current_row = i;
$('#group-list').listview('refresh');
$('#delete-group-list').trigger('create');
}
});
Now I am having two problems
FIRST PROBLEM:
When I try to run the code below (it should show an alert box if any of the list items created in this line $('#group-list').blah...blah in the code above), nothing happens.
$(".view-group-btns").click(function()
{
alert("check");
});
SECOND PROBLEM:
Also when I try to send the form data for the checkboxes (referencing line $('#delete-group-list').blah...blah in the ajax call code above) the post returns the error unexpected token <
What am I doing wrong? I think the two problems are related as I am creating the list items that are used dynamically.
Here is extra code relating to the SECOND problem
HTML:
<form id='delete-group-form' action='php/delete_groups.php' method='post'>
<h3 style='text-align: center;'>Check the Box Beside the Groups you Would Like to Delete </h3>
<div style='margin-top: 20px;'></div>
<div id='delete-group-list'>
</div>
<div style='margin-top: 20px;'></div>
<input type='submit' id='delete-groups-btn' data-theme='b' value='Delete Groups(s)'>
</form>
JS Code
$('#delete-group-form').submit(function(e)
{
e.preventDefault();
alert($('#delete-group-form').serialize());
if ($('#delete-group-form').serialize() == "")
{
alert('No groups selected to be deleted.')
return false;
}
else
if ($('#delete-groups-form').serialize() == null)
{
alert('No groups selected to be deleted.')
return false;
}
else
{
$.post('php/delete_groups.php',$('#delete-groups-form').serialize()).done(function(data)
{
obj = jQuery.parseJSON(data);
var group_codes = obj.group_list;
alert(group_codes);
alert("The selected groups have been deleted");
window.setTimeout(2000);
return false;
});
}
return false;
});
delete_groups.php
<?php
$group_codes = $_POST['groups'];
$items = array('group_list'=>$group_codes); //creating an array of data to be sent back to js file
echo json_encode($items); //sending data back through json encoding
?>
I think the root of the SECOND problem is the line $group_codes = $_POST['groups']; specfically the $_POST['groups'] because when I replace it with $group_codes = 'test'; (just for debugging purposes) , the code works as expected.
You need to use event delegation to make your newly-created elements function properly:
$("#group-list").on("click", ".view-group-btns", function() {
alert("check");
});
I noticed you have 3 single quotes on this line... missed one after controlgroup
$('#delete-group-list')."<fieldset data-role='controlgroup data-iconpos='right'>"
That would explain the unexpected token <
You have to use the jquery on event.
$(".view-group-btns").on("click", function(event)
{
alert("check");
});
Why?
Because you can only use the regular "click" on elements that are created BEFORE the DOM is updated.
When you are dynamically creating new elements into the dom tree, then you can't use .click anymore.
on (and in the past, .live(), which is deprecated now) can listen to modifications in the DOM tree and can use the later-on created elements.
You have to bind the click function after you get the element from ajax call. Binding on pageLoad event will only bind with those elements that are already in the dom. So do something like this.
$.ajax({
success : function(res){
//bind your click function after you update your html dom.
}
})
I know this question has been asked before, but I wasn't able to find any answers that are up to date or functional (at least for my application).
My JQuery autocomplete box is using a mysql database as its source. I want the user to be able to type to get recommendations, but then is forced to select from the dropdown choices before they can submit the form.
My Javascript:
<script type="text/javascript">
$.widget( 'ui.autocomplete', $.ui.autocomplete, {
_renderMenu: function( ul, items ) {
var that = this;
$.ui.autocomplete.currentItems = items;
$.each( items, function( index, item ) {
that._renderItemData( ul, item );
});
}
});
$.ui.autocomplete.currentItems = [];
$(function() {
$("#college").autocomplete({
source: "search.php",
minLength: 5
});
});
var inputs = {college: false};
$('#college').change(function(){
var id = this.id;
inputs[id] = false;
var length = $.ui.autocomplete.currentItems.length;
for(var i=0; i<length; i++){
if($(this).val() == $.ui.autocomplete.currentItems[i].value){
inputs[id] = true;
}
}
});
$('#submit').click(function(){
for(input in inputs){
if(inputs.hasOwnProperty(input) && inputs[input] == false){
alert('incorrect');
return false;
}
}
alert('correct');
$('#college_select_form').submit();
});
</script>
My form:
<form action="choose.php" method="post" id="college_select_form" name="college_select_form">
<input type="text" id="college" name="college" class="entry_field" value="Type your school" onclick="this.value='';" onfocus="this.select()" onblur="this.value=!this.value?'Type your school':this.value;" /><input type="submit" id="submit" name="submit" class="submitButton" value="Go" title="Click to select school" />
</form>
Search.php:
<?php
try {
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
}
catch(PDOException $e) {
echo $e->getMessage();
}
$return_arr = array();
if ($conn)
{
$ac_term = "%".$_GET['term']."%";
$query = "SELECT * FROM college_list where name like :term";
$result = $conn->prepare($query);
$result->bindValue(":term",$ac_term);
$result->execute();
/* Retrieve and store in array the results of the query.*/
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
array_push($return_arr, array('label' => $row['name'], 'value' => $row['name']));
}
}
/* Free connection resources. */
//$conn = null;
/* Toss back results as json encoded array. */
echo json_encode($return_arr);
?>
So what would be the best approach to doing this? The only solution I can think of is using PHP to verify that the textbox's value matches a value in the database, but I'm not sure how to implement that with my current code.
You should always check it in "choose.php" (server-side) since the user can disable the JavaScript and post whatever they want in the inputs of your form
$college = mysql_real_escape_string($_GET['college']);
if ($college != "" || $college != null || $college != -1)
{
//DO STUFF
}
NOTE: YOU SHOULD ALWAYS USE "mysql_real_escape_string" to prevent SQL Injection!
more info: http://www.tizag.com/mysqlTutorial/mysql-php-sql-injection.php
So accordingly in search.php change the
$ac_term = "%".$_GET['term']."%";
to
$ac_term = "%". mysql_real_escape_string($_GET['term']) ."%";
You can also check the form before the user submit to just make it more user friendly (users don't want to wait couple of seconds for the page to gets refreshed with errors on it!)
so maybe something like this would help: Submit Event Listener for a form
function evtSubmit(e) {
// code
e.preventDefault();
// CHECK IT HERE!
};
var myform = document.myForm;
myform.setAttribute('action', 'javascript:evtSubmit();');
In my project i handled it by checking on focus-out , if the text entered in the autocomplete field actually matches my dropdown options.If not i will simply remove it.
change: function(event, ui) {
if (!ui.item) {
this.value = '';
}
}
See my full example here-Jquery auto comp example
it has an embeded fiddle,you can check the fiddle directly also
http://jsfiddle.net/9Agqm/3/light/
Add this code to your JavaScript before you instantiate your autocomplete object:
$.widget( 'ui.autocomplete', $.ui.autocomplete, {
_renderMenu: function( ul, items ) {
var that = this;
$.ui.autocomplete.currentItems = items;
$.each( items, function( index, item ) {
that._renderItemData( ul, item );
});
}
});
$.ui.autocomplete.currentItems = [];
This will make it so whenever the menu appears, you have a list of current items the user can choose from stored in $.ui.autocomplete.currentItems. You can then use that to check against when you are submitting your form. Of course the way you implement this part is up to you depending on how dynamic your form is, but here is an example that requires hard-coding a list of input fields and making sure they all have ids.
//create an object that contains every input's id with a starting value of false
var inputs = {college: false};
//for each input, you will have a function that updates your 'inputs' object
//as long as all inputs have id's and they all are using autocomplete,
//the first line could be written as: $('input').change(function(){ and the
//function would only need to be written once. It is easier to maintain
//if you use seperate id's though like so:
$('#college').change(function(){
var id = this.id;
inputs[id] = false;
var length = $.ui.autocomplete.currentItems.length;
for(var i=0; i<length; i++){
if($(this).val() == $.ui.autocomplete.currentItems[i].value){
inputs[id] = true;
}
}
});
//when you submit, check that your inputs are all marked as true
$('#submit').click(function(){
for(input in inputs){
if(inputs.hasOwnProperty(input) && inputs[input] == false){
return false; //one or more input does not have correct value
}
}
//all inputs have a value generated from search.php
$('#myform').submit();
});
UPDATE
The only difference between our two examples (one that works and one that doesn't) is that you are binding other events to your input element, onclick and onblur. So by changing our listener from change to blur as well mostly fixes the problem. But it creates a new problem when the enter/return key is pressed to submit the form. So if we add a listener for that specific event then everything works out ok. Here is what the code looks like now:
var validateInfo = function(elem){
var id = elem.id;
inputs[id] = false;
var length = $.ui.autocomplete.currentItems.length;
for(var i=0; i<length; i++){
if($(elem).val() == $.ui.autocomplete.currentItems[i].value){
inputs[id] = true;
}
}
}
$('#college').on('blur', function(){
validateInfo(this);
}).on('keydown', function(e){
if(e.which == 13){ //Enter key pressed
validateInfo(this);
}
});
Add a hidden input element to your form:
<input type="hidden" name="selectedvalue" id="selectedvalue" />
Add a select event handler to your autocomplete, that copies the selected value to the hidden input:
$("#college").autocomplete({
source: "search.php",
minLength: 5,
select: function (event, ui) {
$('#selectedvalue').val(ui.item.value);
}
});
Then just ignore the auto-complete form input in posted data.
As this is javascript, your only concern should be if an item is selected from the autocomplete list. This can simply be done by setting a variable to true on select and false on change. That is enough to prevent regular users from continuing without selecting a school. To prevent abuse you need to check the value server side after posting. All normal user will pass that check.
If I understand the question correctly, this is something I have encountered before. Here is some code pretty much lifted straight out of another project. I have used a local datasource here but the project this is lifted from uses remote data so there won't be a difference:
var valueSelected = '';
$('#college').autocomplete({
source: ['collegeA', 'collegeB', 'collegeC']
}).on('autocompletechange autocompleteselect', function (event, ui) {
if (!ui.item) {
valueSelected = '';
} else {
$('#submit').prop('disabled', false);
valueSelected = ui.item.label;
}
}).on('propertychange input keyup cut paste', function () {
if ($(this).val() != valueSelected) {
valueSelected = '';
}
$('#submit').prop('disabled', !valueSelected);
});
This will programatically enable and disable the submit button depending on whether a value has been selected by the user.
Fiddle here
I have a series of two chained selects using ajax that work great. I need to be able to store/save the first select in a cookie for future visits but can't quite figure out how/what to do within the existing code?
$(function(){
var questions = $('#questions');
function refreshSelects(){
var selects = questions.find('select');
// Lets not do chosen on the first select
selects.not(":first").chosen({ disable_search_threshold: true });
// Listen for changes
selects.unbind('change').bind('change',function(){
// The selected option
var selected = $(this).find('option').eq(this.selectedIndex);
// Look up the data-connection attribute
var connection = selected.data('connection');
// Removing the li containers that follow (if any)
selected.closest('#questions li').nextAll().remove();
if(connection){
fetchSelect(connection);
}
});
}
var working = false;
function fetchSelect(val){
if(working){
return false;
}
working = true;
$.getJSON('citibank.php',{key:val},function(r){
var connection, options = '';
switch (r.type) {
case 'select':
$.each(r.items,function(k,v){
connection = '';
if(v){
connection = 'data-connection="'+v+'"';
}
options+= '<option value="'+k+'" '+connection+'>'+k+'</option>';
});
if(r.defaultText){
// The chose plugin requires that we add an empty option
// element if we want to display a "Please choose" text
options = '<option></option>'+options;
}
// Building the markup for the select section
$('<li>\
<p>'+r.title+'</p>\
<select data-placeholder="'+r.defaultText+'">\
'+ options +'\
</select>\
<span class="divider"></span>\
</li>').appendTo(questions);
refreshSelects();
break;
case 'html':
$(r.html).appendTo(questions);
break;
}
working = false;
});
}
$('#preloader').ajaxStart(function(){
$(this).show();
}).ajaxStop(function(){
$(this).hide();
});
// Initially load the product select
fetchSelect('callTypeSelect');
});
Here is great article on using jCookies.
http://tympanus.net/codrops/2011/09/04/j-is-for-jcookies-http-cookie-handling-for-jquery/
The code for setting it goes like this:
$.jCookies({
name : 'Person',
value : { first: 'John', last: 'Smith', Age: 25 }
});
Getting the cookie goes like this
var person = $.jCookies({ get : 'Person' });
Do you need that value on the server? If you don't I recomment the jStorage plugin. It uses local storage and userData to save information. This has the benefits that the values are not sent to your server on every request, like cookies do.
The usage is very simple:
$.jStorage.set("something", {data: [1,2,3], other: "a string"});
and
$.jStorage.get("something"); // returns {data: [1,2,3], other: "a string"}
In your code it would be something like:
$(function() {
var questions = $('#questions');
var lastSelection = $.jStorage.get("lastSelection");
if(lastSelection) {
questions.find("select:first").val(lastSelection);
}
// more code....
selects.unbind('change').bind('change',function(){
var selected = $(this).find('option').eq(this.selectedIndex);
if(questions.find("select:first")[0] === this) { // Only save if it's the first combo (you could change this to a better way to identify the first select)
$.jStorage.set("lastSelection", selected);
}
// more code....
});