ajax like button success incorrect - php

I was making like button with php and ajax/jquery and it wont be reload when you click it will just reload the div but it reload the div but the number of like don't add
here my code.
<div id="Post-ImVi-Action">
<script>
$(document).ready(function () {
$('#Post-ImVi-Action-Like').click(function (e) {
e.preventDefault();
var name = $('#Like_Poster_name').val();
var email = $('#Like_Post_1').val();
$.ajax
({
type: "POST",
url: "php-SocialMedia-Posting-Like.php",
data: { "Poster_name": name, "Post_1": email },
success: function (data) {
$("#Post-ImVi-Action-Like").html(data);
}
});
});
});
</script>
<input type="Hidden" name="Poster_Name" id="Like_Poster_name" value="<?php echo $Post_Row["Poster_Name"];?>">
<input type="Hidden" name="Post_1" id="Like_Post_1" value="<?php echo $Post_Row["Post_1"];?>">
<input type="Hidden" name="ID" id="Like" value="<?php echo $Post_Row["ID"];?>">
<button id="Post-ImVi-Action-View">158K</button>
<button id="Post-ImVi-Action-Like" type="button" name="Like_Button" >
<?php
$Post = $Post_Row["Post_1"];
$Sql_like_count = "SELECT * FROM `likes` WHERE post = '$Post'";
$Result_like_Count = mysqli_query($conn, $Sql_like_count);
while ($ROW_LIKE = mysqli_fetch_array($Result_like_Count)) {
echo $ROW_LIKE['Likes'];
}
?>
</button>
<button id="Post-ImVi-Action-Share">815</button>
<div id="Post-ImVi-Action-Face"></div>
</div>
Here is php-SocialMedia-Posting-Like.php
<?php
include"php-MAIN-Info.php";
include"php-MAIN-SignUp+Database.php";
$Post = $_POST['Post_1'];
$Poster_Name = $_POST['Poster_Name'];
$Sql = "SELECT* FROM Likes WHERE Post = '$Post' AND Poster_Name = '$Poster_Name'";
$Like_Result = mysqli_query($conn, $Sql);
while ($Like_Row = mysqli_fetch_array($Like_Result)) {
$Like_Add = $Like_Row['Likes'] + '1';
$Sql_Like_Add = "UPDATE Likes SET Likes = '$Like_Add' WHERE Post = '$Post' AND Poster_Name = '$Poster_Name';";
$Like_Result_Add = mysqli_query($conn, $Sql_Like_Add);
if ($Like_Result_Add) {
echo $Like_Add;
}
}
update:
i found a error
php-Home-MSOHome.php:352 Uncaught ReferenceError: data is not defined
please try to help cause i'm new to this web.Thanks
why is no one answering my question you k i'm still looking for the answers

I did it its a php error udfinde Poster_name its Poster_Name

Related

HTML AJAX not executing PHP

