i have a load more button on some content that is pulled from a database via ajax.
The ajax call looks like so:
// JavaScript Document
// load more builds function
$(document).ready(function(){
var pageIndex = 1;
$('#loadmorebuilds-div').click(function() {
$.ajax({
url: 'includes/loadmorebuilds.php?type=' + type + '&pageIndex=' + pageIndex,
success: function(html) {
$("#buildcontainer").append(html).waterfall('reflow');
$("#loadmorebuilds-div").stop().fadeOut();
pageIndex++;
var rowCount = MAKE THIS THE VALUE THAT IS APPENDED;
$('.testcount').html(rowCount);
if (rowCount < 18) {
$('#loadmorebuilds-div').remove();
$('.countvar').detach();
} else {
$('.countvar').detach();
}
}
});
});
});
In the appended items, is a div that contains a value of the row count for the database query that has been carried out via the above ajax call.
Normally, i would put this value into a JSON return and simply do e.g.:
rowCount = response.rowCount
However i am not using a JSON datatype but HTML.
How can i get this value from the appended div in the data and use it to set a var?
Thanks!
Use either:
val = $("#thatDiv").text();
or
val = $("#thatDiv").attr("value");
The latter of which, is if you put the value in a pseudo attribute...
Related
I am trying to display region and city if is available and display the country text if city is not available. I tried adding if else condition and setup the variable but it returns blank, undefined or nulled. On the header I have the script below
jQuery.ajax( {
url: '//freegeoip.net/json/',
type: 'POST',
dataType: 'jsonp',
success: function(location) {
jQuery('#city').html(location.city);
jQuery('#region-name').html(location.region_name);
jQuery('#country-name').html(location.country_name);
}
} );
var mycountry = document.getElementById("country-name").value;
var mycity = document.getElementById("country-name").value;
var myregion = document.getElementById("city").value;
then on the body I have
if (mycity != "") {
document.write(mycity); document.write(myregion); }
else {
document.write(mycountry);
}
and the result I got is nulled or undefined.
reference
http://pastebin.com/xaqq16Ks
AJAX is an async operation. You can't use document.write with AJAX. Add the if (city === '') logic to success callback instead.
If you want to display them in text fields, then you should change value instead of html:
$('#city').val(location.city);
$('#region-name').val(location.region_name);
$('#country-name').val(location.country_name);
and the rest of the code will run just fine.
Otherwise if you want to display them with a span/div or any other element, use should change the second part of your code, namely, you should get the innerHTML property and not value as follows:
var mycountry = document.getElementById("country-name").innerHTML;
var mycity = document.getElementById("city").innerHTML;
var myregion = document.getElementById("region-name").innerHTML;
I am dynamically creating a textbox at runtime using javascript and passing its value to my servlet page using a href(which is also created at run time along with the textbox) but somehow the value is being passed as "Null". I am not understanding it why..Can anyone help me on this ??
Here is my javascript code :
//here I am creating textbox
var td1 = document.createElement("TD");
var strHtml1 = "<INPUT TYPE=\"text\" NAME=\"in_name\" id =\"in_nm\" SIZE=\"18\" STYLE=\"height:24;border: 1 solid;margin:0;\">";
td1.innerHTML = strHtml1.replace(/!count!/g, count);
//Here I am fetching its value
var nm=document.getElementById("in_nm");//this value is being passed null
//Here I am passing it through a href tag
var strHtml3 = "<a id=\"link\" href=\"UserHandler?action=insert&&name="+nm+"\">Add Row</a>";
td3.innerHTML = strHtml3.replace(/!count!/g, count);
var dt=document.getElementById('in_dt');
You never put your HTML string into the document, so you can't fetch it from the document.
The DOM you have created never been placed in the document so you can't catch it.
In addition, if you immidietly catch the element it will be empty all the time.
You can append the input field to the body as hidden and then to fetch it.
strHtml1.style.display = 'hidden';
document.body.appendChild(strHtml1);
// At this point the dom is in the HTML and it is not visible and now you can use it.
Add it before your fetching the value.
For those who are facing similar problem as mine, I am posting the solution for their reference
The problem was solved by fetching the value onchange and passing request through ajax as :
$(".edit_trr").click(function() //edit_trr is my class of the dynamic row added
{
}).change(function()
{
var nam=$("#in_name").val(); //in_name is my id of the textfield
var datastr='name='+nam;
if(nam.length >0) //checks if there is value in textfield
{
$.ajax({
type: "POST",
url: "add.jsp", //link of my jsp page where data is added in database
data: datastr,
cache: false,
success: function(html)
{
alert('Inserted');
}
});
}
else
{
alert('Enter Something');
}
});
On JSP page request send can simply be fetched as :
request.getParameter("name");
I would like to know how I can use the result of an ajax request as an "object". I'll try to explain. I have an ajax request that get a number, every 2 seconds, to an xml file. Then I render it into my html.
Here is my js:
var url = window.location.pathname.split('/');
var id = url[3];
setInterval(function() {
$.ajax({
type: "GET",
url: "http://myxml",
success: parseXml
});
}, 2000);
function parseXml(xml){
$(xml).find("user").each(function() {
if($(this).attr("id") === id ) {
$(".DubScore").html($(this).attr("count"))
}
});
}
and my html:
<div class="DubScore"> </div>
It works find, I have a count displayed to my page.
What I want to do, is to take this number and be able to do whatever I wan't with it in my html. For example, name it "Score", and be able to do "Score" + 2 , and things like that.
I hope my question is clear enough. Thank you for your help.
You can parse the attribute value and store it in a global variable :
var score;
function parseXml(xml){
$(xml).find("user").each(function() {
if($(this).attr("id") === id ) {
score = parseInt($(this).attr("count"), 10);
}
});
}
Afterwards, you may do, for example,
score += 2;
$(".DubScore").html(score);
I am having some trouble working out how to get data from a form to post via ajax. I have the following code but it doesn't seem to be sending though the data from elements like checkboxes and radio buttons. Instead it is sending though all the fields. ie if there is a set of radiobuttons it is sending through all the possibilities not just the checked ones. The form can be made up of any type of element and have an undermined amount of elements in it, so I need to iterate through in the way I am. That part seems to be working, but I can't seem to get the javascript to grab the selected data. Do I need to manually check each element's type and then check to see if it checked etc?
myString = "";
my_form_id = "1";
my_url = "phpscript.php";
elem = document.getElementById("form_" + my_form_id).elements;
for(var i = 0; i < elem.length; i++)
{
if (i>0) { myString += "&"; }
myString += elem[i].name + "=" + elem[i].value;
}
$.ajax({
type: "POST",
url: my_url,
data: myString,
success: function(data) {
// process the post data
}
});
`
Since you're using jQuery, you can drastically simplify it all:
var my_form_id = "1";
var my_url = "phpscript.php";
var form = $("#form_" + my_form_id);
$.ajax({
type: "POST",
url: my_url,
data: form.serialize(),
success: function(data) {
// process the post data
}
});
jQuery's serialize method does all the work for you. But if you wanted to do it by hand, then yes, you would have to check each field.
I'm trying to load some ajax content into a table, unfortunately it's only loading the last row multiple times instead of loading each new rows.
This is the code I'm using:
function periodicRefresh()
{
$.ajax({
type: 'GET',
url: 'include/ajaxActions.php',
data: "action=displayLastEvent",
success: function(msg){
var newid = msg;
current = $("#list tr:first").get(0).id;
if(newid != current){
while (current<newid)
{
current++;
addToList(current);
}
}
}
});
}
function addToList(x)
{
$.ajax({
type: 'GET',
url: 'include/ajaxActions.php',
data: "action=displayRow&row="+x,
success: function(msg){
$("#list").prepend(msg);
$("#list tr:first").highlightFade({
speed:3000
});
lastrow = x-20;
$('#'+lastrow).remove();
}
});
}
displayLastEvent returns the id of the last row.
displayRow returns the last row
You need to push your xmlHttps into an array or abstract data type, which you can then attach events handlers. Seems jquery doesn't do that for you.
I would address this issue by encouraging you to change your approach since it looks like you're likely making more AJAX requests than necessary whenever more rows need to be added to the list (2+ instead of just 2).
I would update include/ajaxActions.php?action=displayRow to accept a CSV of ids (or whatever it is you're passing in), and returning a set of row data, instead of data for just one row.
I think that:
current = $("#list tr:first").get(0).id;
return always the same result as jQuery remember only the page when it was first loaded.
For example, if you have a single tr[id=0]:
pass 1 : current = 0; msg = 1 -> 1 tr prepended with id = 1;
pass 2 : current is always 0 (not 1); msg = 1 -> 1 tr prepended with id = 1;
...
what you should do, is make jQuery recognize your page structure after adding your messages, or store the last index in a different way: using hidden input for example:
HTML:
<input type="hidden" value="0" id="lastId"/>
script:
initialize #lastId value when the page is loaded:
$(document).ready(function(){
$("#lastId").val(0);//or by using your displayLastEvent action
});
modify periodicRefresh to read #lastId value:
function periodicRefresh()
{
$.ajax({
type: 'GET',
url: 'include/ajaxActions.php',
data: "action=displayLastEvent",
success: function(msg){
var newid = msg;
var current = $("#lastId").val();
if(current<newid) $("#lastId").val(newid);
if(newid != current){
while (current<newid)
{
current++;
addToList(current);
}
}
}
});
}