How to make an AJAX call to an html element? - javascript

What I want to do is pretty simple. I want to make an AJAX call to a specific html class, so that whenever the html page is loaded, jquery will make an AJAX call to that specific html div class.
For example:
<div class="targeted"></div>
In jquery:
$('.targeted')
I know that the syntax to make an AJAX call is:
$.ajax({
type: "GET",
url: "/api/something",
success: function(data) {
console.log(data);
}
});
But how do I implement this AJAX call to the $('.targeted') whenever the page is loaded?
Thanks

If you mean you want to display the result of the ajax call in the element, you update the element from within the success callback:
$.ajax({
type: "GET",
url: "/api/something",
success: function(data) {
$('.targeted').html(data);
}
});
That example assumes
You want to replace the content of the element (rather than adding to it); more options in the jQuery API.
data will be HTML. If it's plain text, use .text(data), not .html(data). If it's structured data, then of course you'll need to do more work to put the information in the desired form.

window.onload = function() {
yourFunction();
};
function yourFunction(){
$.ajax({
type: "GET",
url: "/api/something",
success: function(data) {
$('.targeted').html(data);
}
});
}
OR Drectly you can pass that method in document ready it will execute automatically
$(document).ready(function(){
//This will execute onload oof your web page what you required
yourFunction();
})
function yourFunction(){
$.ajax({
type: "GET",
url: "/api/something",
success: function(data) {
$('.targeted').html(data);
}
});
}

For when the page is loaded, you use:
$( document ).ready(function() {
console.log( "ready!" );
});
Inside the document ready, you put your AJAX call. If the result you get is in JSON format, you need to include the dataType as well like this:
$.ajax({
method: "GET",
url: "/api/something",
dataType: "json"
})
.done(function( data ) {
$('.targeted').append(JSON.stringify(data));
});
If the result is not JSON, then you can just append the data.
Also note:
The jqXHR.success(), jqXHR.error() and jqXHR.complete() callbacks are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail() and jqXHR.always() instead.
Please look at the jQuery documentation.

you can use jquery load like this:
$(".targeted").load('/api/something');
if you want to wait untill after the page is loaded, wrap it with window load like so:
$(window).load(function () {
$(".targeted").load('/api/something');
});
P.S. $(window).load(..) and $(".class").load(url) are two different functions

You can do:
$(function() {
$.ajax({
type: "GET",
url: "/api/something",
})
.done(function(data) {
$('.targeted').text(data);
});
});

Related

Unable to apply jquery

i have a page searchKB.jsp and it has some code like this :
$.ajax({
type: "GET",
data: {app:app,env:env,ptitle:ptitle,kbaseId:kbaseId},
url : 'jsp/knowledgeBase/kbResults.jsp',
success: function(res){
getResponse(res);
},
error: function(){
document.getElementById("message").style.display="";
$('#message').html("<b><font color=red face=Arial size=2>An Error encountered while processing your Request.Please try again after sometime.</font></b>");
}
});
function getResponse(response){
document.getElementById("message").style.display="none";
document.getElementById("KBInfo").innerHTML = response;
}
searchKB.jspis calling kbResults.jsp through the above code and now i want to apply jquery on elements of kbResults.jsp ..how will i do this ?
i tried everything but it is failing
<input type="button" id="expand3" value="Hide"/> <div id="result3">hide this</div>
and corresponding jquery code
$("#expand3").click(function(){
$("#result3").hide();
});
Try using something like this.
$(document.body).on("click", "#expand3", function(){
$("#result3").hide();
});
Assuming that elements with IDs expand3 and result3 are coming from that AJAX call, you can do something like this:
$.ajax({
type: "GET",
data: {app:app,env:env,ptitle:ptitle,kbaseId:kbaseId},
url : 'jsp/knowledgeBase/kbResults.jsp',
success: function(res){
getResponse(res);
} // removed the error callback for clarity
});
function getResponse(response){
$("#message").hide();
$("#KBInfo").html(response);
// only then attach the listener
// because #expand3 needs to be in the DOM
$("#expand3").click(function(){
$("#result3").hide();
});
}
Or, you can use #ashokd's solution with delegated listener.

Query database on beforeunload event

I was wondering if its possible to send a query to the database on the beforeunload event.
$(window).on('beforeunload',function() {
console.log('beforeunload called. run query');
});
If so, how would I do it? I need to run a query to insert dynamic values into the database.
You could try this, but beware that the onbeforeunload event is limited for certain browsers..
window.onbeforeunload = mySession;
function mySession(){
$.ajax({
url: "/../../myPHP.php",
async: false,
type: "GET"
});
return "WhatEverMessageYouFeelLike";
}
and your PHP executing query from AJAX handling..
$delete = "DELETE FROM MyTable WHERE id=" .$_SESSION['mySessionVariable'];
// your query..
Use a jQuery AJAX call. Assuming you're POSTing your data, try this:
$.post(
'your/url',
{
your : "Post Vars"
},
function(data) {
// not sure if you'll need to do anything here actually.
},
'json' // or 'html', or whatever you want your return format to be
);
I thinks the best way to use post by jQuery is $.post() method.but u can also use $.ajax
Sample way to use is
jQuery
$.post( "ajax/test.html", function( data ) {
$( ".result" ).html( data );
});
jQuery Ajax
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});

