How to get attribute text using ajax? - javascript

I'm trying to get attribute text using ajax but not working. For example
get.php
<div id="get" title="New Text"></div>
html
<div id="title"></div>
javascript
$.ajax({
url: 'index.php?route=get.php',
dataType: 'html',
success: function(html) {
var title = $(html).find('#get').attr('title').text();
console.log(title);
$('#title').text(title);
}
});

Assuming data returned by $.ajax() is <div id="get" title="New Text"></div> the method find() will not work as it looks into descendant. You can directly get its attribute as
var title = $(html).attr('title');
OR, Create a DOM element with returned data as HTML then use find()
var title = $('<div />').html(html).find('#get').attr('title');

var html = '<div id="get" title="New Text">12345</div>'
var title = $(html).attr('title');
$('#title').text(title);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="title"></div>
If you want to get value of attribute, you should use $.attr('attr') instead of $.attr('attr').text()

Related

Update dynamically generated list item (generated using PHP) after ajax call

The following HTML code is being echoed using a while loop in PHP which is adding a list item after fetching data from database.
PHP:
echo '
<li>
<div class="collapsible-header">
<div class = "left">
<div class = "issueStatusIcon" style = "background-color:'.$smallCircleColor.';">'.$smallMsg.'</div>
<span class = "issueTitle" style = "font-family: robotoBold">'.$issueTitle.'</span>
</div>
<div class = "issueButtonsGroup">
<form id = "archiveIssueForm'.$i.'" issue-name = "'.$issueTitle.'" action = "archiveIssue.php">
<input type = "hidden" value = "'.$issueID.'" name = "issueID"/>
</form>
<a class = "right archiveIconButton" onclick = "ajaxIssueArchive('.$i.')" href = "#">
<i class="material-icons black-text issueOptions archiveIcon">archive</i>
</a>
<a class = "right"><i class="material-icons black-text issueOptions">edit</i></a>
</div>
</div>
</li>
';
This is the preview image of the generated list:
Notice the cursor over the archive button which archives the list item. The class for that button is archiveIconButton (you can find it in the above code). When the button is clicked, archiveIssueForm is submitted via AJAX (each form has a unique identifier variable $i appended to its id).
Following is the JQuery AJAX code:
JQuery:
<script>
function ajaxIssueArchive($num){
$.ajax({
type: "post",
url: "archiveIssue.php",
data: $('#archiveIssueForm' + $num).serialize(),
success: function(data){
$fetchIssueName = $('#archiveIssueForm' + $num).attr("issue-name");
$toastText = $fetchIssueName + " has been archived";
Materialize.toast($toastText, 3000);
$('#archiveIssueForm' + $num).html(data);
}
});
}
</script>
After archiving any list item, it gets deleted from the database. I want to update the ul element which contains these list items so that the list item which gets deleted doesn't gets displayed after the AJAX form submission.
Assume the id of ul to be issueListUL.
What i'm currently getting is the whole code of the html page displayed in the li item. I am certainly doing something wrong, any help would be appreciated!
After archiving a list item:
I was able to solve this issue in the following way, The JQuery script in the question should be changed like this:
JQuery:
<script>
function ajaxIssueArchive($num){
$.ajax({
type: "post",
url: "archiveIssue.php",
data: $('#archiveIssueForm' + $num).serialize(),
success: function(data){
//assigning the updated ul's html to a variable
$afterIssueArchival = $(data).find("#issueListContainer").html();
//toast
$fetchIssueName = $('#archiveIssueForm' + $num).attr("issue-name");
$toastText = $fetchIssueName + " has been archived";
Materialize.toast($toastText, 3000);
//updation of ul's html, ID of the ul which contains all the list items is assumed to be 'listContainer'
$("#issueListContainer").html($afterIssueArchival);
}
});
}
</script>
When updating an element's html, just extract the element's updated html code from data attribute in the ajax code (as show in the above code) and update the existing element's html with it!
Hope this helps people with the same problem as mine! :D

Jquery AJAX id selector and post with change class

