apply datatables.js style to table loaded by ajax - javascript

$(document).on('click', '.manage', function (event)
{
var userid = $(this).data('userid');
$.ajax(
{
type: "POST",
dataType:'html',
url:"../user/ajax/doclist.php",
async:true,
data:{userid:userid,task:'view'},
success:function(html)
{
$('.doclistdiv').html(html);
},
error:function(request,errorType,errorMessage)
{
alert ('error - '+errorType+'with message - '+errorMessage);
},
complete:function(html)
{
}
});
});
as above code shown i'm loading ajax data(as a html) to my page.
in among those data i have table.i want to after loading that table convert to table as table in datatable.js(www.datatables.net/)
i think because data come as a html there server side processing is not working

Try the following in your success section:
var root = $('.doclistdiv');
root.html(html);
root.find('table').dataTable();

Related

Why can't I toss post variable to PHP when I cover .ajax with function?

I have 3 files for showing data from myAdmin and it shows no error but after I put function around .ajax, to re-use it, I cannot pass button id to PHP. " Undefined index: btnId"
What seems wrong?
HTML file, written in PHP (below looped in for code)
print"<button class='refresh' data-name='$btnId' id='$btnId'>{$btnId}</button>";
print "<table id='$idForShowNewData' class='showNewData'></table>";
show.js
$(document).ready(function(){
$('.refresh').click(function(){
$(function showTable() {
    $.ajax({
url: "show.php",
type: "POST",
data: {
"btnId": $(this).data("name")
},
success: function(data) {
//more code
},
error: function(xhr,XMLHttpRequest,errorThrown){
//more code
}
});
});
showTable();
});
});
PHP file that get's data from myAdmin. Getting id like below is at the top of the script.
$gotBtnId = $_POST['btnId'];
this in showTable refers to window object and not the button whose data-name you want to send in the request.
If you want showTable to be invoked when the page is loaded and also be registered as a listener for click events to the refresh button, declare it as follows:
const $refreshBtn = $('button.refresh');
function showTable() {
    $.ajax({
url: "show.php",
type: "POST",
data: {
"btnId": $refreshBtn.data("name")
},
success: function(data) {
//more code
},
error: function(xhr,XMLHttpRequest,errorThrown){
//more code
}
});
});
$(function() {
showTable();
$refreshBtn.click(showTable);
});

AJAX post method working in one area but not another

