Allow only one query result per table cell - javascript

I have a jquery script that accesses a db and returns a numeric result and writes that result into a table cell. This scripts runs when the page loads but also when the drop down menu is changed. I want to be able to limit only 1 result per table cell.
Right now when page loads it writes the result to the cell and when the drop down menu is changed it just adds the new result to the cell instead of replacing it.
I have search quite a bit trying to figure out how to do this and can not come up with anything. Can someone help me?
Here is the jQuery:
$(document).ready(function(){
$('.typeval').change(function(){
var movement = $(this).val();
var client_id = $(this).parent().siblings().find('.clientval').val();
var class_id = <? echo $class_id; ?>;
$count = $(this).parents('tr').find('label.count');
$.ajax({
type: "POST",
url: "movement_count.php",
data: {movement:movement, client_id:client_id, class_id:class_id},
dataType: "json",
async: false,
success:(function(output) {
$.each(output, function(index, value){
//alert(value);
$count.append(output[index]);
}); // each
})
}) // ajax
}).change(); // .typeval
}); // document
Here is the table cell where I only want to show one result at a time.
<td><label class="count">5</label></td>
Please let me know if I have not provided enough info for the assistance needed.

Use .text() instead of .append():
$count.text(output[index]);
As its name implies, .append() adds the content to the end of the container. Whereas, .text() sets the text displayed in the container, overwriting any existing text.
Actually, .html(), behaves more like .append() than .text() does, but I don't recommend using .html() unless you are actually setting .html(). Since you said the result is numeric, .text() is better.

Try updating your AJAX call to clear the contents before adding new results:
$.ajax({
type: "POST",
url: "movement_count.php",
data: {movement:movement, client_id:client_id, class_id:class_id},
dataType: "json",
async: false,
success:(function(output) {
$.each(output, function(index, value){
//alert(value);
$count.html(''); // Clear current content
$count.append(output[index]); // Append new content
}); // each
})
}) // ajax

Related

Storing and updating a global value in the success function across multiple Ajax POST calls

I have two HTML elements: 1). the div element is a multiple select (it is a predefined widget that automatically creates the multiple select element) and 2). a button that triggers onclick event.
On the JS side, there is the global variable 'prev_selection' which is set to empty array for now. The idea of prev_selection is to remember the array of values in the multiple select div element before user clicks the button. I want to remember the value before and after a click to see what selections have been added/removed.
When the button is clicked, 'sendData()' is called. It gets the selected data from the div element. Then, it performs some operations using the prev_selection to know what the newly selected values are (in the beginning everything is newly selected in the div).
I want to find out the additions/deletions in the selected values between user clicks. For that, I update the prev_selection with 'selected_data' that I get from the div element jut after the click.
But this does not work as expected. There is something happening with the asynchronous Ajax call and I am not able to find a better solution for this. Everytime a click happens you had expect that 'prev_selection' remembers the value before the click but instead when I print it using console.log() (as shown in the code) it already gets updated to the latest selections even before reaching the success function (where it is supposed to get updated).
Thanks in advance! And please let me know if further explanation is required.
<!-- multiple select/deselect div -->
<div id="someSelectionID"></div>
<button id="updateButtonID" onclick="sendData()">Click to send</button>
// at first, no data is selected
var prev_selection = [];
function sendData() {
// get the selected data from the div element "someSelectionID"
let selected_data = $('#someSelectionID').val();
// perform some operations on the selected data
// this operation involves the use of prev_selection
// printing prev_selection already has value of updated click
console.log(prev_selection );
$.ajax({
type: "POST",
url: "<some url>",
dataType: 'json',
contentType: 'application/json;charset=UTF-8',
data: JSON.stringify( < some data > ),
success: function(result) {
console.log(result);
/* once the request is successfully done update the
previous selection to what the current selected data is */
prev_selection = selected_data;
}
});
}
Try this
$.ajax({
type: "POST",
url: "<some url>",
dataType: 'json',
contentType: 'application/json;charset=UTF-8',
data: JSON.stringify( < some data > ),
}
}).then(function(response){
if (response.status === 200){
console.log('succeed');
} else {
console.log('failed')
}
});
So it worked by changing this line
prev_selection = selected_data;
to:
prev_selection = Array.from(selected_data);
Because the prev_selection variable kept changing without me updating, it lead me to believe that it was some kind of reference to value instead of value itself. So just using Array.from to do a shallow copy actually worked.

Assign value to Paragraph or P tag through jQuery for the data obtained from PHP

I need to set the text of Paragraph or P tag to the value obtained though AJAX.
So I have the HTML page somewhat like this where I have declared the paragraph tab.
<p class="card-text">Client Type<p id="Client_Type" name = "Client_Type"></p></p>
Onclick of the button I am making the AJAX call to HOME_CARD.PHP page.
The PHP is working properly and its returning me the data to jQuery. When I use console.log(data); it displays me all the data correctly.
$.ajax({
url: "Home_Card.php",
method: "POST",
data: {
search_client_id: search_client_id
},
success: function(data) {
console.log(data);
$('#Client_Type').val(data.CLIENT_MNEMONIC);
//$('#Client_Type').text("HELLO");
//$('#Client_Type').attr(data.CLIENT_MNEMONIC);
//$('#card').show();
//$('#Client_Type').("HELLOE");
}
});
So I tried using val function to assign the value in CLIENT_TYPE to p tag in HTML page but its not assigning. When I use $('#Client_Type').text("HELLO"); it assigns the value "HELLO" properly so I am guessing nothing wrong with my program.
I wanted to know is there any other way of assigning the value to paragraph tag in jQuery?
How to assign the specific value obtained from PHP in JSON format to paragraph p tag using jQuery.
Paragraph does not take any value i think.
So you should use one of these methods
$('#Client_Type').text(data.CLIENT_MNEMONIC);
or
$('#Client_Type').append(data.CLIENT_MNEMONIC);
Use text method or html method instead:
$('#Client_Type').text(data.CLIENT_MNEMONIC)
Use html or append method
$('#Client_Type').html(data.CLIENT_MNEMONIC);
Thank you for your time and answers but I found my mistake.
During the AJAX call I did not mention the type of data I getting in return
datatype: "json",
Hope fully it will help someone who is also trying.
$.ajax({
url: "Home_Card.php",
method: "POST",
datatype: "json",
data: {
search_client_id: search_client_id
},
success: function(data) {
console.log(data);
$('#Client_Type').val(data.CLIENT_MNEMONIC);
//$('#Client_Type').text("HELLO");
//$('#Client_Type').attr(data.CLIENT_MNEMONIC);
//$('#card').show();
//$('#Client_Type').("HELLOE");
}
});

