Page Scrolling Effect With Ajax How Data Is Loaded Into The Page - javascript

I am loading data from a mysql table into a html table. I am using AJAX php Jquery to accomplish this. I need to make sure that the way I built this will work regardless of how much data is in the table.
Right now I am working with a table that is 5000 rows long but there will eventually be 88000 rows in this table.
I know if I load all the data on page load this could end up bogging down the server and the load time of the page.
My question is the way my logic is now will it load all the results into the $results and only query the needed amount of rows because it is paginated. Or even though it is paginated is my webpage taking every row in the whole database for load time.
if the whole table is being loaded how can I change the query to only load the data when needed. It loads on page scroll.
Also I need to write a search function. Since the data is paginated would I search the data in $results or query the table with separate search functions? Which way would provide less load times which would cause a bad experience for my user?
The AjAX
<script type="text/javascript">
jQuery(document).ready(function($) {
var busy = true;
var limit = 5;
var offset = 0;
var assetPath = "<?php echo $assetPath ?>"
function displayRecords(lim, off) {
jQuery.ajax({
type: "GET",
async: false,
url: assetPath,
data: "limit=" + lim + "&offset=" + off,
cache: false,
beforeSend: function() {
$("#loader_message").html("").hide();
$('#loader_image').show();
},
success: function(html) {
$("#productResults").append(html);
$('#loader_image').hide();
if (html == "") {
$("#loader_message").html('<button data-atr="nodata" class="btn btn-default" type="button">No more records.</button>').show()
} else {
$("#loader_message").html('Loading... Please wait <img src="http://www.wuno.com/monstroid/wp-content/uploads/2016/02/LoaderIcon.gif" alt="Loading">').show();
}
window.busy = false;
}
});
}
(function($) {
$(document).ready(function() {
if (busy == true) {
displayRecords(limit, offset);
busy = false;
}
});
})( jQuery );
(function($) {
$(document).ready(function() {
$(window).scroll(function() {
// make sure u give the container id of the data to be loaded in.
if ($(window).scrollTop() + $(window).height() > $("#productResults").height() && !busy) {
offset = limit + offset;
displayRecords(limit, offset);
}
});
});
})( jQuery );
});
</script>
This is how I am querying the database
$limit = (intval($_GET['limit']) != 0 ) ? $_GET['limit'] : 5;
$offset = (intval($_GET['offset']) != 0 ) ? $_GET['offset'] : 0;
$sql = "SELECT * FROM wuno_inventory WHERE 1 ORDER BY id ASC LIMIT $limit OFFSET $offset";
try {
$stmt = $DB_con->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll();
} catch (Exception $ex) {
echo $ex->getMessage();
}
if (count($results) > 0) {
foreach ($results as $res) {
echo '<tr class="invent">';
echo '<td>' . $res['wuno_product'] . '</td>';
echo '<td>' . $res['wuno_alternates'] . '</td>';
echo '<td>' . $res['wuno_description'] . '</td>';
echo '<td>' . $res['wuno_onhand'] . '</td>';
echo '<td>' . $res['wuno_condition'] . '</td>';
echo '</tr>';
}
}