I am really new to AJAX/jQuery and PHP, and im trying to work on a little project that writes your daily weight to a Db which then is displayed later on with graphs etc.
I would like when the user submits the form for his or her weight that it displays a pop up message but for whatever reason, the AJAX/Jquery script doesn't seem to be doing anything with the php file therefore no info gets added into the database.
Here is the HTML Form: (index.html)
<form id="ajax-form" method="post" action="connection.php">
<div class="columns field">
<div class="column control is-half is-offset-one-quarter">
<input
class="input"
id="weight"
name="weight"
type="text"
placeholder="Enter your weight for the day"
/>
</div>
</div>
<div class="center-test">
<div class="field">
<div class="control">
<span class="select">
<select name="person">
<option value="Ayush">Ayush</option>
<option value="Sheri">Sheri</option>
</select>
</span>
</div>
</div>
</div>
<input type="date" name="weightdate" id="weightdate" />
<div class="field column is-half is-offset-one-quarter">
<button
type="submit"
id="submit"
name="submit"
class="button is-primary"
>
Submit
</button>
</div>
</form>
<div id="error_message" class="text-danger"></div>
<div id="success_message" class="text-success"></div>
AJAX/jQuery: (inside index.html )
$(document).ready(function () {
$("#submit").click(function (e) {
e.preventDefault();
var weight = $("#weight").val();
var person = $("#person").val(); // You miss this
var weightdate = $("#weightdate").val(); // You miss this
if (weight == "" || person == "" || weightdate == "") {
$("#error_message").html("All Fields are required");
} else {
$("#error_message").html("");
$.ajax({
url: "connection.php",
method: "POST",
data: {
weight: weight,
person: person, // Add this
weightdate: weightdate, // Add this
},
success: function (data) {
$("form").trigger("reset");
$("#success_message").fadeIn().html("data");
setTimeout(function () {
$("#success_message").fadeOut("Slow");
}, 2000);
},
});
}
});
});
PHP: (connection.php)
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
include_once 'dbconnect/db_info.php';
$weight = $_POST['weight'];
$person = $_POST['person'];
$date = $_POST['weightdate'];
$formatDate = date("d/m/y", strtotime($date));
//echo $formatDate;
if(date("m", strtotime($date)) == date("01")) {
$sql = "INSERT INTO WeightTracker (person, kg, weight_date, date_month) VALUES ('$person', '$weight', '$formatDate', 'January');";
#$result = mysqli_query($conn, $sql);
$result = mysqli_query($conn, $sql);
}
elseif(date("m", strtotime($date)) == date("04")) {
//echo working;
$sql = "INSERT INTO WeightTracker (person, kg, weight_date, date_month) VALUES ('$person', '$weight', '$formatDate', 'April');";
#$result = mysqli_query($conn, $sql);
$result = mysqli_query($conn, $sql);
}
else {
$sql = "INSERT INTO WeightTracker (person, kg, weight_date) VALUES ('$person', '$weight', '$date');";
#$result = mysqli_query($conn, $sql);
$result = mysqli_query($conn, $sql);
}
Does anyone have any ideas? When I remove the AJAX/jQuery code, the form successfully submits and the connection.php writes to the database with no issues.
Most of the problem was resolved in comments. The problem (as described in the comments) was a PHP error Undefined index on this line:
$person = $_POST['person'];
As I mentioned in an earlier comment: your person input is missing the expected person ID. That means this Javascript:
var person = $("#person").val();
Is actually undefined, so there is no person field POSTed to your PHP, so when you try to use it as $_POST['person'], you'll get an error.
To fix that, just add the id your Javascript is using to find the person:
<select name="person" id="person">
The data you give for the POST request is just weight, there is no person and weightdate data.
var weight = $("#weight").val();
var person = $("#person").val(); // You miss this
var weightdate = $("#weightdate").val(); // You miss this
if (weight == "" || person == "" || weightdate == "") {
$("#error_message").html("All Fields are required");
} else {
// Your code :)
}
And the data,
$.ajax({
url: "connection.php",
method: "POST",
data: {
weight: weight,
person: person, // Add this
weightdate: weightdate // Add this
},
success: function(data) {
$("form").trigger("reset");
$("#success_message")
.fadeIn()
.html("data");
setTimeout(function() {
$("#success_message").fadeOut("Slow");
}, 2000);
}
});
Your Problem lies here.
include_once 'dbconnect/db_info.php';
Change it to something like
realpath('__DIR__'.'/dbconnect/db_info.php');
Hopefully it will solve your problem.

Pop-up message after submitting a form with php

