I am trying to figure out how to update my option select menu when the button is clicked.
I can make this work by using $(#id).click(function(){}); but I also have another function that needs to be called when a option is selected from the menu. The code listed below will not work because it clears my select menu out. I believe this is because the click event is called twice, once on the 1st click and 2nd after the change occurs.
What can I do in order to load the select menu in a way I can use both events. Perhaps I am not going about this the proper way, I am still really new to ajax and jquery.
Example of my code:
MyMarkup:
<div class="siteId"> Select Site:<select id="site" name="site"
style="width: 60px"></select></div>
JavaScript:
getSiteId: function(){ // fill the option select menu
$.ajax({
type: "POST",
url: "?do=getsiteid",
dataType: "json",
async: true,
success: function(jsonObj) {
var listItems= "";
listItems+= "<option value='empty'></option>"; // fill first entry with a blank value
for (var i in jsonObj){
listItems+= '<option value=' + jsonObj[i].siteId + '>' + jsonObj[i].siteId + '</option>';
}
$("#site").html(listItems);
}
});
},
My events:
$(document).ready(function() {
$('.siteId').click(function(){
Freight.getSiteId();
});
$('#site').change(function(){//event to load table based on user selection from menu
var siteId = $("#site").attr('value');
nEditing = null;
if(siteId != "empty"){
$("#message").hide(); // hide message
$("#new").show(); // show button
$('#wrapper').empty(); //
$('#wrapper').replaceWith(Freight.tbl);
Freight.displayData(siteId);
oTable = $('#grid').dataTable( {
"aoColumns": [
/* Dest */ null,
/* Port Id */ {"bSearchable": false,
"bVisible": false},
/* woodType */ {"bSearchable": false,
"bVisible": false},
/* Cont Rate */ null,
/* Edit */ null
]} );
}
else{
$("#wrapper").empty();
$("#message").show(); // hide message
$("#new").hide(); // show button
}
}); // end
});
Because the .click handler is on your .siteId div it is getting called when you click anything inside your div including the SELECT menu. So the .change event for your SELECT is also firing the .click event for the div. I would put a span around the "Select Site" text and put your click event on the span.
Related
I have a form with multiple types of ajax calls.
- general form update that saves all input fields
- per-field uploads
- per-upload deletion
The per-field and per-upload ajax calls are targeted by the class name of the button that is clicked. So there are only 3 scripts in the page.
Each of the scripts work. When the page loads fresh, I can complete any of the form update, field upload, or upload deletion actions.
However, after I have completed an initial action, subsequent actions don't work.
Example:
If I click the "save" button to update the form, this causes the per-field upload and per-upload deletion buttons not to work.
If I click the "per-field" upload, the upload works, but then I'm not able to delete anything.
If I click a "per-upload" delete button, I can no longer upload anything.
But in each case, I am still able to click "save" to update the form.
Here's a visual of how the page is set up:
When a file or image is uploaded to a field, it appears in a container div within the field's markup. The uploaded asset comes with a 'delete' button allowing the user to remove the upload.
Here's the basic HTML of the page
<form id = "form" action = "/process.php" method = "post">
<div class="field">
<label class="field-label">
<span class="field-label-text">Upload 1</span>
<input type="file" data-name="answer1" name="files_answer1[]" />
</label>
<!-- destination for ajax response messages -->
<div id="ajax-message-answer1" class="ajax-field-message"></div>
<!-- upload button -->
<button type="button" class="ajax-button" data-field="answer1" data-type="files">Upload</button>
<!-- container div for uploads -->
<div class="assets" id="assets-answer1">
<div class="asset file">
Name of file
<label class="asset-action">
<!-- deletion button to remove asset -->
<button type="button" data-asset="asset1" data-parent="answer1" class="ajax-delete" value="asset1" onclick="return confirm('You are about to delete this item. Press OK to proceed.')">Delete</button>
</label>
</div><!-- .asset.file -->
</div><!-- .assets -->
</div><!-- .field -->
.... more fields of the same kind ...
<button type = "submit" id = "save">Save</button>
</form>
JS
There are several other scripts in the page, such as jQuery, jQuery UI, Bootstrap, and some custom ones for generating slugs, etc. But I'm thinking these aren't to blame since the problem began only when I started running more than one Ajax request in the page. Here's the JS:
Form Update script
<script type="text/javascript">
$(document).ready(function() {
// process form
$('#form').submit(function(eform) {
// stop regular form submission
eform.preventDefault();
// set variables
var form = $('#form');
// serialize form data
var fdform = form.serializeArray();
// make request
$.ajax({
url: '/account/ajax.php',
type: 'post',
data: $.param(fdform),
dataType: 'json',
success: function(data) {
// get URL for redirect if supplied
if (data.redirect) {
window.location.href = data.redirect;
} else {
// replace with updated template from response
$('#form').html(data.html);
// place template js in specified div
$('#ajax-js').html(data.js);
}
},
error: function(report) {
console.log(report.responseText);
}
});
}); // .click
}); // .ready
</script>
Per-Field Upload script
<script>
$(document).ready(function() {
$(".ajax-button").click(function() {
var fdUpload = new FormData();
// get field info from the clicked button
var field = $(this).data('field');
var uploadType = $(this).data('type');
var input = $('#' + field)[0];
var container_id = '#assets-' + field;
var button_id = '#button-' + field;
// add each file to uploads array
$.each(input.files, function(i, upl) {
// add each file to target element in fdUpload
fdUpload.append(uploadType + '[]', upl);
});
// make request
$.ajax({
url: '/account/ajax.php',
type: 'post',
data: fdUpload,
dataType: 'json', // returns success(data) as object
contentType: false,
processData: false,
success: function(data) {
// put received html in container
$(container_id).html(data.html);
// put received js in #ajax-js
$('#ajax-js').append(data.js);
// clear file input after upload completes
input.value = '';
if (!/safari/i.test(navigator.userAgent)) {
input.type = '';
input.type = 'file';
}
},
error: function(report) {
console.log(report.responseText);
}
});
});
});
</script>
Per-Upload Deletion script
<script>
$(document).ready(function() {
$(".ajax-delete").click(function() {
var fdDelete = new FormData();
// get asset info from clicked button
var asset = $(this).data('asset');
var parent = $(this).data('parent'); // answer
var container_id = '#assets-' + parent;
var button_id = '#delete-' + asset;
var message_id = '#ajax-message-' + asset;
// make request
$.ajax({
url: '/account/ajax.php',
type: 'post',
data: fdDelete,
dataType: 'json',
contentType: false,
processData: false,
success: function(data) {
// put received html in container
$(container_id).html(data.html);
// put received js in #ajax-js
$('#ajax-js').html(data.js);
// retrieve and display response status
$(message_id).html(data.status);
$(message_id).addClass('show');
},
error: function(report) {
console.log(report.responseText);
}
});
});
});
</script>
Summary
Again, each ajax request works when activated after a fresh page load. But after the form has been updated or after an upload or deletion, the upload and deletion no longer fire.
The 'error' callback doesn't display anything in console when this failure occurs.
Do you see a conflict somewhere in the scripts? Maybe the scripts need function names defined? Or is it a problem that the returned response object is called 'data' in each script?
I haven't been working with Ajax very long, so I'd really appreciate your help. I've been banging my head on this all day.
You're using $(".ajax-...").click(...) but in ajax success handler you're updating HTML code for container, thus loosing any attached click handlers for elements in this container.
If you switch to using $("#form").on('click', '.ajax-...', ...) then you'll catch click events even after directly replacing HTML.
jQuery.on() documentation
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 am using bootstrap , php and mysql for an application . With this , whenever the users are logged in , the admin will post messages across to all users that will be displayed as an alert on the page . Below is my ajax code :
$.ajaxSetup(
{
cache: false,
beforeSend: function() {
$('#admin_message').hide();
},
complete: function() {
$('#admin_message').show();
},
success: function() {
$('#admin_message').show();
}
});
var $admin_msg = $("#admin_message");
$admin_msg.load("get_message_board.php");
var refreshId = setInterval(function()
{
$admin_msg.load('get_message_board.php');
}, 10000);
Below is my alert holder holder
<div class="alert alert-success" id="alert_holder">
<p id="admin_message" style="text-align: center;font-size: 20px"></p>
</div>
PHP SCRIPT :
include './functions.php';
$sql = "select message from msg_db3 where user_group ='".$_SESSION['active_user_group']."' order by id DESC LIMIT 1";
$temp = return_results($sql);
echo $temp['0']['message'];
Now i want to make sure that the div (with id='alert_holder') is hidden by default and shows up only if echo $temp['0']['message'] is not empty .If it is empty , it should be hidden . Also the transition is a bit odd since it shakes the entire page while bringing the alert up on the screen .
Please advice on the above .
THanks in advance .
EDIT:
can you try with normal Ajax?
$.ajax({
url: "get_message_board.php"
})
.done(function( data) {
console.log(data);
if(data.length>0){
$('#admin_message').show();
} else {
alert('not found');
}
}
});
Check your response length and show if it's not null
success: function(data) {
if(data.length>0){
$('#admin_message').show();
}
}
In php script you can change to
if(isset($temp['0'])){
echo $temp['0']['message'];
}
The main problem with your code is with
complete: function() {
$('#admin_message').show();
},
This code will show #admin_message every time when ajax is completed.
if you remove this unnecessary part you can make only my first change with if detection.
On my homepage (home.php) I have a first script who take some result of php page (test.php) and display on div #details-menu.
It's the list of "product" table from database.
After when result is selected, I would like to validate it and display on alert.
But it doesn't work... Some idea to help me ?
Here my code :
HOME.PHP (jquery code)
// First display the list of idcat
$(".displaymenu").on('click', function()
{
var idcat=1;
$.ajax({
type: "GET",
url: "test.php",
data: "idcat="+idcat+"",
success: function(msg){
$("#details-menu").html(msg);
}
});
});
// Second validate the choice after selected one product
$('#details-menu').on('click', '.validproduct', function() {
var idproduct=$(this).attr("choice_idproduct");
alert(idproduct);
});
HOME.PHP (html code) :
<div id="details-menu"></div>
TEST.PHP :
<?php
$idcat=$_GET['idcat'];
echo '<select id="choice_idproduct">';
$result = mysql_query("select * from myproduct where idcat='$idcat'");
while ($r_prod = mysql_fetch_array($result_prod))
{
echo '<option value="'.$r_prod['idproduct'].'">'.$r_prod['nameproduct'].'</option>';
}
echo '</select>';
echo '<div class="validproduct">VALIDATE</div>';
?>
You are trying to get an attribute of your div, what is not exists. #choice_idproduct is the child of the div, not an attribute.
Get the value of the select instead.
Try this:
var idproduct=$("#choice_idproduct").val();
I am trying to make a quote form appear on click, the element is first prepended it then needs to run through ajax to get the content for the element
HTML
<input type="button" class="used_result_icon used_result_nav_enquire" car="'.$full_listing_name.'" />
CSS
#used_car_quote {background:#fff; border:2px solid #bebebe; border-radius:5px; display:none; font-size:20px; left:500px; min-height:350px; position:fixed; width:640px; z-index:100;}
AJAX
$(document).on("click", ".used_result_nav_enquire", function() {
car = $(this).attr('car');
$('#used_car_quote').show();
$('#used_results_sort').prepend('<div id="used_car_quote"></div>');
$.ajax({
type : 'POST',
url : 'http://localhost/carprice/ajax/used-quote-results.php',
data : 'car='+car,
success : function(data) {
$("#used_car_quote").html(data);
}
});
});
Its very strange, I click on the button once, and nothing happens, then I click again, and the form appears.
Use this code in AJAX Success $('#used_car_quote').show();
$(document).unbind("click").bind('click', ".used_result_nav_enquire", function() {
car = $(this).attr('car');
$('#used_results_sort').prepend('<div id="used_car_quote"></div>');
$.ajax({
type : 'POST',
url : 'http://localhost/carprice/ajax/used-quote-results.php',
data : 'car='+car,
success : function(data) {
$("#used_car_quote").html(data);
$("#used_car_quote").show();
}
});
});
I am trying to style it as well, but this is very strange, if I click on it once, then it is not positioned right, close it then click again, and it is
$(document).on("click", ".used_result_nav_enquire", function() {
win_width = $(window).width();
form_width = $('#used_car_quote').width();
left = (win_width-form_width)/2;
win_height = $(window).height();
form_height = $('#used_car_quote').height();
top = (win_height-form_height)/2;
car = $(this).attr('car');
$('#used_results_sort').prepend('<div id="used_car_quote">test</div>');
$('#used_car_quote').css({'left':left,'top':top});
$.ajax({
type : 'POST',
url : 'http://localhost/carprice/ajax/used-quote-results.php',
data : 'car='+car,
success : function(data) {
$("#used_car_quote").html(data);
$('#used_car_quote').show();
}
});
});