By transferring a JSON object from the server the limit, offset and html (and maybe others lime status_messsage, etc.) values could be transferred to the client at the same time.
On the client side I meant something like this:
var limit = 5;
var offset = 0;
var assetPath = "<?php echo $assetPath ?>"
function displayRecords(lim, off) {
jQuery.ajax({
type: "GET",
async: false,
url: assetPath,
dataType: "json", // We expect to receive a json object
data: "limit=" + lim + "&offset=" + off,
cache: false,
beforeSend: function() {
$("#loader_message").html("").hide();
$('#loader_image').show();
},
success: function(json) {
limit = json.lim; // corr to $output['lim']
offset = json.offs; // corr to $output['offs']
$("#productResults").append(json.html); // corr to $output['html']
$('#loader_image').hide();
if (json.html == "") {
$("#loader_message").html('<button data-atr="nodata" class="btn btn-default" type="button">No more records.</button>').show()
} else {
$("#loader_message").html('Loading... Please wait <img src="http://www.wuno.com/monstroid/wp-content/uploads/2016/02/LoaderIcon.gif" alt="Loading">').show();
}
window.busy = false;
}
});
}
...and on the server side:
$limit = (intval($_REQUEST['limit']) != 0 ) ? $_REQUEST['limit'] : 5;
$offset = (intval($_REQUEST['offset']) != 0 ) ? $_REQUEST['offset'] : 0;
$sql = "SELECT * FROM wuno_inventory WHERE 1 ORDER BY id ASC LIMIT $limit OFFSET $offset";
// Make sure to handle invalid offset values properly,
// as they are not validated from the last request.
// Prepare the $output structure (will become a json object string)
$output = array(
'lim'=>$limit,
'offs'=>$offset+$limit,
'html'=>''
);
try {
$stmt = $DB_con->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll();
} catch (Exception $ex) {
$output['html'] .= $ex->getMessage();
}
if (count($results) > 0) {
foreach ($results as $res) {
$output['html'] .= '<tr class="invent">';
$output['html'] .= '<td>' . $res['wuno_product'] . '</td>';
$output['html'] .= '<td>' . $res['wuno_alternates'] . '</td>';
$output['html'] .= '<td>' . $res['wuno_description'] . '</td>';
$output['html'] .= '<td>' . $res['wuno_onhand'] . '</td>';
$output['html'] .= '<td>' . $res['wuno_condition'] . '</td>';
$output['html'] .= '</tr>';
}
}
// Now encode $output as a json object (string) and send it to the client
header('Content-type: application/json; charset=utf-8');
echo json_encode($output, JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_FORCE_OBJECT);

I do this exact thing you want on my site http://www.flixnetforme.com/ where as you can see as you scroll to the bottom of the page the next set of records is loaded. I have over 150,000 records but it only loads 36 at a time when the user scrolls to the bottom of the page.
The way you want to do this is is by loading your first initial records through ajax and not hardcode them into the page.
index.php
$(document).ready(function(){
var last_id;
if (last_id === undefined) {
genres = $("#genres").val();
$.ajax({
type: "POST",
url: "includes/getmorefirst.php?",
data: "genres="+ genres,
success: function(data) {
$( ".append" ).append(data);
}
});
};
};
<html><div class="append"></div></html>
In this example when the user gets to the page and is loaded it calls getmorefirst.php and return the first records.
getmorefirst.php is a file that will load the first set amount of records you want to show when the user gets to the page. In my case I load 36 records at a time when a user scrolls to the bottom of my page.
getmorefirst.php
$sql = "SELECT * FROM table ORDER BY ID ASC LIMIT 36"
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
$last_id = $row['ID'];
echo '<div>'.$row['column'].'</div>';
echo '<div style="display:none" class="last_id" id="'.$last_id.'"';
}
The last_id div is important so that ajax will know the last record sent and which one to pick up after when it loads the next set of 36 records.
.append is the div where I am appending the data from ajax when the user its the bottom.
.last_id is your key to knowing how to load the next set of records. In whatever order you send the records back its important that ajax knows the last ID of the record loaded so it knows where to start loading the next time ajax calls for more records. In my case when the users scrolls to the bottom of the page.
when user scrolls to bottom of index.php
if($(window).scrollTop() === $(document).height() - $(window).height()) {
last_id = $(".last_id:last").attr("id");
$.ajax({
type: "POST",
url: "includes/getmore.php?",
data: "last_id="+ last_id,
success: function(data) {
$( ".append" ).append(data);
}
});
return false;
};
};
last_id = $(".last_id:last").attr("id"); will get the last ID sent.
data: "last_id="+ last_id, will send the last id to getmore.php so it knows the last id of the record sent.
getmore.php
$sql = "SELECT * FROM table WHERE ID > '$last_id' ORDER BY ID ASC LIMIT 36"
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
$last_id = $row['ID'];
echo '<div>'.$row['column'].'</div>';
echo '<div style="display:none" class="last_id" id="'.$last_id.'"';
}
As you can see getmore.php will return the next 36 records but AFTER the last_id sent.
Hope this make sense and gives you a start.

