I am rendering all the option of the select box through an ajax call inside $(document).ready() function.
I have a PHP variable at the top of the page which is initialized with 1 like
$expert_id = 1;
Now here is my code
$(document).ready(function(){
$.ajax({
type: "POST",
url: "<?php echo base_url('insoadmin/experts/all_experts');?>",
dataType: "json",
success: function(data, page) {
$.each(data, function(i, item) {
//console.log(data[i].expert_name);
$('#expert').append($('<option>', {
value: data[i].expert_id,
text : data[i].expert_name,
}));
});
}
});
});
While appending all the option to my expert select box I want to check if data[i].expert_id is equal to my php variable or not, if it is equal to my PHP variable then it should be selected.
How can I achieve that?
Use selected property/attribute while creating jQuery object(<option>)
Refer jQuery( html [, ownerDocument ] )
var data = [{
expert_id: 1,
expert_name: 'rayon'
}, {
expert_id: 2,
expert_name: 'bye'
}];
var expert_id = 2;
$.each(data, function(i, item) {
$('#expert').append($('<option>', {
value: data[i].expert_id,
text: data[i].expert_name,
selected: expert_id === data[i].expert_id
}));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="" id="expert"></select>
Fiddle Demo
Have you tried like this:
$(document).ready(function(){
$.ajax({
type: "POST",
url: "<?php echo base_url('insoadmin/experts/all_experts');?>",
dataType: "json",
success: function(data, page) {
$.each(data, function(i, item) {
//console.log(data[i].expert_name);
$('#expert').append($('<option>', {
value: data[i].expert_id,
text : data[i].expert_name,
}));
});
var expert_id = '<?php echo $expert_id ; ?>';
$('#expert').val(expert_id); //setting the value of select box
}
});
});
Define at top:
<span id="foo"><?php echo $expert_id; ?></span>
Add in the script
<script>
$(document).ready(function(){
$.ajax({
type: "POST",
url: "<?php echo base_url('insoadmin/experts/all_experts');?>",
dataType: "json",
success: function(data, page) {
$.each(data, function(i, item) {
//console.log(data[i].expert_name);
$('#expert').append($('<option>', {
value: data[i].expert_id,
text : data[i].expert_name,
var foo=$('#foo').html();
if(foo==data[i].expert_id){
//do something
}
}));
});
}
});
});
</script>
Related
I have the following code where I make a loop to get data and send that data to a select .
I'm trying to save this data in an array and then display that data in a select
apparently the error comes from the line newOptions.push ({v.c_group: v.c_codigo_group}); since it asks me for a string , I think
here my code.
case <?php echo "'".$row["c_codigo_producto"]."'"; ?>:
$("#divhidden").first().show("fast", function() {});
var newOptions = {};
$.ajax({
data: {
'valor': valor
},
url: 'JSON/search_group.php',
type: 'POST',
dataType: 'json',
cache: false,
success: function(data) {
$.each(data, function(k, v) {
newOptions.push({ v.c_group : v.c_codigo_group });
});
},
async: false,
});
var $el = $('#grupo');
$el.html(' ');
$.each(newOptions, function(key, value) {
$el.append($("<option></option>")
.attr("value", value).text(key));
});
break;
<?php } ?>
I have this HTML in AJAX and I want to grab an ID (#commentsContainer) and insert in my other HTML.
Formatted HTML in AJAX:
<blockquote class=\"blockquote\" style=\"font-size: 15px; background-color: #f5f5f0;\" id='comments1'>
<div id='commentsContainer'></div>
</div><br>
</blockquote>
The code I want to use and insert my new data
$(document).ready(function(){
$.ajax({
url: "/api/comments/",
method: "GET",
dataType: "json",
success: function(data) {
// console.log(data)
$.each(data, function(key, value) {
var commentdesc = value.description;
console.log(commentdesc)
$('#commentsContainer').append("<li>" + commentdesc + "<li>")
);
})
},
error: function(data) {
console.log("error")
},
})
})
There are 2 mistakes in your code.
Updated code
$(document).ready(function(){
$.ajax({
url: "/api/comments/",
method: "GET",
dataType: "json",
success: function(data) {
$.each(data, function(key, value) {
var commentdesc = value.description;
$('#commentsContainer').append("<li>" + commentdesc + "<li>");
});
},
error: function(data) {
console.log("error")
}
});
});
Mistake details:
Extra bracket next to append statement.
Extra comma at the end of error method.
Hope this will help you after rectifying the mistakes.
i am new to JQuery AJAX and i need help with my code. What i want is when i click the add button it will change to delete button. but what happens in my code is that it changes to delete button but when i click delete button, it does not change back to add button. i want it to look like some sort of toggle. here's my html code with javascript:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function () {
$('#add_button').click(function(){
var temp = $('#add_button').val();
$.ajax({
url: "ajax_test.php",
type: "POST",
data: {add_button: temp},
success: function(data){
$('div').html(data);
}
});
});
$('#delete_button').click(function(){
var temp = $('#delete_button').val();
$.ajax({
url: "ajax_test.php",
type: "POST",
data: {delete_button: temp},
success: function(data){
$('div').html(data);
}
});
});
});
</script>
</head>
<body>
<div>
<button id="add_button" name="add" value="testing">Add</button>
</div>
</body>
and here's my php code:
<?php
if(isset($_POST["add_button"])){
echo "<button id='delete_button' name='delete' value='testing'>Delete</button>";
}
if(isset($_POST["delete_button"])){
echo "<button id='add_button' name='add' value='testing'>Add</button>";
}
?>
please help. thanks
You can try hiding the button clicked and show other button something like
$('#add_button').click(function(){
var temp = $('#add_button').val();
$.ajax({
url: "ajax_test.php",
type: "POST",
data: {add_button: temp},
success: function(data){
$('div').html(data);
$('#add_button').hide();
$('#delete_button').show();
}
});
});
$('#delete_button').click(function(){
var temp = $('#delete_button').val();
$.ajax({
url: "ajax_test.php",
type: "POST",
data: {delete_button: temp},
success: function(data){
$('div').html(data);
$('#delete_button').hide();
$('#add_button').show();
}
});
});
Or you can use jquery toggle
$( "#add_button").toggle()
http://api.jquery.com/toggle/
Your solution wasn't working, because delete button event handler was being attached to DOM before the DOM element(delete button) was initialised.
So, one event for both buttons would be enough:
$('button').click(function(){
var button = $(this);
if(button.data('type') == 'add') {
var postData = {add_button: button.val()};
} else {
var postData = {delete_button: button.val()};
}
$.ajax({
url: "ajax_test.php",
type: "POST",
data: postData,
success: function(data){
$('div').html(data);
}
});
});
HTML:
<div>
<button data-type="add" name="add" value="testing">Add</button>
</div>
PHP:
<?php
if(isset($_POST["add_button"])){
echo "<button data-type='delete' name='delete' value='testing'>Delete</button>";
}
if(isset($_POST["delete_button"])){
echo "<button data-type='add' name='add' value='testing'>Add</button>";
}
?>
<script>
$(document).ready(function () {
$('div').on('click', '#add_button', function(){
var temp = $(this).val();
$.ajax({
url: "ajax_test.php",
type: "POST",
data: {add_button: temp},
success: function(data){
$('div').html(data);
}
});
});
$('div').on('click', '#delete_button', function(){
var temp = $(this).val();
$.ajax({
url: "ajax_test.php",
type: "POST",
data: {delete_button: temp},
success: function(data){
$('div').html(data);
}
});
});
});
</script>
Your code won't work on dynamically added elements, while above code works.
Read http://api.jquery.com/on/ for more informations.
Try the below code:
Give a class name to button:
<button id="add_button" class="btnOp" name="add" value="testing">Add</button>
Then you can add a js click event to that classname and change its data accordingly:
$('.btnOp').on('click',function()
{
var text=$(this).text();
if(text==="Add")
{
var temp = $('#add_button').val();
$.ajax({
url: "ajax_test.php",
type: "POST",
data: {add_button: temp},
success: function(data){
$('div').html(data);
$('.btnOp').val('testing');
}
});
}
else
{
var temp = $('#delete_button').val();
$.ajax({
url: "ajax_test.php",
type: "POST",
data: {delete_button: temp},
success: function(data){
$('div').html(data);
$('.btnOp').val('testing');
}
});
}
});
This will help you to change button values and functionality on success of ajax and acts like kind of toggle
I have a simple application that calculates the total price of all the rows in a table.
New rows get added like this:
function add() {
[...data removed for readability...]
jQuery.ajax({
type: "POST",
data: {
a:'addadminprice',
id:<? echo $id; ?>,
priceid:el.attr('value'),
price:price
},
url: options.actionurl,
dataType: "json",
success: function(result){
if (result.status=='success') {
var initaddprice = 0;
var row="<tr class='pricedata' rel='"+result.id+"'>";
row+="<td class='drag'>::::</td>";
row+="<td>"+el.text()+"</td>";
row+="<td class='right'>"+price+"</td>";
row+="<td><input type='text' onchange='recalc(this,"+result.id+")' value='"+price+"' /></td>";
row+="<td>"+(el.data('percent')=='1'?"%":"")+"</td>";
row+="<td><input type='text' onchange='recalc(this,"+result.id+")' value='"+result.qty+"' /></td>";
row+="<td class='right'>"+initaddprice.toFixed(3)+"</td>";
row+="<td><a class='button' href='#' onclick='return removeprice(this,"+result.id+")'>remove</a></td>";
row+="</tr>";
var isfound=false;
$('.pricedata').last().after($(row));
el.remove();
changePrice();
recalcall();
setsort();
saveposition();
}
}
});
As you can see it adds the row - then recalculates the total based all the rows. So far so good, it works fine.
function recalcall() {
console.clear();
console.log('----start calculation----');
var total=0;
$('.pricedata').each(function(){
var price=parseFloat($(this).find('td').eq(6).text());
if (isNaN(price)) price=0;
total+=price;
console.log('+'+price+' = '+total);
});
console.log('----end calculation----');
$('#total').text(total.toFixed(3));
}
When I remove one row, it removes the element and will recalculate the total again. But unfortunately the row is still included in the calculation process? I'm at loss here. Once you remove an element, it should be taken in consideration, right?
function removeprice(el,id) {
if (confirm('Are you sure?')) {
jQuery.ajax({
type: "POST",
data: {
a:'deleteprojectprice',
id:id
},
url: options.actionurl,
dataType: "json",
success: function(result){
if (result.status=='success') {
$(el).closest('tr').remove();
}
}
});
}
recalcall();
}
In the removeprice function, move recalcall(); in to the success function
success: function(result){
if (result.status=='success') {
$(el).closest('tr').remove();
recalcall(); // call function here
}
do it like following
function removeprice(el,id) {
if (confirm('Are you sure?')) {
jQuery.ajax({
type: "POST",
data: {
a:'deleteprojectprice',
id:id
},
url: options.actionurl,
dataType: "json",
success: function(result){
if (result.status=='success') {
$(el).closest('tr').remove();
}
//have this here
recalcall();
}
});
}
}
How can I assign a variable(var) to a json object which is returned from ajax call to the server? I need to access that object in the rest of the body.
For example, I've try this, I don't know it's correct.
var selectValues=$(document).ready(function() {
$.ajax({
type: "POST",
url: "http://10.0.2.2/mobileajax/callajax.php",
data: ({name: theName}),
cache: false,
dataType: "text",
success: onSuccess
});
})
var $vendor = $('select.mobile-vendor');
var $model = $('select.model');
$vendor.change(
function() {
$model.empty().append(function() {
var output = '';
$.each(selectValues[$vendor.val()], function(key, value) {
output += '<option>' + key + '</option>';
});
return output;
});
}).change();
// bonus: how to access the download link
$model.change(function() {
$('a#download-link').attr('href', selectValues[$vendor.val()][$model.val()]).show();
});
Note that, variable selectValues is used in the rest of the body.
I think you should do the whole code inside the $(document).ready(function() function and then make the ajax call synchronous. Because now the ajax call will be made when the document is ready, but the other code will be run directly without waiting for the document to be ready. Also the ajax call is asynchronous by default, so you should make it synchronous and assign the selectValues variable inside the success function of the ajax call. It will become something like this:
$(document).ready(function() {
var selectValues;
$.ajax({
type: "POST",
url: "http://10.0.2.2/mobileajax/callajax.php",
data: ({name: theName}),
cache: false,
dataType: "text",
async: false,
success: function(data) {
selectValues = data
}
});
var $vendor = $('select.mobile-vendor');
var $model = $('select.model');
$vendor.change(
function() {
$model.empty().append(function() {
var output = '';
$.each(selectValues[$vendor.val()], function(key, value) {
output += '<option>' + key + '</option>';
});
return output;
});
}).change();
// bonus: how to access the download link
$model.change(function() {
$('a#download-link').attr('href', selectValues[$vendor.val()][$model.val()]).show();
});
})
you have to define the var outside the document ready scope like this:
var selectValues;
$(document).ready(function() {
// ajax
});
in the onSuccess function you can define the selectValues = data or something like that
$.ajax({
type: "POST",
url: "http://10.0.2.2/mobileajax/callajax.php",
data: ({name: theName}),
cache: false,
dataType: "text",
success: function (result){
var selectValues=result;
}
});
try this.
Here is how we extract the returned information from our (xml) ajax calls:
$.ajax ({
type: "POST",
url: "something.cgi?someparam=whatever",
data: "key=val&key2=val2",
dataType: "xml", // you use json, but I don't think it matters
success: function (data) {
if ($("error", data).text() === "") {
// I could assign $("error", data).text() to a var just here
// This gets the "error" parameter out of the returned xml or
// json, here contained in "data"
}
[snip the rest]
Another way to do this is to add the rest of your code in the success callback lik this:
$(document).ready(function() {
$.ajax({
type: "POST",
url: "http://10.0.2.2/mobileajax/callajax.php",
data: ({name: theName}),
cache: false,
dataType: "text",
async: false,
success: function(selectValues) {
var $vendor = $('select.mobile-vendor');
var $model = $('select.model');
$vendor.change(
function() {
$model.empty().append(function() {
var output = '';
$.each(selectValues[$vendor.val()], function(key, value) {
output += '<option>' + key + '</option>';
});
return output;
});
}).change();
// bonus: how to access the download link
$model.change(function() {
$('a#download-link').attr('href', selectValues[$vendor.val()][$model.val()]).show();
});
}
});
})