I have one question. I am trying to make a ajax post with id and also trying to change the class which data-id selected.
I have created this DEMO from codepen.io
In this demo you can see there is a two container div and the container divs inside some different color div.
So what i am trying to do. When i click .change_pri then that clicked (.style, style1, style2) will automatically change .type style like:
<div class="test" id="1">
<div class="type style">selected color</div> <-- class is style
<div class="select_types">
<div class="type_s"><div class="change_pri style" data-id="0">0</div></div>
<div class="type_s"><div class="change_pri style1" data-id="1">1</div></div>
<div class="type_s"><div class="change_pri style2" data-id="2">2</div></div>
</div>
</div>
after clicking change_pri style2 then it need to looks like this:
<div class="test" id="1">
<div class="type style2">selected color</div> <-- after clicking class is style2
<div class="select_types">
<div class="type_s"><div class="change_pri style" data-id="0">0</div></div>
<div class="type_s"><div class="change_pri style1" data-id="1">1</div></div>
<div class="type_s"><div class="change_pri style2" data-id="2">2</div></div>
</div>
</div>
and post the data-id with ajax.
I do not know how the rest of that section, but I was able to do so. Anyone can help me in this regard ?
$(function() {
var i;
i = $(this).attr('id');
});
$('.change_pri').on('click', function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "chage_number.php",
data: {
id: i,
},
});
});
The Javascript with the AJAX request should probably look something like this:
$('.change_pri').click(function(){
var dataid = $(this).attr('data-id');
var id = $(this).closest('.test').attr('id');
$.ajax({
type: "POST",
url: "chage_number.php",
data: { dataid : dataid, id: id }
}).success(function(result){
alert(result);
});
});
And then depending on what you want to do back-end, you can access that variable in chage_number.php via $_POST['id'].
So a simple example would be
chage_number.php
echo $_POST['id'] . ", ". $_POST['dataid'];
This should alert() both ids.
you can try this..
$('.change_pri').on('click', function(e) {
var styletype = $(this).attr('class').split(' ')[1];
var ctoremove = $('.type').attr('class').split(' ')[1];
$('.type').removeClass(ctoremove).addClass(styletype);
$.ajax({
type: "POST",
url: "chage_number.php",
data: { id: i }
}).success(function(result){
alert(result);
});
});
and here is the FIDDLE
I take it as the second container should be an example of what happens clicking the div's of the first one.
See this working example, it should do what you asked for: http://codepen.io/anon/pen/qdxVzW
This is where you get an alert telling you which data-id you clicked and then it changes the class of the .type element
alert($(this).attr('data-id')); //this can be removed, it's just a test
$('#test-1 > .type') //remove styleN and add the needed one
.removeClass('style0')
.removeClass('style1')
.removeClass('style2')
.addClass('style'+$(this).attr('data-id'))
The part about the ajax call remains almost the same, with a little modification when it comes to setting the id to be sent:
$('.change_pri').on('click', function(e) {
//As suggested by #Mackan, a little modification: store data-id
var dataId = $(this).attr('data-id');
$.ajax({
type: "POST",
url: "chage_number.php",
data: {
id: dataId //send the correct id
}
});
});
The function at the beginning of the script can be safely removed, it doesn't affect the rest of the code :)
I was almost forgetting: add a 0 to the style which doesn't have a number, like:
<div class="change_pri style0" data-id="0">0</div></div>
Otherwise when it come's to data-id=0 the script doesn't know what to do. Of course, same thing should be done into css code:
.style0{
background-color:red;
color:#ffffff;
margin:5px;
}