Here is a reduced example of the JSON / AJAX mechanism that I have tested:
HTML (file test.html)
<html>
<head>
<!-- THE NEXT LINE MUST BE MODIFIED -->
<script src="../jquery-1.4.3.min.js" type="text/javascript"></script>
<script type="text/javascript">
var limit = 5;
var offset = 0;
// THE NEXT LINE MUST BE MODIFIED
var assetPath = "http://www.example.com/stackoverflow/test.php"
function displayRecords(lim, off) {
jQuery.ajax({
type: "GET",
url: assetPath,
dataType: "json", // We expect to receive a json object
data: "limit=" + lim + "&offset=" + off,
async: true,
cache: false,
beforeSend: function() {
$("#content").html("");
},
success: function(json) {
limit = json.lim; // corr to $output['lim']
offset = json.offs; // corr to $output['offs']
$("#content").html(json.html);
window.busy = false;
}
});
}
</script>
</head>
<body>
<div id="content"></div>
<div onclick="displayRecords(limit,offset); return false;" style="cursor:pointer">Click to Call</div>
</body>
</html>
PHP (file test.php)
<?php
$limit = (intval($_REQUEST['limit']) != 0 ) ? $_REQUEST['limit'] : 5;
$offset = (intval($_REQUEST['offset']) != 0 ) ? $_REQUEST['offset'] : 0;
// Prepare the $output structure (will become a json object string)
$output = array(
'lim'=>$limit,
'offs'=>$offset+$limit,
'html'=>''
);
$output['html'] .= '<span style="color:red;">limit='.$output['lim'].', offset='.$output['offs'].'</span>';
// Now encode $output as a json object (string) and send it to the client
header('Content-type: application/json; charset=utf-8');
echo json_encode($output, JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_FORCE_OBJECT);
Result
1st time
2nd time
nth time

Related

Change order status with AJAX in plugin wordpress

I am customizing a plugin, which gives recent orders and plays a sound notification. However i want to add an ajax call to a custom button that shows in every row:
This is my method so far:
// ajax function in plugin file
<?php
function my_action_javascript($order_id) {
$order = wc_get_order( $order_id ); // returns correct order id in every button
?>
<script type="text/javascript"> // initiate script
jQuery(function($){
$('pluginchangebutton').click( function(e){
e.preventdefault();
$.ajax({
type: 'POST',
dataType: 'json',
url: "<?php echo admin_url('admin-ajax.php'); ?>",
data: {
'action': 'my_action', // send php function ?
'order_id': <?php echo $order_id; ?>, // Here we send the order Id
},
success: function(response) { // no response at all
alert('ok');
},
error: function(response) { // no response at all
alert('error');
}
});
});
});
</script> <?php
}
add_action( 'wp_ajax_my_action', 'my_action' );// register my_action to wp ajax
function my_action() {
if ( isset($_POST['order_id']) && $_POST['order_id'] > 0 ) {
$order = wc_get_order($_POST['order_id']);
$order->update_status('completed'); // function to update status
die();
}
}
// ajax end
This is the ajax function which i place on top of the plugin file.
And this is how i display my table:
// get recent orders
$recent_orders = wc_get_orders(array(
'limit' => $show_order_num,
'orderby' => 'date',
'order' => 'DESC',
'status' => $show_order_statuses,
));
$content = "<h1>Нови порачки</h1>";
$content .= "<table id='customers-new-order-notification'>";
$content .= "<tr><th>Последни порачки</th></tr>";
$content .= "<tr><th>Порачка бр.</th><th>Дата на порачка</th><th>Статус на порачка</th><th>Детали за порачка</th></tr>";
foreach ($recent_orders as $recent_order) {
// get order details .. ... .. .. .. .. ..
$order_id = $recent_order->get_id();
$_order = wc_get_order($order_id);
$order_date = $_order->get_date_created();
$order_status = $recent_order->get_status();
$order_link = get_site_url();
$order_link .= "/wp-admin/post.php?post=";
$order_link .= $order_id;
$order_link .= "&action=edit";
$billing_first_name_plugin = $recent_order->get_billing_first_name();
$billing_address_1_plugin = $recent_order->get_billing_address_1();
$billing_city_plugin = $recent_order->get_billing_city();
$billing_postalcode_plugin = $recent_order->get_billing_postcode();
$billing_email_plugin = $recent_order->get_billing_email();
$billing_phone_plugin = $recent_order->get_billing_phone();
$billing_country_plugin = $recent_order->get_billing_country();
$order_shipping_method_plugin = $recent_order->get_shipping_method() . ' - ' . $recent_order->get_shipping_total() . ' rsd';
$order_get_subtotal_plugin = $recent_order->get_subtotal() . ' rsd';
$order_get_total_plugin = $recent_order->get_total() . ' rsd';
$order_javena='Непотврдена';
$customer_note_plugin = $recent_order->get_customer_note();
$statusPrefix = "wc-";
$_orderStatus = $statusPrefix . $order_status;
$_order_status = $order_status_map[$_orderStatus];
$date_format = get_option('date_format'); // format
$time_format = get_option('time_format'); // format
$format_order_date = $time_format . " - " . $date_format;
$items = $recent_order->get_items(); // get product items from order
// add content to $content .. table .. .. . .. row 1
// .... .... ... ... ... ... ... ... row 2
// row 3 start
$content .= "<td>" . esc_html($order_javena) ."<br>";
$content .= my_action_javascript($_order) . "<button class=pluginchangebutton type=submit>Потврди</button>";
$content .="</td>"; // row 3 end
// row 4 add .. .. ..
// row 4 end
if (!$isNew) {
delete_option('_new_order_id_for_notification');
$time = $refreshTime;
header("Refresh:" . esc_html($time) . "");
add_action('wp_head', 'wpb_hook_javascript');
}
echo $content;
}
In inspecting, the $.ajax gets the correct order id for every button, however i do not get a response at all. I've tried with console.log as well but still, no response.
I have tried inserting type, datatype and url with ' ', as well as " ", still nothing.
This code is in the plugin file.
I have tried adding it to functions.php, it does not work.
Can i get some guidance?

