Like button increment counter not working. PHP, AJAX, MySQL, javascript - javascript

I am implementing a facebook like "Like" button counter so everytime a user clicks on the button, a DIV tag besides it retrieves it from the db and updates it (see logic of the code below). However it isn't working. Please see all codes below:-
javascript:
function likeAJAX(strName)
{
If(strName == "")
{
document.getElementById('likeCount').innerHTML="";
return;
}
else
if(window.XMLHttpRequest)
{
xmlHTTP = new XMLHttpRequest();
}
else
{
xmlHTTP = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlHTTP.onreadystatechange = function()
{
if(xmlHTTP.readystate == 4 && xmlHTTP.status == 200)
{
document.getElementById('likeCount').innerHTML = xmlHTTP.responseText;
}
}
xmlHTTP.open("GET","getLikes.php?n=" + strName,true);
xmlHTTP.send();
}
HTML/PHP front-end:
<img src="./images/like.jpg" style="cursor:hand;" onclick="likeAJAX(<?php echo $_GET['val']; ?>)"><?php echo $likeVal; ?> people like this</span>
PHP/MySQL:
<?php
$q = $_GET['n'];
$temp;
$con = mysql_connect('localhost','xxxx','xxxx');
mysql_select_db("xxxx");
$SQLQuery = "SELECT * FROM likes where name= '" . $q . "'";
$res = mysql_query($SQLQuery);
while($data = mysql_fetch_array($res))
{
$temp = $data['likes'];
}
mysql_free_result($res);
mysql_close($con);
if($temp == "")
{
$temp = "0";
}
$intCount = int($temp);
$intCount++;
$con = mysql_connect('localhost','xxxx','xxxx');
mysql_select_db("xxxx");
$SQLQuery = "UPDATE likes set likes = '" . $intCount . "' WHERE busname = '". $q . "';";
$res = mysql_query($SQLQuery);
mysql_free_result($res);
mysql_close($con);
echo $intCount;
?>
Apologies for any formatting issues.
Where am i going wrong? The way i see it, seems like upon clicking the Like image, the javascript function doesn't even seems to be called?
Regards,
Ochen

Try this correction to your js:
function likeAJAX(strName) {
if (strName == "") {
document.getElementById('likeCount').innerHTML="";
return;
} else {
if(window.XMLHttpRequest) {
xmlHTTP = new XMLHttpRequest();
} else {
xmlHTTP = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlHTTP.onreadystatechange = function() {
if (xmlHTTP.readystate == 4 && xmlHTTP.status == 200) {
document.getElementById('likeCount').innerHTML = xmlHTTP.responseText;
}
}
xmlHTTP.open("GET","getLikes.php?n=" + strName,true);
xmlHTTP.send();
}
}

Related

How do I send a value from Javascript to PHP that will not be changed?

I have function that is running multiple times and executing a PHP file. I do, however, want to make sure the functions does not interfere with each other.
for(int i = 0; i<5; i++){
functionName(i)
}
function functionName(number){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
}
};
var PageToSendTo = "phpFile.php?";
var MyVariable = number;
var VariablePlaceholder = "name=";
var UrlToSend = PageToSendTo + VariablePlaceholder + MyVariable;
xhttp.open("GET", UrlToSend, true);
xhttp.send();
}
This is how my code looks so far, how do I change it so that the next iteration of the function does not effect the previous one?
phpFile.php
<?php
require '../notWebsite/dbh.php';
session_start();
$variable = $_GET['name'];
$sqlInsertClass = "INSERT INTO class (className) VALUES (?)";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sqlInsertClass)) {
header("Location: ../Website.php?error=InsertError");
exit();
} else {
mysqli_stmt_bind_param($stmt, "s", $variable);
mysqli_stmt_execute($stmt);
exit();
}
mysqli_stmt_close($stmt);
mysqli_close($conn);
?>

how to force the browser to run the javascript every time it called