Cannot remove appended hidden input with jQuery

I dynamically add hidden input to my form. If you're messaging say four people at once (whose names are in callsign_array) it will add four hidden inputs. The form is then submitted using ajax. I then want to remove all the appended hidden inputs, but $('.remove').remove(); isn't working (if you send a message to Andy, then try to send a different message to Barry, it actually sends the message to Andy and Barry. Sending a third message to Chas would result in a message to Andy, Barry and Chas). I know there are thousands of similar "jquery remove() doesn't work" questions on SO, I've looked at them and I think this should work, but I'm baffled, I just can't see what's wrong.
var callsign_array = $('#callsigns-div').data('callsigns');
var form = $("#message_form");
for(var i=0; i<callsign_array.length; i++) {
form.append('<input type="hidden" class="remove" name="callsigns[]" value="' + callsign_array[i] + '" />');
}
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: 'script'
});
// remove all appended inputs
$('.remove').remove();
// reset the callsigns array
$('#callsigns-div').attr('data-callsigns', '[]');
The page includes this div to hold the callsigns array:
<div id="callsigns-div" data-callsigns='[]'></div>
<crystalball on>
You are not removing entries from your callsign_array container. That is why messages for different users accumulate.
</crystalball off>
Add logging:
console.log("Before remove: ", $('.remove').length);
$('.remove').remove();
console.log("After remove: ", $('.remove').length);
to convince yourself that $().remove works.
Update
Do not mix $().data and $().attr calls when reading/writing dataset properties of DOM elements. These dataset items are cached as separate memory objects by jQuery.
Add logging:
$('#callsigns-div').attr('data-callsigns', '[]');
console.log("Hope array is empty: ", $('#callsigns-div').data('callsigns'));
to convince yourself that your $().attr call does nothing to the result of the subsequent $().data call.
#robert-wade is correct. I don't have reps to comment but you might consider holding all of your users in an array or object and then passing that array/object in the form. It's a little cleaner than adding/removing elements. Of course you would have to parse it on the server-side.
try this
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: 'script' ,
success: function (){
$('.remove').remove(); // reset the callsigns array
$('#callsigns-div').attr('data-callsigns', '[]');
}
}); // remove all appended inputs

Ajax update a span real time

I'm trying to get a online/offline status update for a chatsystem. Currently I'm stuck on how to update a span in real time. I got things working but it keeps adding the value (person which is online) to my span. What I want to achieve is to have a static list of people (those who are inside my database), and next to it a green bullet if they are online.
This is my jQuery script:
function theStatus(type, msg){
$("#status").append(
"<span class='status "+ type +"'>"+ msg +"</span>"
);
}
function getStatus(){
$.ajax({
type: "get",
url: "php/ajax/status_users.php",
async: true,
cache: false,
timeout: 1000,
success: function(data){
theStatus("rt", data);
setTimeout(
getStatus,
1000
);
}
});
};
$(document).ready(function(){
getStatus();
});
All help is welcome!
I don't know what your php script returns now, but I would have it return key - value pairs of username slugs and statuses.
Then you could add the username slug as an ID to each user span and target the correct span to change the status if necessary or to add an additional user if it is not found in the html.
At the moment you are simply appending span's each time your ajax function returns a result instead of checking the existing list against the returned list from the server.

Cannot change response element

I can excess a td element from AJAX response but can't change it.
$('#addjob').click(function(){
$.ajax({
type:"POST",
url: 'invoicelist.php',
success: function(response){
$('#forajax').append(response);
$(response).find('.heading').html();
}
});
});
this code works well and selects the text from the <td class='heading'>123</td> but if I want to change this 123 result I write $(response).find('.heading').html('456'); but it doesnt really change anything.
any suggestions?
You're writing the raw HTML into your #forajax container, then creating a new jQuery object with the contents of response. Any changes to the new object will be discarded; they have nothing to do with the HTML you wrote.
Get the object first, modify it, then append:
// create a jQuery object wrapping the returned HTML
var r = $(response);
// update the contents of our new object
r.find('.heading').html('456');
// add the new, updated object to our container
r.appendTo('#forajax');
Change it, then append. That content isn't linked to that variable:
$(response).find('.heading').html('456');
$('#forajax').append(response);
Changing in repsonse will change in the response text but not the appended DOM object. so instead search for dom element where u appended and do there
$('#addjob').click(function(){
$.ajax({
type: "POST",
url: 'invoicelist.php',
success: function(response){
$( '#forajax' ).append(response);
$( '#forajax' ).find('.heading').html( '456' );
}
});
});

Categories

Resources