How to implement a live search for multiple text fields inside one column of a table?

I have currently implemented a live search (search as you type) function on text fields. The flow is something like this.
Call a .js file inside the page.
Set the id of the text field to "client-search".
Inside the .js file it is currently listening for on key up events of the "client-search" text field.
If the on key up event is fired, the .js file calls a PHP file that searches the database and returns the output as a list item in an unordered list underneath the "client-search" text field.
This setup currently works but how do implement it in multiple fields inside a single page, since it works using "id" and obviously I can't have multiple IDs in a single page.
HTML:
<div class="input-group">
<input type="text" id="client-search" class="form-control" placeholder="Search for manager...">
<ul class="livesearch" id="client-result" onclick="clickResult()"></ul>
</div>
JS
/* JS File */
// Start Ready
$j(document).ready(function() {
// Icon Click Focus
$j('div.icon').click(function(){
$j('input#client-search').focus();
});
// Live Search
// On Search Submit and Get Results
function search() {
var query_value = $('input#client-search').val();
$j('b#search-string').text(query_value);
if(query_value !== ''){
$j.ajax({
type: "POST",
url: "clientsearch.php",
data: { query: query_value },
cache: false,
success: function(html){
$("ul#client-result").html(html);
}
});
}return false;
}
$j("input#client-search").live("keyup", function(e) {
// Set Timeout
clearTimeout($.data(this, 'timer'));
// Set Search String
var search_string = $(this).val();
// Do Search
if (search_string == '') {
$j("ul#client-result").fadeOut();
}else{
$j("ul#client-result").fadeIn();
$j(this).data('timer', setTimeout(search, 100));
};
});
});
PHP:
<?php
$serverName = "(local)";
$connectionInfo = array( "Database"=>"CMS");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn ) {
} else {
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
$html = '';
$html .= '<li value="myLi" class="myLi">';
$html .= '<small>nameString</small>';
$html .= '<small></small>';
$html .= '</li>';
$search_string = $_POST['query'];
//$search_string = preg_replace("/[^A-Za-z0-9]/", " ", $_POST['query']);
if (strlen($search_string) >= 1 && $search_string !== ' ') {
$sql = "SELECT TOP 10 ClientName FROM Client WHERE ClientName LIKE '%" . $search_string . "%'";
$params = array($search_string);
$stmt = sqlsrv_query( $conn, $sql);
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
$results_array[] = $row;
}
if (isset($results_array)) {
foreach ($results_array as $result) {
$display_function = $result['ClientName'];
$display_name = $result['ClientName'];
$output = str_replace('nameString', $display_name, $html);
//$output = str_replace('functionString', $display_function, $output);
echo($output);
}
}else{
$output = str_replace('nameString', '<b>No Results Found.</b>', $html);
$output = str_replace('functionString', 'Sorry :(', $output);
echo($output);
}
}
?>

AJAX On Keyup Search Function