Dears
I called a javascript function on onload body
<body onload="loadLeads()">
This function loads a leads information from database and display it in a table.
The problem is when the user press on delete button to delete a lead from the table. the function runs correctly and delete the lead from the database. BUT although the deletelead function relaoad the page which calls loadLeads() on load the page which should display the new leads without the deleted one. BUT the deleted one display again! although it deleted from the database!!
how can I run it correctly??
I should delete the cache of the browser each time to force the code runs correctly!!
how can I do it please?
this is the javascript code for delete
function deleteLead(id)
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
location.reload();
}
}
xmlhttp.open("GET", "deletelead.php?id="+id, true);
xmlhttp.send();
}
This is the script calling in the HTML
<script src="https://example.net/js/loadLeads.js?version=' + Math.floor(Math.random() * 100) + '"\><\/script>'"></script>
This is the loadleads function javascript
function loadLeads()
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
LeadsInfo = JSON.parse(this.responseText);
LeadsInfoCount = LeadsInfo.length;
DrawLeadsTable();
}
}
xmlhttp.open("GET", "LoadLeads.php", true);
xmlhttp.send();
}
This is the LoadLeads.php
<?php
require "conn.php";
$SelectSQL = "SELECT * FROM leads";
$result = $conn->query($SelectSQL);
$ECount = $result->num_rows;
if ($ECount != 0 )
{
$FinalArr = array();
$count =0;
while($row1 = $result->fetch_assoc())
{
$id = $row1["id"];
$name = $row1["name"];
$email = $row1["email"];
$mob = $row1["mob"];
$country = $row1["country"];
$comefrom = $row1["comefrom"];
$time = $row1["time"];
$qulified = $row1["qulified"];
$landingpage = $row1["landingpage"];
$myArr = array($id,$name,$email, $mob,$country,$comefrom,$time,$qulified,$landingpage);
$FinalArr[$count] = array();
$FinalArr[$count] = $myArr;
$count++;
$UserData = json_encode($FinalArr,JSON_UNESCAPED_UNICODE);
}
}
mysqli_close($conn);
echo $UserData;
?>
Add this before the xmlhttp.send();
xmlhttp.setRequestHeader("Cache-Control", "no-cache, no-store, must-revalidate");

New variable ajaxObj does not work

For some weird reason this line of code is not working:
var ajax = ajaxObj("POST", "php_parsers/status_system.php");
What could it be?
I figured it must be the above line using window.alert's since after that line window.alert does not run.
Full code:
The function is called:
$status_ui = '<textarea id="statustext" onkeyup="statusMax(this,250)" placeholder="What's new with you '.$u.'?"></textarea>';
$status_ui .= '<button id="statusBtn" onclick="postToStatus(\'status_post\',\'a\',\''.$u.'\',\'statustext\')">Post</button>';
The function:
function postToStatus(action,type,user,ta){
window.alert("status passed 1");
var data = _(ta).value;
if(data == ""){
alert("Type something first weenis");
return false;
}
window.alert("status passed 2");
_("statusBtn").disabled = true;
var ajax = ajaxObj("POST", "php_parsers/newsfeed_system.php");
window.alert("status passed 3");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
var datArray = ajax.responseText.split("|");
if(datArray[0] == "post_ok"){
var sid = datArray[1];
data = data.replace(/</g,"<").replace(/>/g,">").replace(/\n/g,"<br />").replace(/\r/g,"<br />");
var currentHTML = _("statusarea").innerHTML;
_("statusarea").innerHTML = '<div id="status_'+sid+'" class="status_boxes"><div><b>Posted by you just now:</b> <span id="sdb_'+sid+'">delete status</span><br />'+data+'</div></div><textarea id="replytext_'+sid+'" class="replytext" onkeyup="statusMax(this,250)" placeholder="write a comment here"></textarea><button id="replyBtn_'+sid+'" onclick="replyToStatus('+sid+',\'<?php echo $u; ?>\',\'replytext_'+sid+'\',this)">Reply</button>'+currentHTML;
_("statusBtn").disabled = false;
_(ta).value = "";
} else {
alert(ajax.responseText);
}
}
}
ajax.send("action="+action+"&type="+type+"&user="+user+"&data="+data);
window.alert("status passed 4");
}
newsfeed_system.php
if (isset($_POST['action']) && $_POST['action'] == "status_post"){
// Make sure post data is not empty
if(strlen($_POST['data']) < 1){
mysqli_close($db_conx);
echo "data_empty";
exit();
}
// Make sure type is a
if($_POST['type'] != "a"){
mysqli_close($db_conx);
echo "type_unknown";
exit();
}
// Clean all of the $_POST vars that will interact with the database
$type = preg_replace('#[^a-z]#', '', $_POST['type']);
$data = htmlentities($_POST['data']);
$data = mysqli_real_escape_string($db_conx, $data);
// Insert the status post into the database now
$sql = "INSERT INTO newsfeed(author, type, data, postdate)
VALUES('$log_username','$type','$data',now())";
$query = mysqli_query($db_conx, $sql);
$id = mysqli_insert_id($db_conx);
mysqli_query($db_conx, "UPDATE newsfeed SET osid='$id' WHERE id='$id' LIMIT 1");
mysqli_close($db_conx);
echo "post_ok|$id";
exit();
}
Ajax methods:
function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
Please help!
The ajax is not refrenced! You need to include the library or put the code for calling an 'ajaxObj'.

