I am using jQuery DataTables with Ajax-sourced data and pagination. Each time when I click pagination link the same Ajax URL is called.
How can I send different offset to load records accordingly?
You can do that with ajax.data option.
For example, to send current page number as URL parameter use the code below:
var table = $('#example').DataTable({
"ajax": {
"url": "/getNextPageData",
"data": function(){
var api = $('#example').DataTable();
// Get paging information
var info = api.page.info();
// Update URL
// Send page number as a parameter
api.ajax.url(
"/getNextPageData/" + (info.page + 1)
);
}
}
});
Try this code for pagination:
function pagination(val)
{
var pageurl='yourPage.php';
event.preventDefault();
$.ajax({
type:'post',
url:pageurl+'?page='+val,
success: function(data){
$('.element').html(data);
}});
}
Define this function in your pagination in html like that
<a onclick='pagination("<?= $i ?>")' href='yourPage.php?page=".$i."'><?=$i?> </a>
Related
What i want to do is, to show a message based on certain condition.
So, i will read the database after a given time continuously, and accordingly, show the message to the user.
But i want the message, to be updated only on a part of the page(lets say a DIV).
Any help would be appreciated !
Thanks !
This is possible using setInterval() and jQuery.load()
The below example will refresh a div with ID result with the content of another file every 5 seconds:
setInterval(function(){
$('#result').load('test.html');
}, 5000);
You need a ajax solution if you want to load data from your database and show it on your currently loaded page without page loading.
<script type="text/javascript" language="javascript" src=" JQUERY LIBRARY FILE PATH"></script>
<script type="text/javascript" language="javascript">
var init;
$(document).ready(function(){
init = window.setInterval('call()',5000);// 5000 is milisecond
});
function call(){
$.ajax({
url:'your server file name',
type:'post',
dataType:'html',
success:function(msg){
$('div#xyz').html(msg);// #xyz id of your div in which you want place result
},
error:function(){
alert('Error in loading...');
}
});
}
</script>
You can use setInterval if you want to make the request for content periodically and update the contents of your DIV with the AJAX response e.g.
setInterval(makeRequestAndPopulateDiv, "5000"); // 5 seconds
The setInterval() method will continue calling the function until clearInterval() is called.
If you are using a JS library you can update the DIV very easily e.g. in Prototype you can use replace on your div e.g.
$('yourDiv').replace('your new content');
I'm not suggesting that my method is the best, but what I generally do to deal with dynamic stuff that needs access to the database is the following method :
1- A server-side script that gets a message according to a given context, let's call it "contextmsg.php".
<?php
$ctx = intval($_POST["ctx"]);
$msg = getMessageFromDatabase($ctx); // get the message according to $ctx number
echo $msg;
?>
2- in your client-side page, with jquery :
var DIV_ID = "div-message";
var INTERVAL_IN_SECONDS = 5;
setInterval(function() {
updateMessage(currentContext)
}, INTERVAL_IN_SECONDS*1000);
function updateMessage(ctx) {
_e(DIV_ID).innerHTML = getMessage(ctx);
}
function getMessage(ctx) {
var msg = null;
$.ajax({
type: "post",
url: "contextmsg.php",
data: {
"ctx": ctx
},
success: function(data) {
msg = data.responseText;
},
dataType: "json"
});
return msg;
}
function _e(id) {
return document.getElementById(id);
}
Hope this helps :)
I have created one application in that there is one text box for searching information from table. Although i have written the code when we enter the character in search text box, after accepting one character control goes out of textbox.
this is my code for searching`
<script type="text/javascript">
$(document).ready(function()
{
var minlength = 1;
$("#searchTerm").keyup(function () {
value = $(this).val();
if (value.length > minlength )
{
searchTable(value);
}
else if(value.length < minlength)
{
searchTable("");
}
});
});
function searchTable(value)
{
$.ajax({
type: "GET",
url: "dispatient.php",
data:({search_keyword: value}),
success: function(success)
{
window.location.href = "dispatient.php?search_keyword="+value;
$("#searchTerm").focus();
},
error: function()
{
alert("Error occured.please try again");
},
complete: function(complete)
{
$("#searchTerm").focus();
},
});
}
<input id="searchTerm" Type="text" class="search_box" placeholder="Search"
value = <?php echo $_GET['search_keyword'] ?> >
`
Please suggest to me..
thanks in advance..
value is default attribute of javascript try to change the variable name of value into something like searchData
In your success callback, you are redirecting the page to dispatient.php. I believe, this is the same page that has the search functionality. Once you redirect, the page is reloaded again and there is no point in writing:
$("#searchTerm").focus();
Since, you are already using AJAX, try loading the data from success on to your page through JavaScript/jQuery without reloading the page.
create one div and load your data in that instead of reloading entire page.
try something like this instead of ajax Call
<div id="searchResult"></div>
$("#searchResult").load("search.php?search_keyword=value",function(){
//your callback
});
I am implementing tags feature in my project.
In my demo tags i found they are passing names in a javascript function for the autocomple.
This is a function in my demo project,
<script>
$(function()
{
var sampleTags = ['c++', 'scala', 'groovy', 'haskell', 'perl', 'erlang', 'apl', 'cobol', 'go', 'lua'];
..................
.................
So , i want pass values from my php controller to this function ,inorder to get the autocomplete value from my database table
For example i am getting tags values from my db in my Controller like this:
` $data["query"] = $this->ordermodel->fetch_orderlist();`
$this->load->view('tagpage', $data); //loading my page tag page where above function exists
Now how can i pass that $data["query"] values into the above javascript function?
Please help
You could echo the variable onto the page using PHP's json_encode. This function will convert a PHP array or object into a JSON object, which JavaScript can work with:
<script>
$(function() {
var sampleTags = <?php echo json_encode($query); ?>;
})();
</script>
But a better way would be to request these values via Ajax. Say you have a PHP script named values.php:
<?php
#...
#assign $query here
#...
echo json_encode($query);
Then, in JavaScript (on the page where you want to use the sampleTags variable), you can use jQuery's .ajax function to make an easy Ajax request:
<script>
var sampleTags;
$.ajax({
url: 'values.php'
}).done(function(data) {
if (data) {
sampleTags = data;
}
});
</script>
I haven't tested this example. Obviously you'll want to tweak it to fit your environment.
You will have to write an ajax function for this
$.ajax(
url : "<?php echo site_url('controller/method')?>",
type : 'POST',
data : 'para=1',
success : function(data)
{
if(data){
var sampleTags = data;
}
}
);
Just echo your php variable
$(function()
{
var sampleTags = '<?php echo $data["query"]; ?>'
I am working on an application where I fetch data from database and process it using javascript/jquery like this:
$sqlEdit = "select revisionContent from tbl_revision where revisionId='".$_SESSION['contentId']."'"; //Query to fetch the result
$rsEdit = $dbObj->tep_db_query($sqlEdit);
$resEdit = $dbObj->getRecord($rsEdit);
$IdLessContent = $resEdit['revisionContent'];
<script language="javascript">
var getSavedContent = '<?php echo json_encode($IdLessContent); ?>';
var trimmedCont=($.trim(getSavedContent).slice(1));
//console.log(trimmedCont);
var lengthCont= trimmedCont.length;
var trimmedCont=$.trim(trimmedCont.slice(0,lengthCont-1));
console.log(trimmedCont);
var test = $('<div class="addId">');
test.append(trimmedCont);
//console.log(test.html());
test.children().each(function(index, value) {
$(this).attr('id', "com-"+randomString());
});
//console.log(test.html());
viewContent = test.html();
I get the required data in viewContent.I want to display it on the page in this section
<div id="mainWrap" onClick="fnDestroyEditable();">
<?php echo $resEdit['revisionContent']; ?> //THis is the unprocessed data displayed directly from database.I want to display the processed data here
</div>
I know we cannot get javascript variables to PHP as both are different (one server side and other client). But then how can I achieve this in my scenario?
EDIT I would like to add that the returned data is HTML stored in the database.So,I get the html->process it(add id attribute)->want to return back after processing
you can put the viewContent inside #mainWrap using javascript.
just make sure the DOM is loaded wrapping your js code with $(document).ready()
and add:
$('#mainWrap').html(viewContent);
at the end of your function.
$(document).ready(function () {
var getSavedContent = '<?php echo json_encode($IdLessContent); ?>';
var trimmedCont=($.trim(getSavedContent).slice(1));
//console.log(trimmedCont);
var lengthCont= trimmedCont.length;
var trimmedCont=$.trim(trimmedCont.slice(0,lengthCont-1));
console.log(trimmedCont);
var test = $('<div class="addId">');
test.append(trimmedCont);
//console.log(test.html());
test.children().each(function(index, value) {
$(this).attr('id', "com-"+randomString());
});
//console.log(test.html());
viewContent = test.html();
// put viewContent in the innerHtml of your wrapper
$('#mainWrap').html(viewContent);
});
if you need to send back info to the server you have to do it with ajax.
I added a javascript function addId() that will be invoked on click on one of the elements.
the new code is:
$(document).ready(function () {
var getSavedContent = '<?php echo json_encode($IdLessContent); ?>';
var trimmedCont=($.trim(getSavedContent).slice(1));
//console.log(trimmedCont);
var lengthCont= trimmedCont.length;
var trimmedCont=$.trim(trimmedCont.slice(0,lengthCont-1));
console.log(trimmedCont);
var test = $('<div class="addId">');
test.append(trimmedCont);
//console.log(test.html());
test.children().each(function(index, value) {
$(this).attr('id', "com-"+randomString());
});
//console.log(test.html());
viewContent = test.html();
// put viewContent in the innerHtml of your wrapper
$('#mainWrap').html(viewContent);
$('#mainWrap .addId').children().click(function({
addId(this);
}));
}
addId = function(elem){
// elem is the child element you clicked on
// $(elem).attr('id') should be "com-[randomString]"
$.ajax({
type: "POST",
url: "path/to/php/script", // update id PHP script
data: data, // whatever you need in json format
dataType: "json",
error: function() {
// error function you want to implement
errorFunction();
},
success: function(resp) {
// do whatever you need with the response from you PHP action
}
});
};
if you need to to call server with out human interaction just substitute
$('#mainWrap .addId').children().click(function({
addId(this);
}));
with:
$('#mainWrap .addId').children().each(function({
addId(this);
}));
if I undesrstand you, you shold only add in the end of your js code this line:
$('#mainWrap').html(viewContent);
If you want to send JS data to PHP, you should use ajax request.
I have a link that looks like this:
<p class="half_text">
<?php echo $upvotes; ?>
<strong><a class="vote_up" style="color: #295B7B; font-weight:bold;" href="#">Vote Up</a></strong> |
<?php echo $downvotes; ?>
<strong><a class="vote_down" style="color: #295B7B; font-weight:bold;" href="#">Vote Down</a></strong>
</p>
and I have the jQuery code that looks like this:
<script type="text/javascript">
$(document).ready(function()
{
$('.vote_up').click(function()
{
alert("up");
alert ( "test: " + $(this).attr("problem_id") );
// $(this).attr("data-problemID").
$.ajax({
type: "POST",
url: "/problems/vote.php",
dataType: "json",
data: dataString,
success: function(json)
{
// ? :)
}
});
//Return false to prevent page navigation
return false;
});
$('.vote_down').click(function()
{
alert("down");
//Return false to prevent page navigation
return false;
});
});
</script>
How can I get the parameter value which is problem_id ? If I add a url in the href parameter, I think the browser will just go to the url, no? Otherwise - how can I pack parameter values into the jQuery?
Thanks!
Because your $.ajax is defined in the same scope of the variable, you can use problem_id to obtain the variable value.
An overview of your current code:
var problem_id = "something"; //Defining problem_id
...
$.ajax(
...
success: function(){
...
//problem_id can also be accessed from here, because it has previously been
// defined in the same scope
...
}, ...)
....
If what you're trying to figure out is how to embed the problem ID in the link from your PHP so that you can fetch it when the link it clicked on, then you can put it a couple different places. You can put an href on the link and fetch the problem ID from the href. If you just do a return(false) from your click handler, then the link will not be followed upon click.
You can also put it as a custom attribute on the link tag like this:
<a class="vote_up" data-problemID="12" style="color: #295B7B; font-weight:bold;" href="#">Vote Up</a>
And, then in your jQuery click handler, you can retrieve it with this:
$(this).attr("data-problemID").
do you mean, getting variables from the php page posted?
or to post?
anyway here's a snippet to replace the $.ajax
$.post('/problems/vote.php', {problem_id: problem_id, action: 'up'}, function(data) {
// data here is json, from the php page try logging or..
// console.log(data);
// alert(data.title);
}, 'json');
{problem_id: problem_id, action: 'up'} are the variables posted... use $_POST['problem_id'] and $_POST['action'] to process..
use simple variables names with jQuery.data and make sure you have latest jQuery..
let me try to round it up..
up
down
<script type="text/javascript">
$('.votelink').click(function() {
$.post('/problems/vote.php', {problem_id: $(this).data('problemid'), action: $(this).data('action')}, function(data) {
// data here is json, from the php page try logging or..
// console.log(data);
// alert(data.title);
}, 'json');
});
</script>