I'm trying to get a pop-up message saying if it was successfully submitted or not without having to go to a different page.
Now chrome gives me the pop-up message but it redirects me to a blank page after.
Here is my current code.
<?php
include "header.php";
include "conexao.php";
echo "<h1 align='center'>Pagina para alterar produtos</h1><div class='container'><hr>";
$referencia=$_GET['id'];
$sql = "SELECT * ";
$sql = $sql . " FROM tb_produto ";
$sql = $sql . " WHERE pr_codigo='".$referencia."'";
$produtos = $db->query($sql);
foreach ($produtos as $produto) {
$referencia = $produto["pr_codigo"];
$nome = $produto["pr_descricao"];
$preco = $produto["pr_preco"];
$disponivel = $produto["disponivel"];
}
echo "<h2>Referencia: ".$referencia."</h2>";
echo "<h2>Nome: ".$nome."</h2><hr>";
?>
<form action="confirmaAlterar.php">
<div class="form-group">
<label>Referencia</label>
<input class="form-control" type="text" name="referencia" value="<?php echo $referencia?>">
</div>
<div class="form-group">
<label>Nome</label>
<input class="form-control" type="text" name="nome" value="<?php echo $nome?>">
</div>
<div class="form-group">
<label>Preço</label>
<input class="form-control" type="text" name="preco" value="<?php echo $preco?>">
</div>
<button class="btn btn-primary">Alterar</button>
</form>
Here is where it submits the information of the form.
<?php
include "header.php";
include "conexao.php";
$nome=$_GET['nome'];
$referencia=$_GET['referencia'];
$preco=$_GET['preco'];
$sql="UPDATE tb_produto SET pr_descricao='".$nome;
$sql.="', pr_preco=".$preco;
$sql.= " WHERE pr_codigo='".$
try{
$comando=$db->prepare($sql);
$comando->execute();
echo "<script type='text/javascript'>alert('submitted successfully!')</script>";
header( "refresh2;Location:index.php" );
}
catch (PDOException $e){
echo "A";
}
To pass values using ajax. Form:
<form id="form">
<input type="text" value="test" name="akcija">
</form>
All inputs fields values in your form will be passed.
Ajax:
jQuery(function(){
$('#form').on('submit', function (e) { //on submit function
e.preventDefault();
$.ajax({
type: 'post', //method POST
url: 'yoururl.php', //URL of page where u place query and passing values
data: $('#form').serialize(), //seriallize is passing all inputs values of form
success: function(){ //on success function
$("#input").attr("disabled", true); //example
$("#input").removeClass('btn-primary').addClass('btn-success');//example
},
});
}
});
And on the ajax page you can get values by
$akcija = $_POST['akcija']
for this Problem you must use ajax method .
1- create html form and all input Required .
<form id="contactForm2" action="/your_url" method="post">
...
</form>
2- add jQuery library file in the head of html page .
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
...
3- add this method Under the jQuery library
<script type="text/javascript">
var frm = $('#contactForm2');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
if(data == 'pass')
alert('ok');
else(data == 'fail')
alert('no');
}
});
ev.preventDefault();
});
</script>
4- in your_url .php file
<?php
$a = ok ;
if( $a == 'ok' ){
echo 'pass';
}else{
echo 'fail';
}
?>
this top answer is easy management form with jquery , but you need managment Complex form better use this library http://jquery.malsup.com/form/

Pagination with search function

What I'm trying to do is make a search page where the result would be on the same page. My concept is to first show all data and then there will be one textbox and one submit button. Below that, I will show the result which is paginated. How do I achieve that?
<input type ="text" placeholder = "search" name = "search">
<input type ="submit" name = "submit">
<?php
if(isset($_POST['submit']))
$search = $_POST['search'];
{
$query = "SELECT * FROM table WHERE search = '$search' ";
$result = mysql_query($query) or die (mysql_error());
while($row = mysql_fetch_array($result))
{
//echo my result here.
}
}
Take a look at jquery and ajax. I did something similar as a test awhile back:
var request = $.ajax({
type: "GET",
url: url,
data: $(".form-wrapper").serialize()
});
request.done(function(data) {
if (data.search("No results") == -1) {
$("#result").show();
$("#result").html(data);
} else {
$('#result').html('').hide();
}
});
request.fail(function(jqXHR, msg) {
alert(msg);
});
<form class="form-wrapper cf">
<input type="text" id="text" name="q" placeholder="" required>
<button type="submit" disabled>Search</button>
</form>
<div id="result"></div>

AJAX jQuery php Login form