How to i get a specific value from a json encoded array?

Here is my JavaScript and my PHP for a dynamic ajax search. I am trying to get data from the database and display it in my DOM as a string.
javascript
var searchBox = document.getElementById("searchBox");
var searchButton = document.getElementById("searchButton");
var search = getXmlHttpRequestObject();
searchBox.addEventListener("keyup", ajaxSearch);
function getXmlHttpRequestObject(){
if(window.XMLHttpRequest){
return new XMLHttpRequest();
}
else if (window.ActiveXObject){
return new ActiveXObject("Microsoft.XMLHTTP");
}
else{
alert("Your browser does not support our dynamic search");
}
}
function ajaxSearch(){
var str = escape(document.getElementById('searchBox').value);
search.open("GET", '../searchSuggest.php?search=' + str, true);
search.send(null);
delay(displaySuggestions);
}
function displaySuggestions(){
var ss = document.getElementById("searchSuggestion");
ss.innerHTML = '';
string = search.responseText;
ss.innerHTML = string;
}
function delay(functionName){
setTimeout(functionName, 100);
}
function setSearch(x){
document.getElementById("searchBox").value = x;
document.getElementById("searchSuggestion").innerHTML = "";
}
searchBox.addEventListener('click', ajaxSearch);
window.addEventListener('click', function(){
document.getElementById('searchSuggestion').innerHTML = '';
});
php
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "Products";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$searchValue = $_GET['search'];
if(isset($searchValue) && $searchValue != ''){
$search = addslashes($searchValue);
$statement = $conn->prepare("SELECT Name FROM Product WHERE Name LIKE('%" . $search . "%') ORDER BY
CASE WHEN Name like '" . $search . " %' THEN 0
WHEN Name like '" . $search . "%' THEN 1
WHEN Name like '% " . $search . "%' THEN 2
ELSE 3
END, Name");
$statement->execute();
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($result);
echo $json;
}
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
What i want to know i how to get specific values from my response.
[{"Name":"iMac"},{"Name":"iPad 2"},{"Name":"iPhone 5"},{"Name":"iPhone 6"},{"Name":"iPod Touch"},{"Name":"iWatch"}]
For my search to work effectively i need it to display just the string of the product name and not the whole object.
Using a delay rather than the ajax callback is just shockingly prone to failure. Suppose your ajax call takes more than 100ms? It can totally happen. Similarly, why wait 100ms if your server is nice and fast and it finishes in 25?
Ditch the global search object, and change this:
function ajaxSearch(){
var str = escape(document.getElementById('searchBox').value);
search.open("GET", '../searchSuggest.php?search=' + str, true);
search.send(null);
delay(displaySuggestions);
}
to
function ajaxSearch(){
var str = escape(document.getElementById('searchBox').value);
var search = getXmlHttpRequestObject();
if (search) {
search.onreadystatechange = function() {
if (search.readyState == 4 && search.status == 200) {
displaySuggestions(JSON.parse(search.responseText));
}
};
search.open("GET", '../searchSuggest.php?search=' + str, true);
search.send(null);
}
}
Then displaySuggestions receives an array:
function displaySuggestions(results) {
// Use standard array techniques on `results`, e.g., `results[0]` is the first,
// maybe loop while `index < results.length`, maybe use `results.forEach(...)`...
}
Or taking it further, let's add a level of convenience there:
var failed = false;
function getXmlHttpRequestObject(done, failed){
var xhr;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject){
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
if (!failed) {
alert("Your browser does not support our dynamic search");
failed = true;
}
return null;
}
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200 {
if (done) {
done(xhr);
}
} else {
if (failed) {
failed(xhr);
}
}
}
};
return xhr;
}
Then:
function ajaxSearch(){
var str = escape(document.getElementById('searchBox').value);
var search = getXmlHttpRequestObject(function(xhr) {
displaySuggestions(JSON.parse(xhr.responseText));
});
if (search) {
search.open("GET", '../searchSuggest.php?search=' + str, true);
search.send(null);
}
}

