I'm doing a personal blog and recently have stopped because of this little problem... is being a challenge to me to figure it out so... I hope you could help me guys
What I want to do is; put some kind of limit to the results I obtain while searching, and that's because these results are loaded asynchronously while typing, so... if I search for something that has over 100 results (for example) the scroll will be just too long, so what I'd like to do is make appear some kind of 'load more button' that allows the user to load more results if he wants to.. how could I do that?
Here's the code I have done so far...
HTML:
<input type="text" id="busqueda" name="busqueda" value="" required autocomplete="off" onKeyUp="search();">
<div id="result"></div>
<button id="loadmore"> load more</button>
PHP:
<?php
//connect to db
require('db_conexion.php');
$consultaBusqueda = $_POST['valorBusqueda'];
if (isset($consultaBusqueda)) {
//sanitize post value
$page_number = filter_var($_POST["page"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH);
//throw HTTP error if page number is not valid
if(!is_numeric($page_number)){
header('HTTP/1.1 500 Invalid page number!');
exit();
}
//capacity
$item_per_page = 5;
//get current starting point of records
$position = (($page_number-1) * $item_per_page);
//query
$buscar= $conexion->query("SELECT info from table ORDER BY id DESC LIMIT $position,$item_per_page");
//conditionals
if (!$query_execute->num_rows) {
$mensaje = "no results";
}else{
$filas= $query_execute->num_rows;
echo $filas.' Results for <mark>'.$consultaBusqueda.'</mark>';
//show results
while($row = $buscar->fetch_array()) {
$variable="something";
echo $variable;
}
}
}else{
echo "Error";
}
?>
JS:
function stopRKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.keyCode == 13) && (node.type=="text")) {return false;}
}
document.onkeypress = stopRKey;
function search() {
var textoBusqueda = $("input#busqueda").val();
if (textoBusqueda != "") {
$("#resultadoBusqueda").show();
$.post("actions/search.php", {valorBusqueda: textoBusqueda}, function(menssage) {
$("#resultadoBusqueda").html(menssage);
});
} else {
$("#resultadoBusqueda").html("");
};
};
Here you have the page so you can see how is working right know
http://www.subeuna.com/blog/
all you have to do y search something, anything... and you'll see... i really need your help guys I hope your answers :(
You might look into having your backend api only return a max number of results and if it exceeds that number provide a property to fetch more. If that extra property exists present the load more button otherwise do not.
API pagination best practices
Related
Have a function that makes a change to taxonomy term via AJAX. This works great, except the content remains unchanged on window.location.reload(true) even though the change has been made. See the code and GIF below to understand.
This is an example that adds the button and reloads page on click
if ( 'publish' === $post->post_status && $post->post_type === 'campaigns' ) {
$text = (in_category( 'live') ? 'Activate' : 'Activate');
echo '<li>' . $text . '</li>';
}
So, is there another way that I can reload the page onClick that may help? Also, the post modified date is not updating, yet changes have been made to the post.
Thanks in advance for your help
EDIT -
I have already tried
location.href = location.href; and
document.location.reload();
ADDITIONAL INFO -
Function
add_action('wp_ajax_toggle_live', function(){
// Check ID is specified
if ( empty($_REQUEST['post']) ) {
die( __('No post ID specified.') );
}
// Load post
$post_id = (int) $_REQUEST['post'];
$post = get_post($post_id);
if (!$post) {
die( __('You attempted to edit an item that doesn’t exist. Perhaps it was deleted?') );
}
// Check permissions
$post_type_object = get_post_type_object($post->post_type);
if ( !current_user_can($post_type_object->cap->edit_post, $post_id) ) {
die( __('You are not allowed to edit this item.') );
}
// Load current categories
$terms = wp_get_post_terms($post_id, 'campaign_action', array('fields' => 'ids'));
// Add/remove Starred category
$live = get_term_by( 'live', 'campaign_action' );
$index = array_search($live, $terms);
if ($_REQUEST['value']) {
if ($index === false) {
$terms[] = $live;
}
} else {
if ($index !== false) {
unset($terms[$index]);
}
}
wp_set_object_terms( $post_id, 'live', 'campaign_action' );
die('1');
});
JS
function toggleLive(caller, post_id)
{
var $ = jQuery;
var $caller = $(caller);
var waitText = ". . .";
var liveText = ". . .";
var deactivateText = ". . .";
// Check there's no request in progress
if ($caller.text() == waitText) {
return false;
}
// Get the new value to set to
var value = ($caller.text() == liveText ? 1 : 0);
// Change the text to indicate waiting, without changing the width of the button
$caller.width($caller.width()).text(waitText);
// Ajax request
var data = {
action: "toggle_live",
post: post_id,
value: value
};
jQuery.post("<?php bloginfo( 'wpurl' ); ?>/wp-admin/admin-ajax.php", data, function(response)
{
if (response == "1") {
// Success
if (value) {
$caller.text(deactivateText);
} else {
$caller.text(liveText);
}
} else {
// Error
alert("Error: " + response);
// Reset the text
if (value) {
$caller.text(deactivateText);
} else {
$caller.text(liveText);
}
}
// Reset the width
$caller.width("auto");
});
// Prevent the link click happening
return false;
}
IT WORKS RIGHT ON PAGE THAT ISN'T SINGULAR
Is toggleLive the function that makes the AJAX request? You are calling reload immediately on click before changes are reflected on the backend. If you are using Jquery include your reload code in the complete callback function that indicates completion of your AJAX request.
Try using Live Query plug-in in jquery instead of live .
I was able to achieve this by setting return trueOrFalse(bool); in the JS and adding the permalink for the page into <a href=""> within the function.
I believe #cdoshi was correct in their answer, yet I was unable to achieve this. I am sure that a little further exploration would make this possible, yet my fix achieved what I wanted with little change to my code.
I'm a student and still new with Javascript and php, i need to make a login page for my website that can check user input in the database using ajax.
Example: When the user enter their username and password into the field given,the system will automatically check in database either the user exist or not and return the data needed such as user responsibilty from the response table to the dropdown menu below, then they can login into the system.
Below is my basic coding:
Config.php:
e$host = "localhost";
$User = "root"
$Pass = "passw";
$db = "skm_spm";
Login.php:
<?
require ("config.php");
$conn=mysqli_connect($host,$user,$pass,$db);
$duser="select * from tab_user where user_name = '".$_POST["Lname"]."'";
$uresult=myqli_query($conn,$duser);
if(!$uresult)
die("Invalid query: ".mysqli_error());
else
if(mysqli_num_rows($uresult)== 0){
echo "User does not exist";
}
else
{
$row=mysqli_fetch_array($result,MYSQL_BOTH);
if($row["User_Password"] == $_POST["Lpass"])
{
$dresp="select resp_id,resp_name from tab_resp";
$result2 = mysqli_query($conn,$dresp);
}
else
{
}
}
?>
<html>
<b>Login</b><br>
Name : <input type = "text" name="Lname" id="Lname" placeholder="Username"/><br>
Password: <input type = "password" name="Lpass" id="Lpass" placeholder="password"/><br><br>
<div class = "optresp">
<select name="sresp" id="sresp">
<option>--Responsibility--</option>
<?
while (mysqli_fetch_array($result2)){
echo "<option value='$row[1]'>$row[1]</option>";
?>
</select>
</div>
</html>
I have learn on internet and try to code with my understanding,but still failed. I need a php ajax coding that can work with code above.
Thank you.
I will provide you with some code from my recent project and hopefully you will be able to understand it and adapt it to your needs.
Firstly, you should have the login form in a separate file to the PHP login code. Then have button on the page or an enter events that run a Javascript function, in my case Login(). In this Javascript function the text within the input fields are saved to two variables and some basic checks are done on them to ensure that they have been filled in. Next, the PHP login function file (it has no visible content in just processes some data in PHP) using the $.post line. This also passed the two input variables (under the same name) to the PHP file. You can also see that depending on what is returned/echoed from the PHP file as "data" several possible outcomes may occur (Login Success, Account Banned or Invalid Login). I personally call these outcomes error messages or success messages, for example error message 6 for incorrect password/username.
//FUNCTIONS
function Login(){
var StrUsername = $("#txtUsername" ).val();
var StrPassword = $("#txtPassword").val();
if (StrUsername == "" && StrPassword == ""){
$('#pError').text('Enter your Username and Password!');
}
else if(StrUsername == ""){
$('#pError').text('Enter your Username!');
}
else if(StrPassword == ""){
$('#pError').text('Enter your Password!');
}
else{
$.post('https://thomas-smyth.co.uk/functions/php/fnclogin.php', {StrUsername: StrUsername, StrPassword: StrPassword}, function(data) {
if (data == 0){
window.location.href = "https://thomas-smyth.co.uk/home";
}
else if (data == 1){
window.location.href = "https://thomas-smyth.co.uk/banned";
}
else if (data == 6){
$('#pError').text('Username & Password combination does not exist!');
}
});
}
}
Next the PHP function file. Firstly, the variables passed by the Javascript are collected using $_POST. My SQL class is then pulled into the file, this does all my SQL DB connections. I then have my SQL statement that will search to see if the account exists. Notice the ? in it. This prevents SQL injections as the variables is bound into the statement through the SQL server meaning it won't allow people to put SQL code within my input fields to break my database. I then check whether the account exists, if it doesn't I save data to 6, which will cause the error message 6 in the Javascript to run when data is returned. I have a field in my database that contains a rank. If the login is correct then I create a SESSION variable to store their username and rank in. This is later used on pages to check whether they are logged in before displaying a page (this speeds up navigation as it means that the DB doesn't need to be searched everytime the user switches page, however does bring some issues like if you ban a user while they are logged in they will stay logged in until their session dies). You could use this on your dropdown menu to ensure the user is logged in and/or get their username. Finally, I return 0 or 1, so that the Javascript then re-directs them to the correct page.
<?php
//Retrieves variables from Javascript.
$StrUsername = $_POST["StrUsername"];
$StrPassword = $_POST["StrPassword"];
require "sqlclass.php";
$TF = new TF_Core ();
$StrQuery = "
SELECT Username, Rank FROM tblUsers
WHERE Username = ? AND Password = ?";
if ($statement = TF_Core::$MySQLi->DB->prepare($StrQuery)) {
$statement->bind_param('ss',$StrUsername,$StrPassword);
$statement->execute ();
$results = $statement->get_result ();
if($results->num_rows == 0){
$data = 6;
}
else {
while ($row = $results->fetch_assoc()) {
//Other groups
if ($row["Rank"] == "Developer" || $row["Rank"] == "Staff" || $row["Rank"] == "Cadet"){
session_start();
$_SESSION["LoginDetails"] = array($StrUsername, $row["Rank"]);
$data = 0;
}
//Banned
else if ($row["Rank"] == "Banned"){
session_start();
$_SESSION["LoginDetails"] = array($StrUsername, "Banned");
$data = 1;
}
}
}
}
echo $data;
?>
Hopefully this helps you. Please say if you need more help!
You need to make ajax call on blur of username to check if user exists in database and on success of that you can make one more ajax to check for password match of that particular user. This will give you both cases whether a user exixts or not if exixts then does the password match or not only after that user will be logged in and then you can show the responsibilities of that particular user.
For username:
$('#Lname').blur(function(){
$.ajax({
url:'url where query for matching username from database',
data:'username collected from input on blur',
type:'POST',
success:function(data){
//Code to execute do on successful of ajax
}
})
})
For Password:
The ajax call remains the same only url, data and response changes
I've created a simple [voting form] using jQuery AJAX and JSON. I want to know how to create a Cookie so that the user will not be able to vote more than once. Following is my code.
I am new to Cookies and jQuery. Please tell me how to complete my task.
JavaScript
<script>
$(document).ready(function(){
$("#poll").click(function(){
var count = '';
if (document.getElementById("vote1").checked) {
count = 0;
}
if (document.getElementById("vote2").checked) {
count = 1;
}
var jsonV= { "vote": count };
$.ajax({
type : "POST",
url : "poll_vote.php",
data : jsonV,
dataType: "json",
success : function ( responseText ){
console.log("Is working " + responseText);
$("#result").html( responseText.vote );
},
complete : function(){
$("#poll").slideUp();
},
error : function( error,responseText ){
// alert("Server not Responding. Sorry for the inconvenience caused. Please Try again Later");
console.log( error );
$("#result").html( error + responseText );
alert( count );
}
});
});
});
</script>
PHP
<?php
$vote = $_REQUEST['vote'];
$filename = "poll_result.txt";
$content = file($filename);
// $decode = json_decode($encode);
$array = explode("||", $content[0]);
$male = $array[0];
$female = $array[1];
if ($vote == '0') {
$male = $male + 1;
}
if ($vote == '1') {
$female = $female + 1;
}
$insertvote = $male."||".$female;
$fp = fopen($filename,"w");
fputs($fp,$insertvote);
fclose($fp);
$table = (
"<h2>Results:</h2>
<table>
<tr>
<td> Male :</td>
<td>
<img src='poll.gif'
width= ".(100*round($male/($female+$male),2)).
"height='20'>".
(100*round($male/($female+$male),2))." %" .
"
</td>
</tr>
<tr>
<td> Female :</td>
<td>
<img src='poll.gif'
width=". (100*round($female/($female+$male),2)) .
"
height='20'>".
(100*round($female/($female+$male),2))." %" ."
</td>
</tr>
</table>"
);
$list = array('vote' => $table);
$encode = json_encode($list);
echo $encode;
?>
HTML
<div id= "poll">
<h3> What is your Gender? </h3>
<form>
Male :
<input type ="radio" name ="vote" id="vote1" >
<br>
Female :
<input type ="radio" name ="vote" id="vote2" >
</form>
</div>
You would want to set a cookie when the user votes, and check for that cookie in PHP when a vote is submitted. If the cookie is already set, the vote should be discarded.
For example, using just PHP, it could look something like this:
if (!isset($_COOKIE['has_voted'])) {
// normal vote submission code goes here
// ...
// then we set a cookie to expire in 30 days
setcookie('has_voted', '1', mktime().time()+60*60*24*30);
} else {
// cookie already exists, user has already voted on this machine
// do not count the vote, flag an error to the user
}
It is worth noting that there are ways round this - the user could easily delete the cookie manually. In this case, you could also store the IP addresses of users who have already voted, but this can open up problems on shared machines and multiple machines behind a network.
Since it seems you're using PHP, you'll be able to implement a cookie to prevent multiple votes within your already existing script.
The syntax for setting a cookie in PHP is as follows:
setcookie("cookiename", "cookiedata", cookietime, "cookielocation");
Where "cookiename" is the name of the cookie, for example, "voted", "cookiedata" is the data stored in the cookie– "yes", for example. "cookielocation" is the location where the cookie is stored in the user's browser cache. Unless you know what you're doing, just set this to "/".
Cookietime is how long the cookie will sit in the users system until the browser automatically deletes it. Note that this doesn't prevent the user from deleting the cookie. For simplicity, I usually set the time as follows:
time()+60*60*24*days
Where days is how long the cookie will sit in the user's system (in days, of course).
To retrieve the value of a cookie so you're able to perform logic on it, try using:
if(isset($_COOKIE['cookiename'])) {
$valueOfCookie = $_COOKIE['cookiename'];
}
Make sure to use the if(isset()) to make sure the cookie has been set, before trying to retrieve the value.
Using these functions, your logic may look something like this when the user submits the form:
Check if the voting cookie is set
If it is, print an error message, else:
Continue to process the form data, and set the vote cookie
However, on a side note, if you're concerned about users potentially deleting their cookies so they can vote again, I might suggest that, rather than using cookies, you store users' IP addresses on the server-side, and deny them voting access if their IP address has already voted.
You could do this with sessionStorage, using only JS:
<script>
$(document).ready(function(){
$("#poll").click(function(){
var count = '';
if (document.getElementById("vote1").checked) {
count = 0;
}
if (document.getElementById("vote2").checked) {
count = 1;
}
var jsonV= { "vote": count };
if ( sessionStorage.getItem( 'voted' ) == 'true' ) {
alert('You have already voted!');
}else if ( sessionStorage.getItem( 'voted' ) == null ){
$.ajax({
type : "POST",
url : "poll_vote.php",
data : jsonV,
dataType: "json",
success : function ( responseText ){
console.log("It's working" + responseText);
$("#result").html( responseText.vote );
},
complete : function(){
$("#poll").slideUp();
sessionStorage.setItem('voted', 'true');
},
error : function( error,responseText ){
// alert("Server not Responding. Sorry for the inconvenience caused. Please Try again Later");
console.log( error );
$("#result").html( error + responseText );
alert( count );
}
});
}
});
});
</script>
What I have done here is added a session storage item in the
complete callback of your ajax call, so once it has completed the
item 'voted' will be set.
I have then wrapped the ajax call in an if condition which checks
the value of the storage item and if it is set then will not allow
you to vote (and instead bring up an alert)
Note that you can also you localStorage if you want the item to last longer as sessionStorage is cleared when the browser window is closed while localStorge will last until the user clears their cookies / browsing data.
And here is a little snippet you can use to clear the storage for testing purposes:
$('#clear').click(function(){
console.log(sessionStorage.getItem( 'voted' ));
sessionStorage.removeItem('voted');
console.log(sessionStorage.getItem( 'voted' ));
});
You will need the accompanying HTML with that:
<p id="clear">clear</p>
I am working on a turn based multiplayer game using php and ajax. The features allow players to log into the game using user info, and select game modes which allows them to either play against AI or opponents. Each user can select a character from a list, and this function has already been completed. I would like to create a search function so that a player could search and battle another player, something similar to chess. However, at the moment I would like for the player to enter another users username in order for the search to take place. I have searched open source to find a method to creating a search function, but the current function I found breaks my code. Here is my current mode codes:
// Define Mode
if (isset($_GET['mode'])) {
$mode = $secure->clean($_GET['mode']);
} else {
$mode = '';
}
if ($mode == 'selection') {
$page_title .=' > Character Selection';
$page_titles .= ' Character Selection - Power Bond';
}
else if ($mode == 'search') {
if (isset($_GET['type'])) {
$type = $secure->clean($_GET['type']);
} else {
$type = '';
}
if ($type == 'private') {
if (isset($_POST['pbsubmit'])) {
$name = $secure->clean($_POST['name']);
}
}
}
Now here is my ajax. The function I found was for checking the match in order to find the username. That function breaks my game.
//Check the match.
if (isset($_POST['f']) && $_POST['f'] == 'checkMatch') {
$checkMatch = $db->query("SELECT * FROM accounts WHERE `id` = '".$account['id']."'");
while ($info = mysql_fetch_array($checkMatch)) {
$status = $info['status'];
$gameid = $info['gameid'];
}
$getGame = $db->fetch("SELECT * FROM Games WHERE `gameid` = '$gameid'");
$status = $info['status'];
$gameid = $info['gameid'];
if(!$getGame = 'NULL') {
$data = 'testaeta';
} else {
$data = '<h1> Who do you want to battle against? </h1>
<br />
<form action="" method="post" id="form-pb" name="pb" target="_self">
USERNAME:<input name="name" type="text" size="40" maxlength="40" />
<input name="pbsubmit" type="submit" value="Search"/>
</form>
<a class="goback" href="#">Cancel</a>';
}
echo $data;
}`
Here is my Javascripit:
`var match = null;
function popUp(what){
if(!what) errorMessage('Error: params', 'params', 'none');
switch(what){
case 'search':
preLoad('Loading please wait . . .');
$('#main_container').prepend('<div id="popup"><div class="opacity"></div><div class="search"></div></div>');
$('.search').load('./?page=game&mode=search&type=private', function(){
$('#preloader').fadeOut('slow',function(){
$('#preloader').remove();
});
});
break;
case 'match':
$.ajax({
url : _path + "/core/ajax.php",
type : 'POST',
data : { f: 'checkMatch'},
dataType : 'text',
success : function(data) {
if(data){
$('#main_container').prepend(data);
match = setInterval(function(){
if(!$('.search').length){
$('#main_container').prepend('<div id="popup"><div class="opacity"></div><div class="search"></div></div>');
}
$('.search').load('./?page=game&mode=search&type=private', function(){
var meta = $('#stopMe').attr('content');
if(meta){
meta = meta.split("URL="), meta = meta[1];
window.location = meta;
}
});
},1000);
}
}
});
break;
case 'submit':
$.post('./?page=game&mode=search&type=private', $("#form-pb").serialize(), function(data){
var $response=$(data);
var error = $response.filter('h3').text();
$('.search').html(data);
if(!error){
match = setInterval(function(){
if(!$('.search').length){
$('#main_container').prepend('<div id="popup"><div class="opacity"></div><div class="search"></div></div>');
}
$('.search').load('./?page=game&mode=search&type=private', function(){
var meta = $('#stopMe').attr('content'); var meta = $('#stopMe').attr('content');
if(meta){
meta = meta.split("URL="), meta = meta[1];
window.location = meta;
}
});
},1000);
}
});
break;
}
}
`
Aside from mysql, those are my main focuses on allowing this to work. Does anyone have a solution on how I could fix this problem? Also, I would like an open source example if possible.
There is no need to search an already coded search solution, generally this is very specific to your application and not complicated.
Look for an autocompletion tool (jQuery provide it), a way to get secure data (GET or POST but check it) and a search method: LIKE %...% (simple) or MATCH(...) AGAINST(...) (More complete)
Seems like a match making system. You could create a table in mysql and name it something like active battles. It then takes user A's info and matches it with user B, putting them inside a battle. I think you could also make a table for the battles actions. That table shows what the users do while in a battle.
PHP - alexa.php
<?
$url = filter_var($_GET['url'], FILTER_SANITIZE_URL);
$xml = simplexml_load_file('http://data.alexa.com/data?cli=10&dat=snbamz&url='.$url);
$rank=isset($xml->SD[1]->POPULARITY)?$xml->SD[1]->POPULARITY->attributes()->TEXT:0;
web == (string)$xml->SD[0]->attributes()->HOST;
echo $rank;
?>
Javascript - alexa.js
function alexa() {
var $btn = $('#buttonreg');
var $input = $('#domain');
var url = $.trim($input.val());
$.get('alexarank.php?url='+url, function(data){
var alexa = parseInt(data);
if ($.trim(data) == '' || alexa < 500000)
{
alert('We don't accept sites with alexa rank higher than 500.000.');
$btn.attr('disabled', 'disabled');
}
else
{
$btn.removeAttr('disabled');
}
}, 'text');
}
HTML - page.html
<input id="domain" class="txt" type="text" name="domain" size="25" value="" maxlength="255" onblur="alexa()"></input>
I need to echo the error alert('We don't accept sites with alexa rank higher than 500.000.'); when the user is adding his website on the registration form if his site alexa rank is smaller than 500.000. I have tested it and it doesn't work, it doesn't do anything.
Started testing it from php, the php works when i go in the browser http://www.testingsite.com?url=http://www.google.com it returns the right value so i am thinking that i have done something bad with the javascript or HTML.
I'll make things clear what I mentioned in the comment.
alert('We don't accept sites with alexa rank higher than 500.000.');
should be replaced with
alert("We don't accept sites with alexa rank higher than 500.000.");
The first one (which you have in your code) has mismatching quotes, and obviously breaks the rest of the code. The single quote you used in " don't " is what broke everything.
EDIT:
Change your code to this and try. If still doesn't work, check js console.
function alexa() {
var $btn = $('#buttonreg');
var $input = $('#domain');
var url = $.trim($input.val());
$.get('alexarank.php?url='+url, function(data){
if( typeof(data) == "undefined" ) return false;
var alexa = parseInt(data);
if ($.trim(data) == '' || alexa < 500000)
{
alert('We do not accept sites with alexa rank higher than 500.000.');
$btn.attr('disabled', 'disabled');
}
else
{
$btn.removeAttr('disabled');
}
});
}