Refresh a table - javascript

I have read posts about this but I can't get the right answer.
I have tried Hide and Show to refresh a table:
$("#cmdUnreadID").click(function(){
$.ajax({
type: "GET",
url:"orderBy.php",
data: "unreadCtrl=1",
success:function(result){
$("#tableInbox").hide(500,function(){
$("#tableInbox").show();
});
}
});
});
this does not work for me. I tried other animations as well but nothing works. I think im missing something or I'm using the wrong way.
Any Suggestion how to Refresh the table only?

Where are you loading the result data to the UI. Probably you need to set the result to any of the element. use the html method to do that
success:function(result){
$("#tableInbox").hide(500,function(){
$("#tableInbox").html(result).show();
});
}

I think you want to change/update the content of the #tableInbox and to do that you can try this:
success:function(result){
$("#tableInbox").hide(500,function(){
$("#tableInbox").html(result).show();
});
}

Populate the table with the AJAX content
$("#cmdUnreadID").click(function(){
$.ajax({
type: "GET",
url:"orderBy.php",
data: "unreadCtrl=1",
success:function(result){
$("#tableInbox").hide(500,function(){
$("#tableInbox").html(result).show(); // <-- Notice html() call here, to populate the table
});
}
});
});

$("#cmdUnreadID").live('click', function () {
$("#tableInbox").hide(500);
$.ajax({
type: "GET",
url: "orderBy.php",
data: "unreadCtrl=1",
success: function (result) {
$("#tableInbox").html(result).show();
//Or
// $("#tableInbox").replaceWith(result).show();
}
});
});

i cant see on your code something that really changes the table,
you gota change the tables .htm() and feed the result like
$("#tableInbox").html(result)
note: you can also set dataType: to "html" or "xml" in your request, because if you receiving XML the result wont be suitable for direct feed to the table .html. jquery will do an inteligent guess from the datatype in servers response, but still it can be XML

Related

How to make an AJAX call to an html element?

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);
});
});

(this).parent().find not working for getting response in ajax call

$(".content-short").click(function() {
$(".content-full").empty();
var contentid=$(this).parent().find(".content-full").attr('data-id');
var content=$(this).parent().find(".content-full");
alert(contentid);
var collegename = $(this).attr('data-id');
$.ajax({
type: "post",
url: "contenthome.php",
data: 'collegename=' + collegename,
dataType: "text",
success: function(response) {
$content.html(response);
}
});
});
here the alert displays the specific data-id but
content=$(this).parent().find(".content-full");
this didn't displays data in content-full div with that specific data-id
anything wrong in the code or something else?
the query displays data if i use(."content-full"); instead of
$(this).parent().find(".content-full");
Inside the ajax callback you are using $content, but you declare your variable as content. May that be the problem?
Your question is not clear. What are you trying to achieve?

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.

Reading a file into a string in jQuery/JS

The title is quite self-explanatory: I need to read a HTML file through jQuery and store its contents into a string variable.
I tried using .load and $.get, but they wouldn't do what I needed.
This is the code I've tried so far, based on the comments below, but they didn't populate my template variable at all:
var template = "";
$.ajax({
url: 'includes/twig/image_box.twig',
type: 'get',
success: function(html) {
var twig = String(html);
template.concat(twig);
}
});
console.log(template);
AND:
var template = "";
var fileUrl = "includes/twig/image_box.twig";
jQuery.get(fileUrl).then(function(text, status, xhr){
var html = String(text);
template.concat(html);
// console.log(html); // WORKS!
});
console.log(template); // Does not work
It's weird why this isn't working. Weird for me at least. This is how I'd populate a variable in PHP so I've carried the same logic to JS. Maybe there is an alternative way?
P.S:V I've also tried all alternative ways, like concatenating with += and assigning inside the callback function to template with =, but nothing worked.
Thanks to the ones who are trying to help me!
Maybe you should try a AJAX request with $.ajax()
Check the jQuery API here
$.ajax({
url: 'yourHTMLfile.html',
type: 'get',
async: false,
success: function(html) {
console.log(html); // here you'll store the html in a string if you want
}
});
DEMO
EDIT: Added a demo!
I reread your question and I noticed you're calling the console log right above the ajax request but you forgot the ajax is asynchronous that means the page will do a request and only will set the template value when the response return with success(if it returns). So the console.log(template) don't appears because it may be not loaded yet.
var template = "";
$.ajax({
url: 'includes/twig/image_box.twig',
type: 'get',
success: function(html) {
var twig = String(html);
template.concat(twig);
console.log(template); // the change!
}
});
or
$.ajax({
url: 'includes/twig/image_box.twig',
type: 'get',
async: false,
success: function(html) {
var twig = String(html);
template.concat(twig);
}
});
console.log(template); // the change!
You can try this:
//as you see I have used this very page's url to test and you should replace it
var fileUrl = "/questions/20400076/reading-a-file-into-a-string-in-jquery-js";
jQuery.get(fileUrl).then(function(text, status, xhr){
//text argument is what you want
});
and if it won't work try if your browser can open the file. if it could you'd better try ajax method in jQuery if not you might have some problems regarding permissions or somethings like that in you application server.

JQuery/ajax page update help pls

Hi Am new to Jquery/ajax and need help with the final (I think) piece of code.
I have a draggable item (JQuery ui.draggable) that when placed in a drop zone updates a mysql table - that works, with this:
function addlist(param)
{
$.ajax({
type: "POST",
url: "ajax/addtocart.php",
data: 'img='+encodeURIComponent(param),
dataType: 'json',
beforeSend: function(x){$('#ajax-loader').css('visibility','visible');}
});
}
but what I cannot get it to do is "reload" another page/same page to display the updated results.
In simple terms I want to
Drag & drop
Update the database
Show loading gif
Display list from DB table with the updated post (i.e. from the drag & drop)
The are many ways of doing it. What I would probably do is have the PHP script output the content that needs to be displayed. This could be done either through JSON (which is basically data encoded in JavaScript syntax) or through raw HTML.
If you were to use raw HTML:
function addlist(param)
{
$.ajax(
{
type: 'POST',
url: 'ajax/addtocart.php',
data: 'img=' + encodeURIComponent(param),
dataType: 'html',
beforeSend: function()
{
$('#ajax-loader').css('visibility','visible');
},
success: function(data, status)
{
// Process the returned HTML and append it to some part of the page.
var elements = $(data);
$('#some-element').append(elements);
},
error: function()
{
// Handle errors here.
},
complete: function()
{
// Hide the loading GIF.
}
});
}
If using JSON, the process would essentially be the same, except you'd have to construct the new HTML elements yourself in the JavaScript (and the output from the PHP script would have to be encoded using json_encode, obviously). Your success callback might then look like this:
function(data, status)
{
// Get some properties from the JSON structure and build a list item.
var item = $('<li />');
$('<div id="div-1" />').text(data.foo).appendTo(item);
$('<div id="div-2" />').text(data.bar).appendTo(item);
// Append the item to some other element that already exists.
$('#some-element').append(item);
}
I don't know PHP but what you want is addtocart.php to give back some kind of response (echo?)
that you will take care of.
$.ajax({
type: "POST",
url: "ajax/addtocart.php",
data: 'img='+encodeURIComponent(param),
dataType: 'json',
beforeSend: function(x){$('#ajax-loader').css('visibility','visible');
success: function(response){ /* use the response to update your html*/} });

Categories