I have an AJAX post method that works in two places both on "Ladder" page, but not another, a "matches" page. This method sets posts the "player ID" which php picks up and sets a session variable
$("form .singles-player-name").click(function (evt) {
evt.preventDefault();
var viewPlayer = $(this).val();
console.log(viewPlayer);
$.ajax({
url: '',
type: 'POST',
data: {
viewPlayerID: viewPlayer
}
}).done(function (data) {
console.log("Success");
//console.log(data);
window.location.href = "Player";
});
});
Working page form:
<form><button type='submit' id='playerInfo' class='singles-player-name' name='viewPlayer' value='",$sglsPlayerID,"'>", $curSGLSRankLName, ", ", $curSGLSRankFName, "</button></form>
Sets session variable
if (!empty($_POST['viewPlayerID'])){
$viewPlayer = isset($_POST['viewPlayerID']) ? $_POST['viewPlayerID'] : 'No data found';
$viewPlayerSql = "SELECT * FROM `PLAYERS` WHERE `ID` LIKE '".$viewPlayer."'";
$viewPlayerQuery = #$conn->query($viewPlayerSql);
$viewPlayerRow=mysqli_fetch_assoc($viewPlayerQuery);
$_SESSION['playerID'] = $viewPlayerRow["ID"];
echo "", $_SESSION['playerID'],"";}
Second working version that lives on the same page as the first but is for doubles players:
$("form .doubles-player-name").click(function (evt) {
evt.preventDefault();
var viewPlayer = $(this).val();
console.log(viewPlayer);
$.ajax({
url: '',
type: 'POST',
data: {
viewPlayerID: viewPlayer
}
}).done(function (data) {
console.log("Success");
//console.log(data);
window.location.href = "Player";
});
});
Form for that ajax method:
<form><button type='submit' id='playerInfo' class='doubles-player-name' name='viewPlayer' value='",$dblsPlayerID,"'>", $curDBLSRankLName, ", ", $curDBLSRankFName, "</button></form>
Then on complete, the ajax methods redirect to the player page and pulls up that players info on that page (ex. https://urlexample.com/Player). This part, from this point-up, works! However, I have another page, the "Matches" page, where I want it to do the same exact thing, and set that session variable, then redirect to the player page, so I have this method below. But for some reason, this one does not work:
$("form .singlesMatch-player1-name").click(function (evt) {
evt.preventDefault();
var viewPlayer = $(this).val();
console.log(viewPlayer);
$.ajax({
url: '',
type: 'POST',
data: {
viewPlayerID: viewPlayer
}
}).done(function (data) {
console.log("Success");
console.log(data);
window.location.href = "Player";
});
});
Not working form:
<form><button type='submit' id='playerInfo' class='singlesMatch-player1-name' name='viewPlayer' value='",$sglsPlayer1ID,"'>", $P1LN, ", ", $P1FN, "</button></form>
For some reason, all this second method does is post it to the URL (ex. https://urlexample.com/WeeklyMatchUps?viewPlayer=1) instead of setting the session variable and redirecting to the player page (ex. https://urlexample.com/Player). All thats different between the 2 is the class name of the button.
$sglsPlayer1ID should probably be $sglsPlayerID.
Also, try adding a success and error condition to your AJAX conditions instead of just using a done operator. This will allow you to dump helpful error codes on a failure to better resolve these kinds of issues in the future.
I had a function being called on the page that was commented out causing an error before jQuery was added in a script at the bottom of the page. removing that function from being called fixed the issue.
S/O to #line88 for the assistance!

Wordpress do shortcode using ajax

I'm trying to do shortcode by ajax, i'm getting page content using ajax , and shortcode's added to content are displaying like plain text. I was searching for solution but there's nothing that's help me solve this problem.
For example i have metaslider shortcode in content, and i want to display it on several pages. The main problem is that there will be diffrent slider on every page, so i need load sliders depends on their ID.
get page content method:
ajax_get_post: function(postid) {
var loader = $('#pop-single .loader');
loader.show();
var data = {
'action': 'get_single_post',
'post_id': postid
};
$.ajax({
type: 'POST',
url: ajaxurl,
data: data,
success: function(data) {
var content = $('#pop-single .popup');
loader.hide();
content.show();
//console.log(data);
var post = JSON.parse(data),
title = post.post_title,
content = post.post_content;
$('#pop-single h1.title').html(title);
$('#pop-single .content-ajax').html(content);
},
error: function(data) {
alert('nope');
}
});
},
get post php - functions.php
add_action('wp_ajax_get_single_post', 'ajax_get_single_post');
add_action('wp_ajax_nopriv_get_single_post', 'ajax_get_single_post');
function ajax_get_single_post() {
if (!empty($_POST['post_id'])) {
$id = $_POST['post_id'];
$post = get_page($id);
echo json_encode($post);
}
die();
}
Now in same way i want to display any shortode added to content, or maybe there's other way, but it should be done dynamically, that's why im using ajax.
Thank's in advice for any help or example how to do that.

How can i get data from mysql?

I'm trying to make some data in my database editable by using "X-editable" Bootstrap plugin. What should my code look like? I need the anchor text to be pre-filled with data. This is what I have.
Html:
JS:
$(document).ready(function() {
//toggle `popup` / `inline` mode
$.fn.editable.defaults.mode = 'popup';
//make username editable
$('#objekt_alias').editable();
/*
//uncomment these lines to send data on server
,pk: 1
,url: '/post'
*/
});
Take a look at the jQuery website (linked by Arpit Srivastava below your post) and implement an ajax request like this :
function doAjaxRequest(id){
$.ajax({
url: "'/post'",
data: { pk: id }, //complete this object to pass your data
}).done(function() {
alert('request done !');
});
}

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