$('#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.

parse output and style xml data

I have xml located on a remote server with the following format:
<query_results>
<row id="1">
<distance>...</distance>
<post_title>...</post_title>
<post_excerpt>...</post_excerpt>
<ID>...</ID>
</row
<row id="2">
.........................etc
</query_results>
I need my javascript to go through each of these rows in a way so that I can append each to a div on my html document with a class for styling without the script caring too much what the individual names are for each element in each row. I have used Jquery's parse XML function, however i am lost after that. Anybody got a good idea how to do this? Any help is appreciated a lot.
I made a JSFiddle with a possible solution to your problem. It loads your sample XML from this Gist.
In the HTML there is a placeholder:
<div id="query_results"/>
You can load the file using JQuery ajax:
$.ajax({
type: "GET",
url: "/url/to/your/file.xml",
dataType: "xml",
success: parser
});
In the parser function you can use .find() and .children() to navigate the XML:
function parser(xml) {
$(xml).find('query_results').children().each(function() {
var row = $(this);
var id = row.attr("id");
var rowContents = "";
row.children().each(function() {
var tag = $(this);
var tagName = tag[0].tagName;
rowContents += "<div class='"+tagName+"'>"+tag.text()+"</div>";
});
var newRow = "<div id='row"+id+"'>"+rowContents+"</div>";
$("#query_results").append(newRow);
});
}
I used the row IDs and names to create and ID for each row DIV, for example:
<div id="row1"> ... </div>
And then used the tag names inside each row as classes:
<div class="distance"> ... </div>
<div class="post_title"> ... </div>
The parser() function above builds the divs and adds them to the placeholder div. The final result will be:
<div id="query_results">
<div id="row1">
<div class="distance">...</div>
<div class="post_title">...</div>
<div class="post_excerpt">...</div>
<div class="ID">...</div>
</div>
<div id="row2">...</div>
</div>
Then you can style the result in CSS using selectors such as:
#query_results div { ... }
#query_results div div { ... }
#row1 .distance { ... }
#row2 .ID { ... }

How to detect the div in which a link to a javascript function has been clicked

I have the following html code:
<div id="result1" class="result">
... some html ...
... link
... some html ...
</div>
<div id="result2" class="result">
... some html ...
... link
... some html ...
</div>
<div id="result3" class="result">
</div>
<div id="result4" class="result">
</div>
The goal is to update the content of the next div when I click on the link. So for instance, when I click on a link in #result2, the content of #result3 will be updated.
Here is the javascript function:
<script>
function updateNext(elem, uri) {
$.ajax({
url: uri,
success: function(data) {
elem.closest('.result').nextAll().html('');
elem.closest('.result').next().html(data);
}
});
}
</script>
However, when I use the link, elem is set as the window, not the link itself.
The content of the div is generated by a server which should not know the position of the div in which the code he is generating will be.
I also tried with a
<a href="javascript:" onclick="updateNext(...
with no other result...
any idea ? :-)
Thanks,
Arnaud.
this returns the window when used in href, but here it returns the actual link:
... link
Don't forget to use the jQuery $ in:
$(elem).closest('.result').nextAll().html('');
$(elem).closest('.result').next().html(data);
Why do you use inline scripts when you alrady are using jQuery?
I've setup a Fiddle for you which does what you want: http://jsfiddle.net/eLA3P/1/
The example code:
$('div.result a').click(function() {
$(this).closest('div.result').next().html('test');
return false;
});
First, you must remove those href="javascript:..." attributes. Please never use them again, they are evil.
Then, bind a click handler via jQuery, which you are alredy using:
// since you dynamically self-update the a elements, use "live()":
$("div.result a").live("click", function () {
var $myDiv = $(this).closest("div.result");
$.ajax({
url: "/build/some/url/with/" + $myDiv.attr("id"),
success: function(data) {
$myDiv.next("div.result").html(data);
}
});
return false;
});
Done.
Try to use jQuery to bind the event instead putting a javascript link in the href.
<div id="result1" class="result">
link
</div>
$('.resultLink').click(function(){
var elem = $(this);
$.ajax({
url: uri,
success: function(data) {
elem.closest('.result').nextAll().html('');
elem.closest('.result').next().html(data);
}
});
});
You should do it like this:
http://jsfiddle.net/hJhC7/
The inline JavaScript is gone, and the href is being used to store the "uri", whatever that might be. I'm assuming it's different for each link.
The //remove this lines are just to make $.ajax work with jsFiddle.
$('.update').click(function(e) {
e.preventDefault();
var elem = $(this);
$.ajax({
type: 'post', //remove this
data: {html: Math.random() }, //remove this
url: $(this).attr('href'),
success: function(data) {
//not sure why you're doing this
//elem.closest('.result').nextAll().html('');
elem.closest('.result').next().html(data);
}
});
});
with this HTML:
<div id="result1" class="result">
link
</div>
<div id="result2" class="result">
link
</div>
<div id="result3" class="result">
link
</div>

Categories