span tag not working in online name checking using ajax

Here is my code in JavaScript that is calling check.php file for checking online existence of user in the database
<html>
<input type = "text" name="txt1" id="user" onKeyUp="check_username(this.value)"> <br>
<script>
var xmlhttp = false;
if (window.ActiveXObject) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} else {
xmlhttp = new XMLHttpRequest();
}
function check_username(str) {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var arr = xmlhttp.responseText.split("^");
document.getElementById("user").value = arr[1];
if (arr[0] == 1) {
</script>
<span style="color:blue">Username exists</span>
<script>
} else {
</script>
<span style="color:green">user available</span>
<script>
}
}
}
xmlhttp.open("GET", "check.php?txt1="+str, true);
xmlhttp.send();
}
</script>
</html>
And below is check.php file
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("check");
$username = ($_REQUEST['txt1']);
$a = 0;
if (checkexistence($username)) {
$a = 1;
echo $a."^".$username;
} else {
$a = 0;
echo $a."^".$username;
}
function checkexistence($username) {
$check = mysql_query("select uname from t1");
while ($row = mysql_fetch_array($check)) {
if (strcmp($username, $row['uname']) == 0) {
return true;
}
}
return false;
}
?>
It works correctly when I use alert (of course, we cannot use alert as it will become too irritating) but when I am using span tag it do not works correctly giving only
Username exists user available
as output instead of checking after each character we enter in the textfield..
How can I correct it??
Don't close and open the scripts in between of if else statements.
You can achieve this using jQuery library in easily. Download the jQuery library from here. You can include this jQuery files in bottom of the page, like this
<script src="js/jquery.1.11.0.js" type="text/javascript"></script>
Let's do that in different way of manner. Use jQuery method of after() to insert a content in between any where.
And try this code,
<input type = "text" name="txt1" id="user" onKeyUp="check_username(this.value)"> <br>
<span id="exist" style='color:blue'></span>
<span id="avail" style='color:green'></span>
<script>
var xmlhttp = false;
if (window.ActiveXObject) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} else {
xmlhttp = new XMLHttpRequest();
}
function check_username(str) {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var arr = xmlhttp.responseText.split("^");
document.getElementById("user").value = arr[1];
if (arr[0] == 1) {
$("#avail").html();
$("#exist").html('Username exists');
} else {
$("#exist").html();
$("#avail").html('User available');
}
}
}
xmlhttp.open("GET", "check.php?txt1="+str, true);
xmlhttp.send();
}
</script>

Categories