I want to insert a like into the database, but I want this on multiple pages. I crated a page where I insert the likes and I included this page on all the other pages.
It works, but now every time I like, the page is reloading. I thought I could fix this with AJAX, but I couldn't find a solution.
Index.php:
include_once('Post.php');
if(isset($_GET['postId'])) {
Post::likePost($_GET['postId'], $userId);
}
//Here sql to select postText, postId...
//Here echo the post
<form action="index.php?postId='.$postId.'" method="post">
<input type="submit" name="like" value="Like">
<input type="submit" name="unlike" value="Unlike">
</form>
Post.php:
class Post {
public static function likePost($postId, $likerId) {
//select database and check if user already liked post. If yes: -1 like if no: +1 like
}
}
Does anyone know if I can use AJAX to send the Post::likePost($_GET['postId'], $userId); so I can like a post without refreshing?
This is how you can try it. the code is well commented
<html><head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
type="text/javascript" charset="utf-8"></script>
<script>
$(document).ready(function(){
$(".like, .unlike").click(function(){
var postId= 1;
//var post1 = $('#postId').val();
var id_likeunlike = this.id; // Getting Button id for like or unlike
var userId= 101;
var datasend = "postId="+ postId + "&id_likeunlike=" + id_likeunlike + "&userId=" + userId;
// display a loading image when sending ajax request
$('#loader').fadeIn(400).html('<br><span class="well"><img src="loader.gif" align="absmiddle"> Please Wait, Your Data is being Submitted</span>');
$.ajax({
type:'POST',
url:'post.php',
data:datasend,
crossDomain: true,
cache:false,
success:function(msg){
$('#loader').hide();
alert('success');
$('#listpost').fadeIn('slow').prepend(msg);
}
});
});
});
</script>
</head>
<body>
<div id="loader"> </div>
<div id="listpost"> </div>
<input type="submit" id="like" class="like" name="like" value="Like">
<input type="submit" id="unlike" class="unlike" name="unlike" value="Unlike">
</body>
post.php
<?php
$postId = intval($_POST['postId']);
$id_likeunlike = strip_tags($_POST['id_likeunlike']);
$userId = strip_tags($_POST['userId']);
if($id_likeunlike=='like'){
echo "like success";
}
elseif($id_likeunlike=='unlike'){
echo "unlike success";
}
else{
echo "Error occured";
}
?>
Related
I am wanting to submit a form using ajax to go to my page 'do_signup_check.php'.
There it will check the email address the user entered against the database to see if there is a match.
If there is a match I want my ajax form to redirect the user to the login.php page.
If there isn't a match I want it to load my page 'do_signup.php'
for some reason the code seems to be doing nothing. Please can someone show me where I am going wrong?
My Ajax form:
<html lang="en">
<head>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"
async defer>
</script>
<?php include 'assets/config.php'; ?>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'do_signup_check.php',
data:{"name":name,"email":email},
success: function () {
if(result == 0){
$('.signup_side').fadeOut(500).promise().done(function() {
$('.signup_side').load('do_signup.php',function(){}).hide().fadeIn(500);
});
}else{
$('.signup_side').fadeOut(500).promise().done(function() {
$('.signup_side').load('login.php',function(){}).hide().fadeIn(500);
}
});
});
});
</script>
</head>
<body>
<div class="sign_up_contain">
<div class="container">
<div class="signup_side">
<h3>Get Onboard.</h3>
<h6>Join the directory.</h6>
<form id="signup" action="" method="POST" autocomplete="off" autocomplete="false">
<div class="signup_row action">
<input type="text" placeholder="What's your Name?" name="name" id="name" class="signup" autocomplete="new-password" autocomplete="off" autocomplete="false" required />
<input type="text" placeholder="Got an Email?" name="email" id="email" class="signup" autocomplete="new-password" autocomplete="off" autocomplete="false" required />
<div class="g-recaptcha" style="margin-top:30px;" data-sitekey="6LeCkZkUAAAAAOeokX86JWQxuS6E7jWHEC61tS9T"></div>
<input type="submit" class="signup_bt" name="submit" id="submt" value="Create My Account">
</div>
</form>
</div>
</div>
</div>
</body>
</html>
My Do_Signup_Check.php page:
<?php
session_start();
require 'assets/connect.php';
$myName = $_POST["name"];
$myEmail = $_POST["email"];
$check = mysqli_query($conn, "SELECT * FROM user_verification WHERE email='".$myEmail."'");
if (!$check) {
die('Error: ' . mysqli_error($conn));
}
if (mysqli_num_rows($check) > 0) {
echo '1';
} else {
echo '0';
}
?>
Try to use input id 'submt' to trigger the form as such :
$("#submt").click(function(){
e.preventDefault();
//your logic
You have not included the jquery in your page, the function is also missing the closing parentheses.
Include the jquery at the top
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Replace your function with the following code:-
<script>
$(function () {
$('form').on('submit', function (e) {alert(123);
e.preventDefault();
$.ajax({
type: 'post',
url: 'receive-callback.php',
data:{"name":name,"email":email},
success: function () {
if(result == 0){
$('.signup_side').fadeOut(500).promise().done(function() {
$('.signup_side').load('do_signup.php',function(){}).hide().fadeIn(500);
});
}else{
$('.signup_side').fadeOut(500).promise().done(function() {
$('.signup_side').load('login.php',function(){}).hide().fadeIn(500);
});
}
}
});
});
});
</script>
After receiving success in Ajax and doing all necessary logic (fadeOut etc) just relocate user to login.php:
window.location.href = 'path/to/login.php';
Otherwise, in error function (it is goes just after success function) do the next:
window.location.href = 'path/to/do_signup.php';
Upd:
In case you want to have some piece of code from another file, you can use jQuery method load.
$('#some-selector').load('path/to/course/login.php');
It's a very basic example of using 'load', go google around it to explore more.
Please Try this code.
$.ajax({
type: 'post',
url: 'do_signup_check.php',
data:{"name":name,"email":email},
success: function (result) {
if(result == 0){
window.location.href = 'do_signup.php';
}else{
window.location.href = 'login.php';
}
});
My Do_Signup_Check.php page:
<?php
session_start();
require 'assets/connect.php';
$myName=$_POST["name"];
$myEmail=$_POST["email"];
$check = mysqli_query($conn, "SELECT * FROM user_verification WHERE email='".$myEmail."'");
if (!$check) {
die('Error: ' . mysqli_error($conn));
}
if(mysqli_num_rows($check) > 0){
echo json_encode(array('result'=>'1'));
exit;
}else{
echo json_encode(array('result'=>'0'));
exit;
}
?>
I hope this will work for you.
i have two php files home.php and ajax.php. i have two buttons on home.php. when they are clicked the according php functions in ajax.php should get called.
home.php
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.min.js" type="text/javascript"></script>
<script type='text/javascript'>
$(document).ready(function(){
$('.button').click(function(){
var clickBtnValue = $(this).val();
var ajaxurl = 'ajax.php';
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function (response) {
// Response div goes here.
alert("action performed successfully");
});
});
});
</script>
</head>
<body>
<form action='ajax.php' method="POST">
<input type="submit" class="button" name="insert" value="insert" />
<input type="submit" class="button" name="select" value="select" />
</form>
</body>
</html>
ajax.php
<?php
echo 'this was called';
echo $_POST['action']; //THROWS AN ERROR undefined index 'action'
if ( isset( $_POST['action'] ) ) {
switch ($_POST['action']) {
case 'insert':
insert();
break;
case 'select':
select();
break;
}
}
function select() {
echo "The select function is called.";
exit;
}
function insert() {
echo "The insert function is called.";
exit;
}
?>
the problem is the json data i assign to data property in jquery code will not get passed to the ajax.php. Is there any reason why it doesn't not pass it?
here is my youtube video on the error video
There are two possibilities, depending of what you want to achieve afterwards.
Eighter you stick on doing a backgroud ajax-call to ajax.php and then do with the response whatever you want (that's what I'd suggest):
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.min.js" type="text/javascript"></script>
<script type='text/javascript'>
$(document).ready(function(){
$('.button').click(function(){
var clickBtnValue = $(this).id(); // changed to id here!
var ajaxurl = 'ajax.php';
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function (response) {
// Response div goes here.
console.log(response); // log what the response is
alert("action performed successfully and the resonse is: \n"+response);
// do with that data whatever you need
});
});
});
</script>
</head>
<body>
<!-- changed to buttons, removed the form -->
<button class="button" id="insert">insert</button>
<button class="button" id="select">select</button>
</body>
</html>
or you submit the form and output on screen the response from ajax.php:
<html>
<head>
<!--script src="https://code.jquery.com/jquery-2.1.4.min.js" type="text/javascript"></script-->
<script type='text/javascript'>
// no need for any javascript then
</script>
</head>
<body>
<form action='ajax.php' method="POST">
<input type="submit" class="button" name="insert" value="insert" />
<input type="submit" class="button" name="select" value="select" />
</form>
</body>
and in ajax.php:
<?php
echo 'this was called';
if ( isset( $_POST['insert'] ) ) {
insert();
}
if ( isset( $_POST['select'] ) ) {
select();
}
function select() {
echo "The select function is called.";
exit;
}
function insert() {
echo "The insert function is called.";
exit;
}
?>
try
$.post(ajaxurl, data)
.done(function( r ) {
alert("action performed successfully");
});
I like to use the jQuery on() and to be sure post has worked, I moved in your variables as such. Also you can try to do console.log(clickBtnValue) after the click to be sure you are able to see the value itself. After confirming, the post() should send that value into action post param.
<script type='text/javascript'>
$(document).ready(function(){
$('.button').on('click',function(){
var clickBtnValue = $(this).val();
var ajaxurl = 'ajax.php';
$.post(ajaxurl, {action:clickBtnValue}, function (response) {
alert("action performed successfully");
});
});
});
</script>
If you need to do a ajax call, remove the following part from the home.php
<form action='ajax.php' method="POST">
</form>
I think you are messed up with Ajax technology and the form post mechanism.
I am unable to send POST request to my php file using AJAX. I have two files, the first one is index.php and second isVerificationStatusAPIV2.php. Contents of index.php are:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Phone Verification by Dial2Verify API V2 ( www.dial2verify.com )</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
var attempt=1;
var transactionToken="";
$(document).ready(function(){
$("#enter_number").submit(function(e) {
e.preventDefault();
initiateDial2Verify();
});
});
function initiateDial2Verify() {
showCodeForm(1);
GetVerificationImage();
}
function showCodeForm(code) {
$("#dial2verify").fadeIn();
$("#enter_number").fadeOut();
$("#waiting_msg").text("Waiting for missed call from "+$("#phone_number").val());
}
function GetVerificationImage() {
$.post("GetImageAPIV2.php", { phone_number : $("#phone_number").val() },
function(data) { updateImage(data.img,data.transactionToken); }, "json");
}
function updateImage(img, vtransactionToken) {
$("#Image").html("Please give a missed call to <br><img src=\""+img+"\"/>");
transactionToken = vtransactionToken;
PollStart("0");
}
function CheckStatus()
{
$.post("VerificationStatusAPIV2.php", { transactionToken : transactionToken },
function(data) { PollStart(data.status); }, "json");
}
function PollStart(vStatus)
{
attempt =attempt+1;
if ( attempt >= 90 ) { TimeoutCheck(); }
else
if (vStatus === "0") {
$("#status").html("Please give a missed call in <b><i>"+(90-attempt) +"</i></b> seconds.");
setTimeout(CheckStatus, 1000);
}
else if (vStatus === "1")
{
success();
}
else
TimeoutCheck();
}
function Err() {
$("#status").html("Error!<br>Sorry something went wrong, Please cross check your telephone number.");
}
function success() {
$("#status").text("Congrats !!! Phone Number Verified!");
}
function TimeoutCheck() {
$("#status").text("Verification Failed!");
}
</script>
</head>
<body>
<form id="enter_number">
<p>Enter your phone number:</p>
<p><input type="text" name="phone_number" id="phone_number" /></p>
<p><input type="submit" name="submit" value="Verify" /></p>
</form>
<div id="dial2verify" style="display: none;">
<p id="waiting_msg"></p>
<p id="Image">Loading ..</strong></p>
<p id="status">Loading ..</strong></p>
</div>
</body>
</html>
In function CheckStatus() I am sending a post request using AJAX to file VerificationStatusAPIV2.php but it isn't making any post request. can someone tell what's wrong in that?
Update I just saw that "status" in "data.status" in func CheckStatus() is in yellow color while others in blue color. maybe thats the problem?
In your code snipped the only place you have CheckStatus exept for the function itselft is this line ... setTimeout(CheckStatus, 1000); so if this is the function call it'S should be like this : setTimeout(CheckStatus(), 1000);
This may be your problem.
Try changing
<input type="submit" name="submit" value="Verify" />
to
<input type="submit" id="btn_enter" name="submit" value="Verify" />
and in the js:
$("#btn_enter").submit(function(e) {
e.preventDefault();
initiateDial2Verify();
});
you were pointing your submit function to the HTML form's ID
var request=$.ajax({
method:"POST",
url:"VerificationStatusAPIV2.php",
data:{ transactionToken : transactionToken },
dataType:"json"
});
request.success(function(data){
PollStart(data.status);
});
i have created a simple html form with one field and it post to the server side php and the value of the field is saved to a text file.
This is the parts of the code:
Html:
<form action="videorefresh.php" method="POST">
<input name="videolink" type="text" size="70" />
<input type="submit" name="submit" value="Save Data">
</form>
php:
<?php
$open = fopen("video.txt","w+");
$txt = "video.txt";
if (isset($_POST['videolink'])) { // check if both fields are set
$fh = fopen($txt, 'a');
$txt=$_POST['videolink'];
fwrite($fh,$txt); // Write information to the file
fclose($fh); // Close the file
}
?>
here everythink works fine!
I want to drive all this through Ajax so the main html form wont refresh.
so here is the html:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="./JS/videolink.js"></script>
</head>
<body>
<div id="mainform">
<div id="form">
<div>
<input name="videolink" type="text" id="videolink" size="70">
<input id="submit" type="button" value="Submit">
</div>
</div>
</div>
</body>
</html>
And here is the js:
$(document).ready(function(){
$("#submit").click(function(){
var name = $("#videolink").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'videolink1='+ videolink ;
if(videolink=='')
{
alert("Please Fill All Fields");
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "./videorefresh.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
}
});
}
return false;
});
});
What i do wrong here and it doesnt work?
Please help
I think you want to do is:
var dataString = '?videolink='+ name;//typo videolink
// or better put an id on the form and use serialize()
// var dataString = $('#myform).serialize();
NOT
var dataString = 'videolink1='+ videolink ;
You have the value of the input in name, videolink is undefined
I have this code.
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<form action = "" method = "POST" id = "form">
<img src = "circle.gif" id="loading" style="display:none; "/>
<input type="text" name = "text2">
<input type="submit" name="submit2" value="Send">
</form>
<?
if (isset($_POST['submit2'])){
echo $_POST['text2'];
}
?>
<script>
$('#form').submit(function(e) {
$('#loading').show();
return false;
});
</script>
</body>
</html>
I want to store in my db the value written in the textbox using PHP, and while it's being saved, I want to show a gif using jQuery, once the page is loaded, this gif should be removed.
Then, If I don't comment nothing, gif appears when submit button is submitted but echo fails.
If I comment the jQuery script, PHP echoes the vale written.
If I comment the PHP script, gif is shown but no echo of course...
How could I do what i'm asking. I know that my full script does until only showing the gif, but this without this I can't continue.
You can achieve your desired behaviour, but you need to do it by submitting an AJAX request to the server and then handling the return value. So basically you'd add this ajax request to the click or submit event of the form, and handle the behaviour and request via javascript.
Perhaps something like this:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<form action = "formSubmitHandler.php" method = "POST" id = "form">
<img src = "circle.gif" id="loading" style="display:none; "/>
<input type="text" name = "text2">
<input type="submit" name="submit2" value="Send">
</form>
<script>
$(document).ready(function(){
$('#form').submit(function(){
// Show the loading icon before the processing begins
$('#loading').show();
// Send the query/form details to the server
jQuery.ajax({
data: $(this).serialize(),
url: this.action,
type: this.method,
success: function(results) {
// Now that the processing has finished, you
// can hide the loading icon
$('#loading').hide();
// perhaps display some other message etc
}
})
return false;
});
});
</script>
</body>
</html>