hello i have a little bit of a trouble finding a specific answer so .. i hope this is not a repost, i have the following login.php code
function loginBackUser($arr){
global $link;
extract($arr);
$msg = '';
$pass = md5($pass);
$pass = md5($pass);
$pass = sha1($pass);
$pass = md5($pass);
$pass = md5($pass);
$pass = sha1($pass);
$pass = sha1($pass);
$pass = sha1($pass);
$sql = "SELECT * FROM `table` WHERE `email`='$email' AND `pass`='$pass'";
$sqlEmail = "SELECT * FROM `table` WHERE `email`='$email'";
$resEmail = mysqli_query($link,$sqlEmail) or die("SQLEmail gresit");
$res = mysqli_query($link,$sql) or die("SQL gresit");
if(mysqli_num_rows($res) == 1){
$row = mysqli_fetch_assoc($res);
session_start();
$id=$row['id'];
$_SESSION['id'] = $row['id'];
$_SESSION['name'] = $row['name'];
$sqlEmptyAttempts = "UPDATE `table` SET `attempts` = '0' WHERE `id` = '$id'";
$resEmptyAttempts = mysqli_query($link,$sqlEmptyAttempts) or die("SQLEmptyAttempts gresit");
header('Location:/oproit/index.php?pag=dash_homepage');
}else if(mysqli_num_rows($resEmail) == 1){
$row2 = mysqli_fetch_assoc($resEmail);
$id=$row2['id'];
$sqlVerifyAttempts = "SELECT `attempts` FROM `table` WHERE `id` = '$id'";
$resVerifyAttempts = mysqli_query($link,$sqlVerifyAttempts) or die("SQLVerifyAttempts gresit");
$row3 = mysqli_fetch_assoc($resVerifyAttempts);
if($row3['attempts']<3){
$attempts = $row3['attempts']+1;
$sqlSetNewAttempts = "UPDATE `table` SET `attempts` = '$attempts' WHERE `id` = '$id'";
$resSetNewAttempts = mysqli_query($link,$sqlSetNewAttempts) or die("SQLSetNewAttempts gresit");
echo "wrong password";
}else{
$sqlEmptyAttempts = "UPDATE `table` SET `attempts` = '0' WHERE `id` = '$id'";
$resEmptyAttempts = mysqli_query($link,$sqlEmptyAttempts) or die("SQLEmptyAttempts gresit");
echo "dude be serious"; // here will be some mail function but for now i just want it to work with ajax
}
}else{
echo "your email is not in our data base";
}
$thread_id = mysqli_thread_id($link);
mysqli_kill($link,$thread_id);
mysqli_close($link);
}
i would like it to be accessed by axaj, and my "echos" to be inside a previously empty div, the login form html page
<form id="loginUser" method="post" action="login.php" onsubmit="return false;">
<input type="text" id="email" name="email" class="textField" value="email" />
<input type="password" id="pass" name="pass" class="textField" value="" />
<input type="submit" id="loginUserSubmit" onclick="isSession('loginUser','resultShow')" name="loginUserSubmit" value="Da Bah!" /></form><div id="resultShow">sas</div>
my so far javascript is
function isSession(selector,responseElement) {
var e = document.getElementById(selector);
if(!e){
alert('there is no element with the id='+selector);
}
var b = document.getElementById(responseElement);
if(!b){
alert('there is no element with the id='+responseElement);
}
$(e).submit(function (event) {
$.ajax({
type: $(e).attr('method'),
url: $(e).attr('action'),
data: $(e).serialize(),
success: function(data){
$(b).html(data);
},
error: function() {
alert("Error occured")
}
});
event.preventDefault();
});
}
but it does nothing .. i need when the user clicks the login button and gets only the pass wrong .. to let him be wrong for three times .. but at every turn tell him . in that empty div .. that he was wrong...
Do you know what i mean?
The problem is on your PHP (login.php).
You should remove the function loginBackUser: you're not calling that method.
And change the extract method on login.php to extract($_POST).
e.g.:
<?php
if (isset($_POST['pass']) && isset($_POST['email'])) {
global $link;
extract($_POST);
...
}
EDIT
This isn't the best way to make a login system, I hope you are just studying/testing :)
so ... in stead of using ajax which i don't know that well, i made something that might be called unprofessional by others, which is <div id="resultShow">
<?php
if(isset($_POST['loginUserSubmit'])){
require_once('/path/to/Class.BackUser.php');
$bkUser = new BackUser();
$bkUser->loginBackUser($_POST);
}
?>
</div>
and this way .. whatever the method loginBackUser() echos, is in the place that i wanted it to be, but i would still like with your help, if you will, to find a way to skip that refresh php needs to do everything :D
I'm not sure how you handle the server side validation but I simplified your code just to make a small demonstration of ajax get/post on same page. This is just an example and can be done in many other ways.
From .serialize() documentation:
No submit button value is serialized since the form was not submitted
using a button.
Here's the full code I came up with
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<?php
if(isset($_POST["email"]) && isset($_POST["pass"]))
{
echo "Email:".$_POST["email"]."<br/>Password:".$_POST["pass"];
}
else
{
?>
<form id="loginUser" method="post" action="login.php">
<input type="text" id="email" name="email" class="textField" value="email" />
<input type="password" id="pass" name="pass" class="textField" value="" />
<input type="submit" id="loginUserSubmit" name="loginUserSubmit" value="Da Bah!" />
</form><div id="resultShow"></div>
<script>
$(document).ready(function(){
$("#loginUser").submit(function (event) {
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(data){
$("#resultShow").html(data);
},
error: function() {
alert("Error occured")
}
});
event.preventDefault();
});
});
</script>
<?php
}
?>
</body>
</html>
You should make a reference to jQuery library with
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
Always better to wrap your script in $(document).ready() function like this
$(document).ready(function()
{
//your code here
}
);
In your case, it's as follows
$(document).ready(function(){
$("#loginUser").submit(function (event) {
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(data){
$("#resultShow").html(data);
},
error: function() {
alert("Error occured")
}
});
event.preventDefault();
});
});
On server-side there are many ways to see if the form was posted or not. Simply use
if(isset($_POST["email"]) && isset($_POST["pass"]))
and wrap your logic in it. If the form was not submitted do something else.
Give this a try and if that works, implement the validations along with extras on the working version.