I wrote a AJAX search function which grabs the keyword values on key up and fires off the script. My goal is to have it populate the content area every key reordering the results to be in ABC order.
Instead what's happening is the first key fires off and the top result is always this
*ENGRAVING
then the rest of the values under it are in no specific order that I can tell.
I think this has to do with escaping characters?
Any help would be appreciated. Please help me get this to function so as a user searches the content area reorders itself being in order based on the keyword being searched up to the value that has been entered at that time.
On page load 5 results are added to the page then on page scroll more results are added to the page like this,
var assetPath = "<?php echo $assetPath ?>";
var searchPath = "<?php echo $searchPath ?>";
function displayRecords(lim, off) {
jQuery.ajax({
type: "GET",
async: false,
url: assetPath,
data: "limit=" + lim + "&offset=" + off,
cache: false,
beforeSend: function() {
$("#loader_message").html("").hide();
$('#loader_image').show();
},
success: function(html) {
$("#productResults").append(html);
$('#loader_image').hide();
if (html === "") {
$("#loader_message").html('<button data-atr="nodata" class="btn btn-default" type="button">No more records.</button>').show();
} else {
$("#loader_message").html('Loading... Please wait <img src="http://www.example.com/monstroid/wp-content/uploads/2016/02/LoaderIcon.gif" alt="Loading">').show();
}
window.busy = false;
}
});
}
Then when a user wants to search they use this form,
<div class="form-group pull-right">
<input type="text" name="itemID" id="itemID" class="search form-control" placeholder="Search product number">
</div>
Then this ajax function fires off on keyup
$("#itemID").keyup(function (){
var itemID = $(this).val();
var url = searchPath;
$.ajax({
type : "GET",
async : false,
url : url,
data : "itemID=" + encodeURIComponent(itemID),
cache : false,
success: function(html) {
$('#loader_image').hide();
$( "#productResults" ).replaceWith( html );
if (html === "") {
$("#loader_message").html('<p>There were no results that match your search criteria</p>').show();
} else {
$("#loader_message").html('Searching... Please wait <img src="http://www.example.com/monstroid/wp-content/uploads/2016/02/LoaderIcon.gif" alt="Loading">').show();
}
window.busy = false;
}
});
});
which runs this script at searchPath as the path variable
require_once ('Dbconfig.php');
$sql=" SELECT * FROM wuno_inventory WHERE wuno_product like '%".$itemID."%' OR wuno_alternates like '%".$itemID."%' ORDER BY wuno_product ";
try {
$stmt = $DB_con->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll();
} catch (Exception $ex) {
echo $ex->getMessage();
}
if (count($results) > 0) {
foreach ($results as $res) {
echo '<tr class="invent">';
echo '<td>' . $res['wuno_product'] . '</td>';
echo '<td>' . $res['wuno_alternates'] . '</td>';
echo '<td>' . $res['wuno_description'] . '</td>';
echo '<td>' . $res['wuno_onhand'] . '</td>';
echo '<td>' . $res['wuno_condition'] . '</td>';
echo '</tr>';
}
}
The initial data populates perfectly in order from what is in the database. So I do not see why there would be problems for this function if it is a escaping situation.
Also the initial data is paginated. Would this cause a problem with the second query? I was thinking maybe since there is so much data it's all being appended to the content instead of replacing it. Maybe the jquery is conflicting?
Try introducing the timeout for your AJAX call. Move your AJAX JS into a separate function first:
function get_search_results(event) {
var itemID = $(event.target).val();
var url = searchPath;
$.ajax({
type : "GET",
async : false,
url : url,
data : "itemID=" + encodeURIComponent(itemID),
cache : false,
success: function(html) {
$('#loader_image').hide();
$( "#productResults" ).replaceWith( html );
if (html === "") {
$("#loader_message").html('<p>There were no results that match your search criteria</p>').show();
} else {
$("#loader_message").html('Searching... Please wait <img src="http://www.example.com/monstroid/wp-content/uploads/2016/02/LoaderIcon.gif" alt="Loading">').show();
}
window.busy = false;
}
});
}
Then add it to your keyup handler:
$("#itemID").keyup(function (){
setTimeout(get_search_results, 200);
});

AJAX Search Function Not Updating Answer

