I want to load more than 10 rows from my table with jQuery, but it's not working.
My php code: (...chat.php?load=archive)
} else if (isset($_GET["load"]) && $_GET["load"] == "archive") {
echo "<script type='text/javascript' src='includes/js/chatArchive.js'></script>";
$limit = (int)$_POST["limit"];
$result = mysql_query("SELECT * FROM `chat` ORDER BY `date` DESC LIMIT ".$limit.", 2");
if (mysql_num_rows($result)) {
while($db = mysql_fetch_array($result)) {
echo "..."; // My datas...
}
echo "<div style='text-align: center; margin: 10px 0 10px 0;'>\n";
echo "<input type='submit' value='Load more rows' class='loadMore'>\n";
echo "</div>\n";
}
}
My JS file: (chatArchive.js)
var limit = 50;
$(document).ready(function() {
$(".loadMore").click(function() {
limit += 10;
$.ajax({
url: "../../../system/functions/chat.php?load=archive",
type: "POST",
data: { "limit" : limit },
success: function() {
alert("Success...");
console.log(limit); // This displayed my console!!!
}
});
});
});
Can anyone point out the problem?
Function which is defined as a callback for success property has an argument, usually called data, which is the returned value from your script. So, you should change your success function as follows:
success: function(data) { // see data here
alert("Success...");
console.log(limit); // This displayed my console!!!
console.log( data ); // check what data contains
}
Also it's a good practice to add error callback, which will indicate that something bad happens:
$.ajax({
url: "../../../system/functions/chat.php?load=archive",
....
error: function() {
alert("Bad thing happenned!");
}
)};
your ajax method is POST but in your php script you check GET request
if (isset($_GET["load"]) && $_GET["load"] == "archive")
Change Your ajax method to GET
Related
so I have this table with contenteditable divs, when a user inputs something in a div they have to click a button that collects all the content of the divs and stores them into Var OBJ.
document.getElementById("done_editing").addEventListener("click", get_values);
var OBJ = [];
function get_values() {
let divobj = document.querySelectorAll('[contenteditable=true]')
for (var i = 0; i < divobj.length; i++) {
OBJ.push(divobj[i].textContent)
//console.log(OBJ)
}
OBJ = OBJ.filter(item => item)
console.log(OBJ)
I want to send the values inside of var OBJ to a Database. I cant Wrap my head around on how to do this . It is not your average form so I guess I have to use ajax but I have no experience with ajax. this is what i Have for ajax.
$.ajax({
type: "POST",
url: "test.php",
data: { arraykey: OBJ },
success: function (response) {
alert('succes')
// You will get response from your PHP page (what you echo or print)
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
})
}
Anyone can point me in the right direction on how to use ajax and how to configure the php file ?
php file :
//Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$data = isset($_POST['arraykey']);
if ($data)
{
$array = $_POST["arraykey"];
echo $array;
echo " is your array";
}
else
{
$array = null;
echo "no array supplied";
}
/*$data = isset($_POST['OBJ']);
print_r($_POST);
*/
// close connection
mysqli_close($link);
?>
the var_dump($_POST); returns a array(0) { }
update: ajax seems to succeed but no array is passed to php.
Thanks in advance !
As there are multiple divs you can use array to add mutliple values to it and send the same to ajax.
Demo Code :
document.getElementById("done_editing").addEventListener("click", get_values);
var OBJ = [];
function get_values() {
let divobj = document.querySelectorAll('[contenteditable=true]')
for (var i = 0; i < divobj.length; i++) {
OBJ.push(divobj[i].textContent); //add in array
}
console.log(OBJ)
//your ajax call
$.ajax({
type: 'POST',
url: 'test.php',
data: {
OBJ: OBJ //pass array to php
},
success: function(data) {
alert("something");
}
});
}
div {
border: 1px solid;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div contentEditable="true"></div>
<div contentEditable="true"></div>
<div contentEditable="true"></div>
<div contentEditable="true"></div>
<button id="done_editing">Done</button>
Your php will look like below :
<?php
// You should call this first
session_start();
$data = isset($_POST['arraykey']);
if ($data)
{
$_SESSION['arraykey'] = $_POST["arraykey"];//putting aray value in session
echo $_SESSION['arraykey'];
echo " is your array";
}
else
{
echo "no array supplied";
}
?>
I have a function that populates the DataTable when the document is ready.
$(document).ready(function()
{
var $dataTable = $('#example1').DataTable({
"ajax": 'api/qnams_all.php',
"dataType": "json",
"bDestroy": true,
"stateSave": true
});
// this portion reloads the datatable without refreshing the page
setInterval(function() {
$dataTable.ajax.reload();
}, 60000);
}
So now I want to add a search feature. It would basically re-populate the DataTable with the search data returned from the server.
Directly below is the jQuery that retrieves the parameters entered by the user:
$('#searchSubmit').on('click', function()
{
var searchbooking = $('#searchbooking').val();
var searchquote = $('#searchquote').val();
$.ajax({
url:'api/qnams_all.php',
type:"POST",
data:{searchbooking: searchbooking, searchquote: searchquote},
contentType:"application/x-www-form-urlencoded; charset=UTF-8",
dataType:"json"
}).done(function(response){
console.log(response.data)
}).fail(function(){
alert('error');
}).always(function(){
alert('done');
});
});
Here is the PHP process found in api/qnams_all.php:
<?php
include("../include/database.php");
include("../include/sessions.php");
$_SESSION['where'] = "";
$searchbooking = strip_tags(mysqli_real_escape_string($dbc, trim(strtoupper($_POST['searchbooking']))));
$searchquote = strip_tags(mysqli_real_escape_string($dbc, trim(strtoupper($_POST['searchquote']))));
// build the WHERE clause
if($searchbooking != ""){
$_SESSION['where'] = "booking = '".$searchbooking."'";
}
if($searchquote != ""){
if( $_SESSION['where'] != "" )
$_SESSION['where'] .= " AND ";$_SESSION['where'] .= "quote = '".$searchquote."'";
}
// check if WHERE is blank
if($_SESSION['where'] == ""){$where = "where TLI_COMPLETE = 'N'";}
else{$where = $_SESSION['where'];}
// run the query
$select = "SELECT
CONCAT('\"',COALESCE(booking,''),'\"')
,CONCAT('\"',COALESCE(quote,''),'\"')
FROM
searchTable " . $where . "";
$query = mysqli_query($dbc, $select) or die(mysqli_error());
$resnum = mysqli_num_rows($query);
echo "{\"data\":[";
$i = 1;
while($row = $query->fetch_assoc())
{
echo "[";
echo implode(', ', $row);
echo "]";
if($i < $resnum){
echo ",";
}
$i++;
}
}
echo "]}";
mysqli_free_result($query);
?>
The PHP process above works perfectly with the $(document).ready() function.
My question is: how can I manipulate my code so that the search functions works with the ready() function?
Right now, the search function is located outside of the ready() function. Can I apply the search function within the ready() function? If so, how would the AJAX call look like?
Currently, it reads:
"ajax": 'api/qnams_all.php'
If I am able to add the search to the ready() function, would this AJAX call change?
To put it in one question, how can I add the search feature to the ready() function so that I can initially display data, and then repopulate the data if the user decides to search for a record?
You have to keep 2 copies of the same code(ajax part)
In document.ready with async:false in ajax call.(Will load the search results when the page opens).
The original place where it is now i.e inside the onClick function.(For the default behaviour).
That's because you need to wrap your ajax call in an eventListener and here you are having to separate events.
I am using AJAX to loadmore data from an image gallery.
I pass PHP variable to set the $page number and other data. Each time I loadmore data from AJAX, I would like the $page to increase by 1 so next time, it gets the next data on the list. Here is my JS
$(window).bind('scroll', function() {
if($(window).scrollTop() >= $('#postswrapper').offset().top + $('#postswrapper').outerHeight() - window.innerHeight) {
$('div#loadmoreajaxloader').show();
$.ajax
({
url: "loadmore.php",
method: "get",
data: { page: "<?=$page?>", perpage: "<?=$perpage?>"},
success: function(html)
{
if(html)
{
$("#postswrapper").append(html);
$('div#loadmoreajaxloader').hide();
// ###### THIS IS NOT WORKING
<? $page++; ?>
}
else
{
$('div#loadmoreajaxloader').html('<center>No more posts to show.</center>');
}
}
}); // close AJAX
} // close if()
}); // close $(window)
I tried incorporating <? $page++; ?> in the success function, but it's not working.
I USE THE $page variable inside my SQL query
HERE IS MY loadmore.php CODE
if (isset($_GET['page']))
{
$page = $_GET['page'];
$perpage = $_GET['perpage'];
$start = ($page -1) * $perpage ;
$sql = mysql_query("select * from ..... limit ".$start.", ".$perpage." ");
$html = '';
while($blog2 = mysql_fetch_array($sql))
{
$html .='HTML GOES HERE';
}
echo $html;
exit;
}
What I'm trying to achieve is to load the SQL query starting from the next page every time I load more data... Any suggestions on how I should proceed?
First, remember to sanitize any user input in your PHP file to prevent sql injection:
$page = $_GET['page'];
$perpage = $_GET['perpage'];
// escape the values, or make sure they are numbers, e.g.:
if(!is_numeric($page))
$page = 0;
if(!is_numeric($perpage))
$perpage = 10; // or whatever default value
And write your PHP values into Javascript variables and use those in your js code:
var pageNumber = <?= $page ?>;
var perPage = <?= $perpage ?>;
$(window).bind('scroll', function() {
if($(window).scrollTop() >= $('#postswrapper').offset().top + $('#postswrapper').outerHeight() - window.innerHeight) {
$('div#loadmoreajaxloader').show();
$.ajax
({
url: "loadmore.php",
method: "get",
data: { page: pageNumber, perpage: perPage},
success: function(html)
{
if(html)
{
$("#postswrapper").append(html);
$('div#loadmoreajaxloader').hide();
// use the js variable
pageNumber++;
}
else
{
$('div#loadmoreajaxloader').html('<center>No more posts to show.</center>');
}
}
}); // close AJAX
} // close if()
}); // close $(window)
No
PHP runs server-side, the AJAX runs client side. You need a javascript variable there (although you can set its initial value with PHP).
I am trying to change text in a div depending on value change on a dropdown box. The dropdown box values are populated from MySQL using PHP. I am loading the dropdown box on page load.
<script>
$(document).ready(function() {
$('#products').change(function(){
var idval=$('#products').val();
$.ajax
( {
type: "post",
url: "my.php",
data: {winner_id:idval},
success: function(response)
{ alert("The winner was passed!")},
}
);
<?php
require_once 'config.php';
$iid=$_GET['winner_id'];
$sql="SELECT * FROM Products where prod_id = ".$iid;
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
$prodCredit="Credit :".$row["prod_price"];
$time="estmated time is :".$row["prod_time"];
?>
$('#esdTime').text(' <?php echo $prodCredit ?> ' );
$('#credit').text(' <?php echo $time ?> ' );
});
});
</script>
I am not getting results.
Let me know how can I assign JavaScript value idval to PHP variable $iid value.
//you would want a the php script to be in a separate file that you could call Have the php file return an array or json object. Have the callback success function append the new options to the html select. The following is a ruffexample
<script>
$(document).ready(function() {
$('#products').change(function(){
var idval=$('#products').val();
$.ajax
( {
type: "post",
url: "my.php",
data: {winner_id:idval},
success: function(response){
for (var i = 0; i < response.length; i++) {
$("#idofyourselect").append("<option val='" +response[i]+"'>" + response[i] + "</option>");
}
},
}
);
</script>
I have a table in which the details are fetched from the DB.
if(mysql_num_rows($sql) > 0)
{
$row_count_n=1;
while($rows=mysql_fetch_assoc($sql))
{
extract($rows);
$options1 = select_data_as_options("project_resources", "name", $resource_allocated);
$options2 = select_data_as_options("project_roles", "name", $role);
echo "<tr>";
echo "<td><select name='ra_$row_count_n'><option value=''>-- Select --$options1</option></select></td>";
echo "<td><select name='role_$row_count_n'><option value=''>-- Select --$options2</option></select></td>";
echo "<td><input type='text' name='start_date_tentative_$row_count_n' class='date_one' value=$tentatively_starts_on /></td>";
echo "</tr>";
$row_count_n++;
}
}
I wanted to update the table when required, am doing this using Ajax by collecting data from the form using Jquery and saving it on button click.
$("#save_changes_id").click(function()
{
// To retrieve the current TAB and assign it to a variable ...
var curTab = $('.ui-tabs-active'); // in NEWER jQueryUI, this is now ui-tabs-active
var curTabPanelId = curTab.find("a").attr("href");
if(curTabPanelId == "#tab_dia")
{
var curTab = $('#sub_tabs .ui-tabs-active');
var curTabPanelId = curTab.find("a").attr("href");
}
responseData = doAjaxCall($(curTabPanelId + " form"));
if(responseData == 1)
showMessage('status_msg', 'Project details updated successfully', 'green');
else
showMessage('status_msg', 'Error: Please check all the fields', 'red');
});
function doAjaxCall(objForm)
{
var values = objForm.serialize();
$.ajax({
url: ajaxURL,
type: "post",
data: values,
async: false,
success: function(data)
{
responseData = data;
},
error:function()
{
alert('Connection error. Please contact administrator. Thanks.');
}
});
return responseData;
}
Ajax code is as below:
case "allocate_ba_details":
for($i=1; $i<=$row_count; $i++)
{
$resource = $_REQUEST["ra_$i"];
$role = $_REQUEST["role_$i"];
$start_date_tentative = $_REQUEST["start_date_tentative_$i"];
$already_available_check = mysql_num_rows(mysql_query("select * from project_allocate_ba where project_id = $pdid"));
if($already_available_check > 0)
{
$sql = ("UPDATE project_allocate_ba SET resource_allocated='$resource', role='$role', tentatively_starts_on='$start_date_tentative' WHERE project_id=$pdid");
}
}
echo $sql;
break;
As I am new to this am not sure how to pass the row name in order to update a particular row.
Please suggest a solution. Thanks in advance.
firstly use PDO or some php framework that has nice API to work with mysql. Second don't use success/error callback in jquery is too deprecated. Instanted use done/fail.always.
I understand that you want update row in html table data from the server ?
In success callback simply update the table using jquery text method for jquery object. You don't paste all code so i write example:
in server.php
<?php
[...]
$already_available_check = mysql_num_rows(mysql_query("select * from project_allocate_ba where project_id =" . intval($pdid)));
[...]
echo $already_available_check;
?>
This code return the integer, so in doAjaxCall:
function doAjaxCall(objForm)
{
var values = objForm.serialize();
$.ajax({
url: ajaxURL,
type: "post",
data: values,
async: false,
success: function(data)
{
if(typeof data !== 'undefined' && $.isNumeric(data)) {//check that server send correct anserw
$('whereIsData').text(data);
}
},
error:function()
{
alert('Connection error. Please contact administrator. Thanks.');
}
});
}
Now in success method you populate some DOM element using text method. You cannot simply return data from ajaxCall method because $.ajax is asynchronized method and responseData has value only when ajax request ends, so always return undefined in you example. You must present responseData to the user in success callback method.
For one thing...
$sql = ("UPDATE project_allocate_ba SET resource_allocated='$resource', role='$role', tentatively_starts_on='$start_date_tentative' WHERE project_id=$pdid")
needs single quotes around $pdid
Also don't echo the $sql. Instead do your inspection and form a response.
$response = array();
if(EVERYTHING_IS_GOOD){
$response['status'] = 'good to go';
}else{
$response['status'] = 'it went horribly wrong';
}
echo json_encode($response);