Ajax Id Auto Incrementing

I will probably sound or look dumb by this but I need to learn. Check out the following part of a code:
$('.buttonclass').click(function(){
var button_id = $(this).attr('id');
$('#'+button_id).click(function(){
var yes = $("input#yes").val();
if (yes == "") {
return false;
}
var id = $("input#id").val();
if (id == "") {
return false;
}
var dataString = 'yes='+ yes + '&id=' + id;
//try insted this //alert (dataString);return false;
$.ajax({ type: "POST", dataType:'HTML',
//or the appropiate type of data you are getting back
url: "http://www.edshaer.com/EdinburgCISD/Gorena/Gorena.php", data: dataString,
//in the php file do $email = $_POST['email'];
//not a good practice but you can try with it and without it
success: function(data) {
$("#div").hide(data).fadeOut();
$("#div").html(data);
$("#div").show(data).fadeIn();
// Change the content of the message element
// Fade the element back in
} });
//ajax ends
return false; });
//click ends
});//document ready ends
My button ID that is being submitted in my html page is sending random numbers. For example
It can be:
$("#383").click(function() {
or it can be:
$("#521").click(function() {
My question is, how do I do it to auto increment the ID of the button clicked so that no matter what ID number is clicked it will still run the run the code smoothly... Right now I have this:
$('.buttonclass').click(function(){
var button_id = $(this).attr('id');
$('#'+button_id).click(function(){
Hopefully someone can help me... let me know if you need more info... Thank you in advanced...
Here is part of my HTML code... Hopefully it will be a little more understandable...
<?php
$data3 = mysql_query("SELECT * FROM `EdinburgCISDGorenamessage`
ORDER BY `ID` DESC LIMIT 0, 100")
or die(mysql_error());
echo "<div id=\"div\"> <table align=\"center\" width=\"570\">";
while($info3 = mysql_fetch_array( $data3 ))
{
$id = $info3['ID'];
}
?>
<form name="contact" id="post" method="post" action="">
<input id="id" value="<?php echo $id?>"/>
<input type="submit" class="buttonclass" id="<?php echo $id?>" name="<?php echo $id?>" value="Yes" />
<input type="submit" id="no<?php echo $id ?>" name="no<?php echo $id ?>" value=" No " /> </form>
I don' want to provide the whole code because its too messy and it doesn't go with the question... Let me know if you need anything else.
Use a class instead. Add a class to the button, and an incremental id you give it while printing it out in your html (I suppose you echo buttons in a loop?), and then just use one snippet:
$('.buttonclass').click(function(){
var button_id = $(this).attr('id');
$('#'+button_id).click(function(){
// your function here
alert(button_id); // just to see if ID is retrieved
)};
});
So, if you have
<button id="325" class="buttonclass" type="button">BUTTON 325</button>
<button id="150" class="buttonclass" type="button">BUTTON 150</button>
The ID of the button you click is retrieved only when you press it

Categories