I have an AJAX function that calls a php function to search a mysql database. The script fires off on keyup and the problem is on the first key press the html content is updated but it will not update after the initial keyup event
How do I make the page continuously update the html content with the new data that is coming in after every keyup.
My AJAX function,
var searchPath = "<?php echo $searchPath ?>";
$("#itemID").keyup(function (){
var itemID = $(this).val();
var url = searchPath;
$.ajax({
type : "GET",
async : false,
url : url,
data : "itemID=" + encodeURIComponent(itemID),
cache : false,
success: function(html) {
$('#loader_image').hide();
$( "#productResults" ).replaceWith( html );
if (html === "") {
$("#loader_message").html('<p>There were no results that match your search criteria</p>').show();
} else {
$("#loader_message").html('Searching... Please wait <img src="http://www.example.com/monstroid/wp-content/uploads/2016/02/LoaderIcon.gif" alt="Loading">').show();
}
window.busy = false;
}
});
});
And this is the php behind it all,
<?php
require_once ('Dbconfig.php');
$sql=" SELECT * FROM wuno_inventory WHERE wuno_product like '%".$itemID."%' OR wuno_alternates like '%".$itemID."%' ORDER BY wuno_product ";
try {
$stmt = $DB_con->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll();
} catch (Exception $ex) {
echo $ex->getMessage();
}
if (count($results) > 0) {
foreach ($results as $res) {
echo '<tr class="invent">';
echo '<td>' . $res['wuno_product'] . '</td>';
echo '<td>' . $res['wuno_alternates'] . '</td>';
echo '<td>' . $res['wuno_description'] . '</td>';
echo '<td>' . $res['wuno_onhand'] . '</td>';
echo '<td>' . $res['wuno_condition'] . '</td>';
echo '</tr>';
}
}
?>

parse return data from html to ajax

I have some problem with the returned value of ajax.
this is the ajax code:
$(document).ready(function() {
var request;
$("#flog").submit(function(event) {
if(request)
request.abort();
event.preventDefault();
var form = $(this);
var serializedData = form.serialize();
var btnname = $('#log').attr('name');
var btnval = $('#log').val();
var btn = '&'+btnname+'='+btnval;
serializedData += btn;
request = $.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: serializedData,
});
request.done(function(data, status, jdXHR) {
alert(data);
});
request.fail(function(jdXHR, status, error) {
});
});
});
it takes data from a form and send it to another page.
this is the second page:
<?php include 'head.php'; ?>
<?php
if($_POST['login']) {
session_regenerate_id(true);
$con = mysqli_connect("localhost", "Alessandro", "ciao", "freetime")
or die('Could not connect: ' . mysqli_error($con));
$query = 'SELECT * FROM users WHERE username="' . $_POST['user'] . '"';
$result = mysqli_query($con, $query) or die('Query failed: ' . mysqli_error($con));
if(mysqli_num_rows($result) == 0) {
mysqli_close($con);
session_unset();
session_destroy();
$res = false;
return $res;
}
$query = 'SELECT password FROM users WHERE username="' . $_POST['user'] . '"';
$result = mysqli_query($con, $query) or die('Query failed: ' . mysqli_error($con));
$line = mysqli_fetch_array($result, MYSQL_ASSOC);
if(md5($_POST['password']) != $line['password']) {
mysqli_close($con);
session_unset();
session_destroy();
return false;
}
?>
<?php include 'foot.php'; ?>
and in .done the returned data is all the html page.
How can I retrieve only a data, like $res? I tried with json_encode() but with no results.
If in the second page I delete the lines include 'head.php' and include 'foot.php' it works. But I need that the secon page is html, too.
Somenone can help me?
Dont use the Data attribute from AJAX.
Replace
request.done(function(data, status, jdXHR) {
alert(data);
});
with
request.done(function(data, status, jdXHR) {
alert(jdXHR.responseText);
});
You could do it in a much simpler way.
In PHP store the result of the attempted login into a variable, for instance $result =0; to start with
If the login is valid change it to 1 and return it to ajax by doing an echo at the end of your PHP file. If you need other value returned such as the name you could add it to the variable with a separator such as || for instance.
in javascript collect your return and go data = data.split('||');
if (data[0] == 0){alert("Welcome back " + data[1]);}else{alert("wrong login...")}
Previous use is correct, you need to escape the user collected in your PHP script.
Hope this helps.

Categories