update span using jquery find in ajax call - javascript

I'm trying to update/refresh a specific after data is returned from the server.
I want to update span class="answer-final-score". I use class instead of ID because this HTML gets dynamically generated multiple times.
The jquery ($('.rating').on... gets executed once the user clicks on a star in the div class="answer-score"
$('.rating').on('rating.change', function (event, value, caption) {
$(this).closest('.answer-container').find('.answer-score-final').text('aaa');
// above works standalone but not in .done section of $.ajax call below
.done(function (result) {
var jsonReturn = JSON.parse(result);
$(this).closest('.answer-container').find('.answer-score-final').text(jsonReturn.score);
})
<div class="answer-container">
<div class="answer-score">
Score (<span class="answer-count">#Model.ElementAt(i).Count)</span><br /><br />
<span class="answer-final-score">#(Math.Round((decimal)(Model.ElementAt(i).RatingScore)))</span>
</div>
<div class="answer-rateIt">
<input data-id="#Model.ElementAt(i).OptionID" type="number" class="rating" min=0 max=5 step=0.5 data-size="sm">
<div class="hover">hover</div>
</div>
</div>

$(this).closest('.answer-container').find('.answer-score > .answer-score-final').text('aaa');
should work for you. Instead of using find again, just use the original find and find one of its children.

Not a JS expert so I don't know if this is best way, but this works.
var answerScoreFinal = $(this).closest('.answer-container').find('.answer-score-final');
// had to assign span object to a variable before making Ajax call, then
// use answerScoreFinal.text('value') in the Ajax .done section.
$.ajax({
type: "post",
...
})
.done(function (result) {
var jsonReturn = JSON.parse(result);
answerScoreFinal.text(jsonReturn.score);
})

Related

How to pass variable to child function from HTML page

I want to pass a value from HTML page to child function from parent function.
HTML Page:
<div class="bottom_wrapper clearfix">
<div class="message_input_wrapper">
<input class="message_input" placeholder="Type your message here..." />
</div>
<div class="send_message">
<div class="icon"></div>
<div class="text">Send/div>
</div>
</div>
Parent Function Call:
$('.send_message').click(function (e) {
return [sendMessage(getMessageText()),sendMessage1(getMessageText1())];
});
$('.message_input').keyup(function (e) {
if (e.which === 13) {
return [sendMessage(getMessageText()),sendMessage1(getMessageText1())];
}
});
here getMessageText1 is child function.
Child Function:
getMessageText1 = function () {
var result="";
var id = Parent_FUNC_INPUT;
$.ajax({
url:"func.php",
type: 'POST',
data: ({id:id}),
async: false,
success:function(data) {
result = data;
}
});
I want to populate [[id]] variable in child function from parent function.
First, I'll do my best to clean up the HTML:
<div class="bottom_wrapper clearfix">
<div class="message_input_wrapper">
<input class="message_input" placeholder="Type your message here..." />
</div>
<div class="send_message">
<div class="icon"></div>
</div>
<div class="text">Send</div>
</div>
Using proper indentation will make things far easier to read. And while we're on the subject, you may want to use dashes - instead of underscores _ in your class names, as that's the common convention.
On to your question, it seems like what you want to do is simply pass an argument to getMessageText1 from within (as you refer to it) a "parent" function bound to an event listener.
So you'd define this "child" function with a single parameter:
function getMessageText1(Parent_FUNC_INPUT) {
...
var id = Parent_FUNC_INPUT;
...
}
And then you can just call it with getMessageText1(value) where value is whatever you want to pass in.
One more note: for readability's sake I recommend you do not name your functions the way you have. Having two functions getMessageText and getMessageText1 will just be a source of confusion later on. Instead, think of something more descriptive, ala getMessageTextFromID.
Hopefully I answered the question you meant to ask. Let me know.

How to receive AJAX (json) response in a divs with same class name individually?

I've been getting crazier day after day with this, I can't find an answer, I've spent like 100h+ with this... I hope someone could help me out!
UPDATE:
So to make myself more clear on this issue and be able to get help from others, I basically have 3 containers named "main-container" they all have 3 containers as childs all with the same class name, and when I submit the button, I trigger an ajax function to load the JSON strings comming from php into the child divs, the problem is that I get the 3 "main_containers" to load the ajax at the same time, I only want to load the ajax if I press the button of each "main_container" individually.
I've been using jquery and vanilla JS as well but seems I just can't get it done!
This is how I currently trigger the button with jquery:
$('.trigger_button_inside_divs').click(my_ajax_function);
And this is how my ajax looks like:
function my_ajax_function(){
$.ajax({
dataType: "JSON",
type: 'POST',
url: test.php,
success: function(data) {
$('.div_to_render_JSON_1').html(data.PHP_JSON_1_RECEIVED);
$('.div_to_render_JSON_2').html(data.PHP_JSON_2_RECEIVED);
$('.div_to_render_JSON_3').html(data.PHP_JSON_3_RECEIVED);
}
});
}
HTML looks like this:
<div class="main_container">
<div class="my_div">
//div_to_render_JSON_1
</div>
<div class="my_div">
//div_to_render_JSON_2
</div>
<div class="my_div">
//div_to_render_JSON_3
</div>
<button class="trigger_ajax_function_btn">Click to load ajax</button> //this btn loads ajax into the div class "my_div"
</div>
<div class="main_container">
<div class="my_div">
//div_to_render_JSON_1
</div>
<div class="my_div">
//div_to_render_JSON_2
</div>
<div class="my_div">
//div_to_render_JSON_3
</div>
<button class="trigger_ajax_function_btn">Click to load ajax</button> //this btn loads ajax into the div class "my_div"
</div>
<div class="main_container">
<div class="my_div">
//div_to_render_JSON_1
</div>
<div class="my_div">
//div_to_render_JSON_2
</div>
<div class="my_div">
//div_to_render_JSON_3
</div>
<button class="trigger_ajax_function_btn">Click to load ajax</button> //this btn loads ajax into the div class "my_div"
</div>
So in conclusion, each of those 6 "divs" has a button that triggers an function containing my ajax to render inside that particular div. But what I get is that every time I click that triggering button, I get the ajax to render in all of the 6 divs, instead of render on each particular div only when I click its particular button.
Thanks a lot people, I really hope to get this done!
Cheers.
PD:
This is something a programmer did to achieve what I'm trying to achieve but I just can't figure out what in this code is that is making possible clicking 1 button and affect THAT html element , even though they all have the same class.
(function(){
$("form input[type=submit]").click(function() {
$("input[type=submit]", $(this).parents("form")).removeAttr("clicked");
$(this).attr("clicked", "true");
});
var xhr = new XMLHttpRequest();
var el;
function SetDataInTheForm()
{
var resp = JSON.parse(xhr.response)
var pt=0
var ct=0
var gt=0
Array.prototype.forEach.call(el.querySelectorAll(".test"),function(e,i){
e.innerHTML=resp[i].name
})
Array.prototype.forEach.call(el.querySelectorAll(".p"),function(e,i){
e.innerHTML=parseFloat(resp[i].p).toFixed(0)
pt+=parseFloat(resp[i].p)
})
Array.prototype.forEach.call(el.querySelectorAll(".c"),function(e,i){
e.innerHTML=parseFloat(resp[i].c).toFixed(0)
ct+=parseFloat(resp[i].c)
})
Array.prototype.forEach.call(el.querySelectorAll(".g"),function(e,i){
e.innerHTML=parseFloat(resp[i].g).toFixed(0)
gt+=parseFloat(resp[i].g)
})
el.querySelector(".wtp").innerHTML=parseFloat(resp[0].total).toFixed(0)+" "+resp[0].unit
el.querySelector(".wtc").innerHTML=parseFloat(resp[1].total).toFixed(0)+" "+resp[1].unit
el.querySelector(".wtg").innerHTML=parseFloat(resp[2].total).toFixed(0)+" "+resp[2].unit
el.querySelector(".pt").innerHTML=pt.toFixed(0)
el.querySelector(".ct").innerHTML=ct.toFixed(0)
el.querySelector(".gt").innerHTML=gt.toFixed(0)
}
function HandleSubmit(e)
{
el=e.currentTarget
e.preventDefault();
xhr.open("POST","/url_here.php",true)
xhr.setRequestHeader("content-type","application/x-www-form-urlencoded")
xhr.onload=SetDataInTheForm
var button=e.currentTarget.querySelector("input[type=submit][clicked=true]")
button.removeAttribute("clicked")
xhr.send($("#"+e.currentTarget.id).serialize()+"&"+button.getAttribute("name")+"=on")
}
[].forEach.call(document.querySelectorAll("._form_"),function(form){
form.addEventListener("submit",HandleSubmit,false);
})
})()
Remember that $('.div_container_to_render_JSON') is a new selector that selects all elements with a class div_container_to_render_JSON. What you want to happen is figuring out where that click came from, and find the corresponding div_container_to_render_JSON.
Luckily for you, a jQuery click handler sets the this keyword to the HTMLElement where the click was captured. You can use this to get the parent element.
$('.your-button').on('click', function () {
const myButton = $(this);
$.ajax({
// ...
success (data) {
myButton.parent().html(data.PHP_JSON_RECEIVED);
// or if you need to find a parent further up in the chain
// myButton.parents('.div_container_to_render_JSON').html(data.PHP_JSON_RECEIVED);
}
});
});
The problem is that your class selector is indeed selecting all your divs at the same time.
Solution, set identifiers for your divs as such:
<div class="my_div" id="my_div_1">
and then you can use those id's to fill in the data:
$('#my_div_1').html(data.PHP_JSON_1_RECEIVED);
and repeat for your 6 divs (notice the change from class selector '.' to identifier selector '#')
Thanks for the replies people. I finally figured it out after days of hard work, it was something really simple.. here's the answer:
$('.trigger_button_inside_divs').click(my_ajax_function);
var thisButton = $(this);
var thisDiv = thisButton.closest(".main_container");
function my_ajax_function(){
$.ajax({
dataType: "JSON",
type: 'POST',
url: test.php,
success: function(data) {
thisDiv.find('.div_to_render_JSON_1').html(data.PHP_JSON_1_RECEIVED);
thisDiv.find('.div_to_render_JSON_2').html(data.PHP_JSON_2_RECEIVED);
thisDiv.find('.div_to_render_JSON_3').html(data.PHP_JSON_3_RECEIVED);
}
});
}

load to work as append in jquery

i am creating form using js functions.. i want that when this function is called twice form should be created twice.. i am using jquery load hence it is overwriting again and again...
my jquery code:
function form(module,user) {
$.post("php/test.php",{ module:module , user:user}, function(data, status){
var f= jQuery.parseJSON( data );
$(".cards-container").load("modules/ams.html",function(){
$(".cards-container > div").addClass("card card-shadow animated fadeInDown");
$(".form-t").append("<input type='text'"+"placeholder="+f.text+" name='fname' required>");
});
});}
form("home",200);form("home",300);
AMS.html:
<div class='w100 large forms'>
<form action='test.php' method='post'>
<div class="form-t"></div>
<input type='submit' value='Submit'></form>
</div>
JQuery load() method always replaces content of "element-receiver". Use get() method to request new content with subsequent appending:
var f= jQuery.parseJSON( data );
$.get('modules/ams.html', function(data){
$(".cards-container").append(data);
$(".cards-container > div").addClass("card card-shadow animated fadeInDown");
$(".form-t:last").append("<input type='text'"+"placeholder="+f.text+" name='fname' required>");
});
Load will always overwrite. It is a shortcut function for an Ajax method. So instead, use Ajax so you have control of the result:
$.ajax({
url: "modules/ams.html",
type: "GET"
}).done(function (result) {
$(".cards-container").append(result);
});
This will just append the content directly into the container. You will have to apply any other logic you need. Remember that ids should be unique and forms cannot be nested so make sure you avoid loading html with a form when your container is already within a form.

$('#notificationClick').click not working

so I'm trying to make this works here is the jquery+php.
When I try to trigle the click in jquery it doesnt even does the "alert()".
PHP(Updated):
$MSG_Notification_sql = mysqli_query($Connection, "SELECT * FROM notifications WHERE user_id='".$bzInfo['id']."'");
while ($MSG_Notification_row = mysqli_fetch_array($MSG_Notification_sql)){
$MSG_Notification_rows[] = $MSG_Notification_row;
}
foreach ($MSG_Notification_rows as $MSG_Notification_row){
$bzWhen = date('d-m-Y H:m:i', strtotime($MSG_Notification_row['when']));
echo '<form method="POST">
<div class="notificationClick notification-messages info">
<div class="user-profile">
<img src="assets/img/profiles/d.jpg" alt="" data-src="assets/img/profiles/d.jpg" data-src-retina="assets/img/profiles/d2x.jpg" width="35" height="35">
</div>
<div class="message-wrapper">
<div class="heading"> '.$MSG_Notification_row['title'].'</div>
<div class="description"> '.$MSG_Notification_row['description'].' </div>
<div class="date pull-left"> '.$bzWhen.'</div>
</div>
<input name="notificationID" value="'.$MSG_Notification_row['id'].'" style="display: none" />
<div class="clearfix"></div>
</div>
</form>';
}
Javascript(Updated):
$(document).ready(function(){
$('.notificationClick').click(function(event){
alert('Ok');
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = $('#notificationClick').serialize();
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : '../../class/notifications/msgs_del.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json' // what type of data do we expect back from the server
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
window.location = '/?page=messages&sub=inbox&bx=preview&id='+ data.notificationID +'';
});
event.preventDefault();
});
});
Can anybody help me please? I'm trying to complete this but nothing :(
First as the others say, ids need to be singular. So use the class you already have. Now inside, you need to use the current form that you clicked on, not all the forms.
$('.notification-messages').click(function(event){ //<-- change to class
var formData = $(this).closest("form").serialize(); //change to this
...
If you are loading these dynamically, you need to use event delegation
$(document).on("click", '.notification-messages', function(event){
var formData = $(this).closest("form").serialize();
...
You can concatenate the timestamp to your id to make it unique (separated by an _ if you like) and change your selector for the click event to $('[id*="notificationClick_"]')
On the other hand, you might want to use a class instead, that's what it's there for:
$(".notification-messages")
You're using ID, you can only bind click to 1 id not multiple ids.
You should use the class to bind the .click function.

Only slideUp the deleted message

I'm using a PM system and added the delete-message feature. I've got a form which checks for the message_id and message_title. The form posts to delete_message.php page which contains the query to delete the message. This has been done via Javascript as I dont want the page to refresh.
I've got two functions for this:
function deleteMessage() {
$.ajax({
url: "message/delete_message.php",
type: "POST",
data: $("#delMsgForm").serialize(),
success: function(data,textStatus,jqXHR){ finishDeleteMessage(data,textStatus,jqXHR); }
});
}
function finishDeleteMessage( data , textStatus ,jqXHR ) {
$(".inboxMessage").slideUp('slow');
}
Currently when I click on the delete button (image of a trashcan) it deletes the message without reloading the page, as a finishing touch, it slidesUp the divclass (inboxMessage) the message is in. Since I tell it to slide up this class, it slides up every message. This is my piece of code containing the classes and the form:
<div class="inboxMessage">
<div class="inboxMessageImg NoNewMsg"></div>
<div class="inboxMessageHeader">
<a id="ajax" class="inboxMessageLink" onclick="showMessage('.$row['message_id'].')">'.$row['message_title'].'</a>
<p class="inboxMessageStatus Read">'.$inboxMessageStatus_Read.'</p>
</div>
<div class="inboxMessageDescription">'.$inboxMessageDescription.'</div>
<div class="inboxMessageActions">
<form id="delMsgForm" name="delMsgForm" action="message/delete_message.php" method="post">
<input type="hidden" id="msgTitle" value="'.$row['message_title'].'" name="message_title">
<input type="hidden" id="msgID" value="'.$row['message_id'].'" name="message_id">
</form>
<input type="submit" id="ajax" value="" name="deleteMessageButton" class="deleteMessageIcon" onclick="deleteMessage()">
</div>
</div>
What I want it to do is to slideUp only the message which has just been deleted by the user. I know this has to be done by telling javascript to only slideUp the deleted message which contains the message_id and/or message_title.
I've tried several things, but no love whatsoever. I'm also not that familiar with javascript/ajax. Any help would be highly appreciate.
Cheers :)
where do you call deleteMessage from? indirect the function call through another function which knows the parent of your "trash can", and can call slide up on that specific one.
function deleteMessage (element) {
//element will be clicked button
var container = $(element).closest("div.inboxMessage"),
//container div including the trashcan
$.ajax({
url: "message/delete_message.php",
type: "POST",
data: $("#delMsgForm").serialize(),
success: function(data,textStatus,jqXHR){
finishDeleteMessage(container);
}
});
});
and this will be your button
<input type="submit" id="ajax" value="" name="deleteMessageButton" class="deleteMessageIcon" onclick="deleteMessage(this)">
Apparently, you've got more divs with class inboxMessage. Since you're adding this code:
$(".inboxMessage").slideUp('slow');
.. all divs with that class will remove. If you want just one div to remove, give it a unique ID or data-attribute and hide it that way.
For example: add the message-id to the div..
<div class="inboxMessage" id="(message_id)">
..and use..
$(".inboxMessage#message_id").slideUp('slow');
.. to slide up the right div.
Edit:
Add your message ID to the div and to the function deleteMessage(), so it will be deleteMessage(message_id).
function deleteMessage(message_id) {
$.ajax({
url: "message/delete_message.php",
type: "POST",
data: $("#delMsgForm").serialize(),
success: function(){ finishDeleteMessage(message_id); }
});
}
function finishDeleteMessage(message_id) {
$(".inboxMessage#"+message_id).slideUp('slow');
}

Categories