Using Two jQuery Ajax Methods in Script

Can you please let me know how I can use two Ajax call in one script and avoid conflicts? For example, I have a script like this:
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: 'POST',
url: 'nearest.php',
success: function( resp1 ){
$("#div1").html(resp1);
}
});
$.ajax({
type: 'POST',
url: 'closettime.php',
success: function( resp2 ){
$("#div2").html(resp2);
}
});
</script>
Can you please let me know how I can use both methods in the script? Thanks.
Just close DOM ready with }); at the bottom of your script block and you're all set:
$(document).ready(function() {
$.ajax({
type: 'GET',
url: 'nearest.php',
success: function( resp1 ){
$("#div1").html(resp1);
}
});
$.ajax({
type: 'GET',
url: 'closettime.php',
success: function( resp2 ){
$("#div2").html(resp2);
}
});
});// <------ YOU'RE MISSING THIS
The requests should work fine. And since you're not posting any data to the URLs I might suggest that you use type:'GET'.
Maybe you want to use the $.when method http://api.jquery.com/jquery.when/
jQuery.when understanding
possibly put one in the callback of the other, I don't understand the problem off the top my head. But if div2 is inside div 1 or something you can control the order in that fashion

"this.source is not a function" error while implementing autocomplete

$(document).ready(function(){
var var_name=null;
$('#id1').click(function(){
$.ajax({
type:"GET",
url:" ggs.erm.servlet.setup5.Page",
success:function(response){
var_name=response;
console.log(response);
}
})
});
$("#id").autocomplete({source:var_name});
});
This is the Code I am messing with,It says TypeError:this.source is not a function. Where I am wrong,Correct me???
jQuery Ajax methods are non-blocking, so it looks like you're trying to set an auto-complete source before the previous method resolves. You probably want to move the autocomplete assignment into the success method of your .ajax() call.
So, instead of what you have, use:
$.ajax({
type: "GET",
url: "ggs.erm.servlet.setup5.Page",
success: function(response) {
$("#id").autocomplete({ source: response });
}
});

Search box in a jQuery ajax success page - issues in loop

Firstly, there have some tag links in my main page. click each one, post value to b.php with jquery.ajax and turn back value in div#result.
b.php have a search box. when search something in it. the result data will still show in the div#result.
my problem is: I know if I will do jQuery ajax in the b.php, I shall write the jQuery code in the first success part. but this only can control one time, when I continue search in the search box, the jQuery not work. I think I met a loop problem. How to solve it?
a.php
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.click').click(function(){
var value1 = $(this).text();
$.ajax({
url: "b.php",
dataType: "html",
type: 'POST',
data: "data=" + value1,
success: function(data){
$("#result").html(data);
$('#search').click(function(){
var value = $('#search1').val();
$.ajax({
url: "b.php",
dataType: "html",
type: 'POST',
data: "data=" + value,
success: function(data){
$("#result").html(data);
}
});
});
}
});
});
});
</script>
<a rel="aa" class="click">aa</a>
<a rel="aa" class="click">bb</a>
<div id="result"></div>
b.php
<?php
echo $_POST['data'];
?>
<form name="form">
<input type="text" value="" id="search1">
<a name="nfSearch" id="search">search</a>
</form>
When a new element is introduced to the page the jQuery .click() method becomes useless because it can only see elements that were part of the original DOM. What you need to use instead is the jQuery .live() method which allows you to bind events to elements that were created after the DOM was loaded. You can read more about how to use it at the below link.
.live() – jQuery API
$('#search').live('click', function(e) {
// Prevent the default action
e.preventDefault();
// Your code here....
});
First of all i think you should attach the ajax call to the click on the link: the way you are doing right now just execute an ajax call as soon as the page is loaded.
$(document).ready(function(){
//when you click a link call b.php
$('a.yourclass').click(function(){
$.ajax({
url: "b.php",
dataType: "html",
type: 'POST',
data: "data = something",
success: function(data){
$("#result").html(data);
var value = $('#search').val();
$.ajax({
url: "b.php",
dataType: "html",
type: 'POST',
data: "data =" + value,
success: function(data){
$("#result").html(data);
}
});
}
});
});
});
In this way, each time a link with the class of "yourclass" is clicked an ajax call to b.php is sent and if it succed, another call is made (always to b.php). I don't understand if this is what you are looking fo, if you post your html my answer can be better.
In b.php of course you need to echo some html that can be used in the callback
It's strange how your attempting to do two ajax requests like that, surely one is enough. If you need to support multiple text boxes then you just adjust your selectors.
Your whole code can be shortended down to something like this:
$(document).ready(function() {
$('#result').load('b.php', { data: $('#search').val() });
});
So if you wanted to search for the value when clicking on a link (for links within #container):
$('#container').delegate('a', 'click', function() {
// .text() will get what's inside the <a> tag
$('#result').load('b.php', { data: $(this).text() });
});

Categories