i want to make like/unlike system with PHP and jQuery/AJAX..
Here is my form in PHP foreach... Here i have own id's for every form;
<?php foreach ($vid as $var) { ?>
<form class="classform" action="functions/videolike.php" method="post">
<input type="text" name="id" value="<?php echo $var['video_id'];?>">
<button class="submitbuttonclass"type="submit">Like</button>
</form>
<?php } ?>
Here is my Ajax script;
<script>
// this is the id of the submit button
$(".submitbuttonclass").click(function() {
$.ajax({
type: 'post',
url: "functions/videolike.php",
data: $(".classform").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
</script>
the codes are working but not correctly;
When i click "like" button is working good, i cheked the database, caunting, inserting, deleting , working good...
But I want to make this with AJAX becouse, refreshing page is stopping the video when user watching video if he click the like button. Video is preloading becouse page refresh...
After i add my ajax script its working. But when i am clicking the like button, AJAX is posting to PHP, only the last id in the foreach loop,
THE Question?
How to make AJAX to get all of the id's in PHP foreach loop ??
And this is my videolike.php if you want to check;
<?php
session_start();
if($_POST['id'] && #$_SESSION["userid"]){
require_once "connectdb.php";
$id = $_POST["id"];
$VLcheck = "SELECT count(*) FROM `videolikes` WHERE user_id = ? AND liked_vid_id=?";
$reslike = $conn->prepare($VLcheck);
$reslike->execute(array($_SESSION["userid"],$id));
$VLrow = $reslike->fetchColumn();
echo $VLrow;
if ($VLrow > 0){
$VLcheck = "DELETE FROM `videolikes` WHERE user_id = ? AND liked_vid_id=?";
$reslike = $conn->prepare($VLcheck);
$reslike->execute(array($_SESSION["userid"],$id));
} else {
$curentsess= $_SESSION["userid"];
$INSlike = $conn->prepare("INSERT INTO videolikes(user_id, liked_vid_id)
VALUES('$curentsess','$id')");
$INSlike->execute();
}} else {die;}
?>
As you have a lot forms with class .classform, so how do you think your script should select the proper one?
The asnwer is - script can't, you should help it). Use .closest function to find closest <form> for a clicked button:
$(".submitbuttonclass").click(function() {
var form = $(this).closest("form");
// or find closest element with class `classform`
//var form = $(this).closest(".classform");
$.ajax({
type: 'post',
url: "functions/videolike.php",
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
Related
Following is the code I used to print the delete button for each data echoed.
<?php
$sno=1;
while($row=mysqli_fetch_assoc($datas)){
echo('<b><tr><td>'.$sno.'</td><td>' .$row['id'].'</td>
<td>'.$row['name'].'</td>
<td>'.$row['address'].'</td>
<td>'.$row['faculty'].
"</td><td>
<button onclick=deletee(); name='del_user' value='<?= $row['id']; ?>'> Delete </button><br>
</td></tr>");
++$row;
$sno++;
}
?>
In script;
function deletee() {
<?php
$datas="";
$sql="";
$idd=$row['id'];
$datas=mysqli_query($database,"SELECT*FROM data");
if(isset($_POST['delete_user'])){
$newrow=mysqli_fetch_assoc($datas);
if($newrow['id']==$idd)
{
$sql = "DELETE FROM data WHERE id='$idd' ";
mysqli_query($database,$sql);
header("Location: main.php");
}
}
?>
}
Yet I'm not able to delete a specified tuple. Whats the problem?
I'm trying to delete a row.
"After every data row is a delete button which deletes a specific row."
A better option to your above would be to create your button as
<button onclick=deletee(<?=Row['id'] ?>)
From there your function would be
function deletee(int id){
var url = "/Url/Where/PHP/is/run"
$.ajax({
url: url,
type: "post",
data: { id = id },
success: function (response) {
// Redirect to a page, or update whats displayed on the page here
},
error: function(jqXHR, textStatus, errorThrown) {
// do your error logging / display to page here
}
});
Now you just create a page to run the delete via your php and make sure the url in the ajax function points to that page, and it accepts a field called "id" (Note, this is using as a "POST", you can change to get etc. just make sure you do some checking on the data sent through.
If you don't want to use jquery at all, an alternative would be to make every lineitem a form pointing to the same url with a different value i.e.
//line item details Here
// where the submit button is use the code below instead
<form action="url/with/php/code" method="post">
<input type="hidden" name="id" value="<?= $row['id']?>" />
<input type="submit" value="delete">
</form>
Then have the php form it directs to check for post values, and redirect on success / do what it needs to do on failure
I have the following problem:
What i'm trying to accomplish is:
User clicks on a submit/image type button
Ajax call handles the submit, calls another PHP script to update a record in a MySQL table, all without reloading the page ( obviously )
My PHP code is working fine without the AJAX, as it will reload and update the record. but somehow the ajax call is not working and/or returning any error.
My code:
$(function() {
$('#like_form').submit(function(event) {
event.preventDefault(); // Preventing default submit button
var formEl = $('#like_form');
var submitButton = $('input[type=submit]', formEl);
$.ajax({
async: true,
type: 'POST',
url: formEl.prop('action'),
accept: {
javascript: 'application/javascript'
},
beforeSend: function() {
submitButton.prop('disabled', 'disabled');
}
}).done(function(data) {
submitButton.prop('disabled', false);
$("#like").fadeOut();
$("#like").fadeIn();
});
});
});
<!-- LIKE een gebruiker -->
<form action="" id="like_form" method='POST' enctype="multipart/form-data">
<input onmouseover="this.src='img/heart2.png'" onmouseout="this.src='img/heart.png'" name='like' id="like" src='img/heart.png' type="image" />
</form>
my PHP (just in case):
<?php
include_once "dbconnection.php";
//if like button (submit button) clicked
if ($_POST){
$conn = DatabaseConnection::getConnection();
$sql = "UPDATE dating_members
SET likes = likes + 1
WHERE member_id = 3";
$stmt = $conn->prepare($sql);
$stmt->execute();
}
?>
I figured out what the problem is, Kind of silly I didn't notice but better late than never.
I had to 'include' the JS script at the end of my PHP page in order to catch my onsubmit function and therefore disable the default event a.k.a submit button submitting my form and page reload / POSTs to the other PHP file.
Everything is working fine now
I have a modifypassword form that modifys the password in a flat file for a user.( I know its not safe etc. ).
So the thing is: whenever I click on modify password on my website, I get a prompt that asked to enter a new password. All fine, after that it will submit the form. But I cannot get the variable somehow that is typed in. I want to $_GET['newpw'] so I can use it to adjust my flat file.
So I have a form like this:
echo "<td> <form action=\"admin.php\" method=\"GET\" onsubmit=\" modifyPassword();\">
this is the modifyPassword function:
<script type="text/javascript">
function modifyPassword() {
var newpw=prompt("Enter a new password");
if(newpw !== null) {
$.ajax({
type: "GET",
url: "admin.php",
data: {data: newpw},
success: function(data) {
console.log(data);
}
});
}
}
</script>
And when the form is actually submitted I want to get the value from what is typed in like this:
echo $_GET['data'];
This is all in the same file.
The output of $_GET['data'] does not show anything.
The rest just works fine when I choose a static password like: "test". It will update my flat file, but I want to get the user input to change the password.
Can someone tell me what i am doing wrong?
I think the base problem may be, that you have event handler onsubmit, but the form gets submited anyway. So the actual prompt has no chance to execute.
You should add return false; or manage the logic in modifyPassword() method.
For example this may help to stop form to submit:
echo "<td> <form action=\"admin.php\" method=\"GET\" onsubmit=\"modifyPassword(); return false;\">"
OR
If you want to submit the form in standard way, just to change the password, just change the input value.
Modify form: echo "<td> <form action=\"admin.php\" method=\"GET\" onsubmit=\"modifyPassword(this)\"><input type=hidden name=newpw />"
And then change the javascript:
<script type="text/javascript">
function modifyPassword(passForm)
{
var newpw = prompt("Enter a new password");
if (newpw !== null)
{
passForm.newpw.value = newpw;
}
}
</script>
Then you should have the value in php in $_GET['newpw'].
Your current PHP code:
}elseif (isset($_GET['Modify'])){ echo $_GET['data'];
But according to the Ajax request code, you don't send a Modify parameter so the $_GET['Modify'] isn't set and therefore the condition returns false and never reach to the echo $_GET['data'] part.
You need to add another parameter to the data as in the following:
JS
<script type="text/javascript">
function modifyPassword(){
var newpw=prompt("Enter a new password");
if(newpw !== null){
$.ajax({
type: "GET",
url: "admin.php",
data: {action: 'modifypass', data: newpw}, //Added another parameter.
success: function(data)
{
console.log(data);
}
});
}}
</script>
PHP
elseif (isset($_GET['action']) && $_GET['action'] == "modifypass"){
echo $_GET['data'];
bit of a selfish question but I am really strugerling with ajax in general so I need some help. So basically Im trying to update and sql database using an 'onblur' function. heres my code:
code on index.php
function saveStatus(){
var status =document.getElementById("statusForm").value;
$.ajax({
url: 'saveStatus.php',
type: 'post',
data: 'feed_id=' + status,
success: function(result){
}
}
<form id="statusUpdate" action = "whosout.php" method="post">
<input type="text" id="statusForm" onblur="saveStatus()"
placeholder="<?php if($status!=null){ echo '‘'.$status.'’';}
else { echo 'Enter your status here.';}?>">
</form>
and code on saveStatus.php
<?
require 'core.php';
require 'connect.php';
$status = $_POST['feed_id'];
$idPerson = $_SESSION['user_id'];
$query = "UPDATE person SET status = '".mysql_real_escape_string($status)."'
WHERE idPerson = '$idPerson'";
$query_run = mysql_query($query);
?>
at the moment the sql database does not update when i click of the input box. Any help would be great!!
Answer:
You have to devide scripts and html output
You forget );.You have to close $.ajax block.
You miss } closing function saveStatus().
Code:
<script>
function saveStatus(){
var status =document.getElementById("statusForm").value;
$.ajax({
url: 'saveStatus.php',
type: 'post',
data: 'feed_id=' + status,
success: function(result){
}
}); // <-- Also, you forget `);` here
} // <-- Also, you foget closing `}` here
</script>
<form id="statusUpdate" action = "whosout.php" method="post">
<input type="text" id="statusForm" onblur="saveStatus()"
placeholder="<?php if($status!=null){ echo '‘'.$status.'’';}
else { echo 'Enter your status here.';}?>">
</form>
Not error, but advice:
Also, note this: you used jQuery ajax function, so use jQuery in other cases too (you used pure JavaScript instead).
You getting value this way:
var status = document.getElementById("statusForm").value;
Use jQuery syntax instead:
var status = $("#statusForm").val();
Additional info
As, #Utkanos noticed in comments to this answer:
...all of which would be obvious if you look in the error console.
You have to use some debug tool, like FireBug or DevTools (Chrome, also in Chrome you can use CTRL+SHIFT+J). Not have to. You MUST do it.
Hi I am adding dynamic validation to a form on my webpage to stop unnecessary page reloads. The form is for registring an account, and I want to be able to check if the username that the user selects is already taken, however as far as I know I can only retrieve data from mysql in php. How should I go about this?
Use PHP to load a list of existing users into an array when the registration page loads and then use that array to do the Javascript validation.
you can using ajax.
this is function in php:
function check_registration() {
if ($_POST['val']) {
$query = "select user from member where user = '" . $_POST['val'] . "'";
$row = $this->countRow($query);
if ($row > 0) {
echo "user has been taken";
}
}
}
and this is ajax that u can put in html
<script>
$(document).ready(function(){
$('#input1').keyup(function(){
var values = $('#input1').val();
var dataString = 'val='+ values;
$.ajax
({
type: "POST",
url: "http://localhost/authentication/check",
data: dataString,
cache: false,
success: function(html)
{
$("#error1").html(html);
}
});
});
});
</script>