Ajax PHP Follow Script - Nothing stored in the database - javascript

I recently discovered a treehouse blog on ajax for beginners http://blog.teamtreehouse.com/beginners-guide-to-ajax-development-with-php I've been looking for a follow script for a while and I've hit a dead end. Currently the follow button fades as it should do, yet no values are stored in the database as of yet.
Profile.php (follow button):
<div id="followbtncontainer" class="btncontainer">Follow</div>
Ajax.js
$(function(){
$('#followbtn').on('click', function(e){
e.preventDefault();
$('#followbtn').fadeOut(300);
$.ajax({
url: '../ajax-follow.php',
type: 'post',
data: {'action': 'follow'},
success: function(data, status) {
if(data == "ok") {
$('#followbtncontainer').html('<p><em>Following!</em></p>');
var numfollowers = parseInt($('#followercnt').html()) + 1;
$('#followercnt').html(numfollowers);
}
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
}
}); // end ajax call
});
$('body').on('click', '#morefllwrs', function(e){
e.preventDefault();
var container = $('#loadmorefollowers');
$(container).html('<img src="images/loader.gif">');
var newhtml = '';
$.ajax({
url: 'ajax-followers.php',
type: 'post',
data: {'page': $(this).attr('href')},
cache: false,
success: function(json) {
$.each(json, function(i, item) {
if(typeof item == 'object') {
newhtml += '<div class="user"> <img src="'+item.profile_pic+'" class="avi"> <h4>'+item.username+'</h4></div>';
}
else {
return false;
}
}) // end $.each() loop
if(json.nextpage != 'end') {
// if the nextpage is any other value other than end, we add the next page link
$(container).html('Load more followers');
} else {
$(container).html('<p></p>');
}
$('#followers').append(newhtml);
},
error: function(xhr, desc, err) {
console.log(xhr + "\n" + err);
}
}); // end ajax call
});
});
ajax.php
<?php require 'database.php' //<?php include 'session-check-index.php' ?>
<?php include 'authentication.php' ?>
<?php
session_start();
$follower=$_SESSION['id'];
$sql = "SELECT * FROM users WHERE username='$username'";
$result = mysqli_query($database,$sql);
$rws = mysqli_fetch_array($result);
$following=$rws['id'];
/**
* this script will auto-follow the user and update their followers count
* check out your POST data with var_dump($_POST)
**/
if($_POST['action'] == "follow") {
$sql=" INSERT INTO `user_follow` (`follower`, `following`, `subscribed`) VALUES ('$follower', '$following', CURRENT_TIMESTAMP);"
/**
* we can pass any action like block, follow, unfollow, send PM....
* if we get a 'follow' action then we could take the user ID and create a SQL command
* but with no database, we can simply assume the follow action has been completed and return 'ok'
**/
mysqli_query($database,$sql) or die(mysqli_error($database));
}
?>
I'm not sure if the actual $following and $follower values are causing the problem, and just not passing any data. Any help would be much appreciated, thanks!

try to change in ajax.js
$(function(){
$('#followbtn').on('click', function(e){
e.preventDefault();
$('#followbtn').fadeOut(300);
$.ajax({
url: '../ajax-follow.php',
...
the url parameter to :
url: 'ajax-follow.php',
See if it will work that way

Related

post in my js wont work

JS : Fixed by godot!
/* Data Delete Starts Here */
$(".delete-file").click(function()
{
var name = $(this).attr("name");
var file_id = $(this).attr("id");
var active_user = document.getElementById("username").value;
if(confirm('Sure to Delete ' +name+ '?'))
{
$.ajax({
url: 'suf-delete.php',
type: 'post',
async: false,
data: {'file_id':file_id ,'active_user':active_user},
success: function(response){
$("#file_table"+file_id).fadeOut('slow');
},
error: function(error){
console.log(error.responseText);
//you could debug your php code if some error raises
}
});
}
return false;
});
/* Data Delete Ends Here */
PHP: Working Fine (suf-delete.php)
elseif($_POST['file_id'] && $_POST['active_user'])
{
$file_id = $_POST['file_id'];
$active_user = $_POST['active_user'];
$crud->filesDelete($file_id,$active_user);
}
Im now having a problem with my class crud.
I think Its just my query. Im trying to make activity log, delete, select and unlink Item using my code provided below.
Please check this:
Class Crud
public function filesDelete($file_id,$active_user)
{
$stmtFiles = $this->conn->prepare('SELECT * FROM tbl_files WHERE file_id=:file_id');
$stmtFiles->execute(array(":file_id"=>$file_id));
$unFile=$stmtFiles->fetch(PDO::FETCH_ASSOC);
$userStmt = $this->conn->prepare('SELECT * FROM tbl_login WHERE username=:username');
$userStmt->execute(array(":username"=>$active_user));
$fetch = $userStmt->fetch(PDO::FETCH_ASSOC);
$activity = "Deleted the file ".$unFile['file_name'];
if($fetch['access_type']=="Design2K18ADMIN") {
$type = "Administrator";
}
elseif ($fetch['access_type']=="Design2K18MANAGER") {
$type = "Manager";
}
elseif ($fetch['access_type']=="Design2K18MODERATOR") {
$type = "Moderator";
}
elseif ($fetch['access_type']=="Design2K18SIMPLE") {
$type = "Simple";
}
$actLog = $this->conn->prepare("INSERT INTO activity_log(username, activity, type) VALUES(:username, :activity, :type)");
$actLog->execute(array(":username"=>$active_user, ":activity"=>$activity, ":type"=>$type));
$stmtSelFol = $this->conn->prepare('SELECT * FROM tbl_section WHERE sec_id=:sec_id');
$stmtSelFol->execute(array(":sec_id"=>$unFile['sec_id']));
$unFol=$stmtSelFol->fetch(PDO::FETCH_ASSOC);
unlink("../Files/".$unFol['sec_folder']."/".$unFile['file_name']);
$stmtDelFile = $this->conn->prepare('DELETE FROM tbl_files WHERE file_id=:file_id');
$stmtDelFile->execute(array(":file_id"=>$file_id));
return true;
}
I have confirm that My js and php works fine by saving the logs in error.php
I save the value of file_id and active_user in my error.txt file.
9Daren appears which is the value(id) of Item and the current session user is Daren.
Please help me check my public function why It does not do anything.
I would use ajax:
/* Data Delete Starts Here */
$(".delete-file").click(function()
{
var name = $(this).attr("name");
var file_id = $(this).attr("id");
var active_user = document.getElementById("username").value;
if(confirm('Sure to Delete ' +name+ '?'))
{
$.ajax({
url: 'suf-delete.php',
type: 'post',
async: false,
data: {'file_id':file_id ,'active_user':active_user},
success: function(response){
$("#file_table"+file_id).fadeOut('slow');
},
error: function(error){
console.log(error.responseText);
//you could debug your php code if some error raises
}
});
}
return false;
});
/* Data Delete Ends Here */

PHP GET variable not being set

I have a registraion php class that displays a form and when the registration button is clicked, calls a function in a login javascript file. This file uses ajax to post data to a index.php file. My index.php file cannot access this data, despite the post being a success (ajax success is true as the alert is being called).
Login.js
var loginData, urlPath;
// Allow users to log in or register
function Login() {
loginData = "username=" + $("#usernameField").val() + "&email=" + $("#emailField").val() + "&password=" + $("#passwordField").val();
urlPath = "../index.php?action=register";
// Send the login/registration data to database
$(document).ready(function() {
$.ajax({
type: "POST",
url: urlPath,
data: loginData,
success: function (result) {
alert("success");
}
})
})
}
index.php
<?php
require_once("Model/model.php");
require_once("Controller/controller.php");
require_once("View/view.php");
$model = new Model();
$view = new View();
$controller = new Controller($model, $view);
$controller->Begin();
// Client wants to register
if(isset($_GET['action'])) {
if($_GET['action'] == "register") {
echo '<script type="text/javascript">alert("hello")</script>';
}
}
?>
You used POST method of ajax. So send data also in POST manner like below:-
// Send the login/registration data to database
$(document).ready(function() {
var username = $("#usernameField").val();
var email = $("#emailField").val();
var password = $("#passwordField").val();
$.ajax({
type: "POST",
url: "../index.php",
data: {"username":username,"email":email,"password":password,"action":"register"},
success: function (result) {
alert(result);//check the change
}
});
});
And then change GET to POST at php end:-
<?php
require_once("Model/model.php");
require_once("Controller/controller.php");
require_once("View/view.php");
$model = new Model();
$view = new View();
$controller = new Controller($model, $view);
$controller->Begin();
// Client wants to register
//single condition can do the job and use POST instead of GET
if(isset($_POST['action']) && $_POST['action'] == "register" ) {
echo "hello"; //check the change
}
?>
Note:- Please take care of comments too.(added in the code)
loginData = "username=" + $("#usernameField").val() + "&email=" + $("#emailField").val() + "&password=" + $("#passwordField").val() + "&action=" + "register";
urlPath = "../index.php";
$(document).ready(function() {
$.ajax({
type: "POST",
url: urlPath,
data: loginData,
success: function (result) {
alert("success");
}
})
});
Try adding the action also in post data and receive it as $_POST
if($_POST['action']) {
if($_POST['action'] == "register") {
echo '<script type="text/javascript">alert("hello")</script>';
}
}

Magento insert data into database through ajax

I'm new to ajax so I'm not sure if i'm approaching this correctly, basically I have a variable in javascript that need to be inserted into the database, this is what I have so far...
onInit: function() {
window.fcWidget.on('widget:loaded', function() {
window.fcWidget.user.get().then(function(resp) {
var status = resp && resp.status,
data = resp && resp.data;
if (status === 200) {
if (data.restoreId) {
// Update restoreId in database
$.ajax({
type: "POST",
url: "insert.php",
data: data.restoreId,
success: function(data) { alert("Success"); },
failure: function(data) { alert("Failure"); }
})
}
}
});
});
}
I have placed the file "insert.php" in the same folder but it seem like it doesn't get called at all...
This is what insert.php looks like
<?php
if(Mage::getSingleton('customer/session')->isLoggedIn()){
if(isset($_POST['data.restoreId']){
$restoreId =$_POST['data.restoreId'];
}
$first = Mage::getSingleton('customer/session')->getCustomer()->getFirstname();
$last = Mage::getSingleton('customer/session')->getCustomer()->getLastname();
$fullName = $first . "." . $last;
//get resource model
$resource = Mage::getSingleton('core/resource');
//retrieve write connection
$writeConnection = $resource->getConnection('core_write');
//read connection
$readConnection = $resource->getConnection('core_read');
$exId = $fullName;
$resId = $restoreId;
$testQuery = "SELECT `externalId` FROM `freshchat_user` WHERE `restoreId` = '$fullName'";
$result = $readConnection->fetchAll($testQuery);
if(count($result) == '0'){
$query = "INSERT INTO `freshchat_user`(`externalId`, `restoreId`) VALUES ('$exId','$resId')";
$writeConnection->query($query);
}else{
//echo "nope";
}
}
?>
I checked the network tab but insert.php doesn't seem to be called at all, what is wrong with my code?
//Please put your insert.php file in root path(Magento installation path) and change below line in your javascript code.
url: "www.yourwebsite.com/insert.php",

Form/button stop work after ajax partly reload page after form success

(If my english is bad I'm from pewdiepieland)
I have a problem that itch the hell out of me.
I have a page with a picture gallery. When logged in every picture gets a form where you can change the description or delete the picture. I also have a form where you can add a new picture to the gallery.
If I add a picture or delete/edit an existing one the part of the page where all of the pictures are shown reloads so that the new content is loaded. (since I don't want the whole page to reload and also wants to show a message about what happened, eg. "The picture was successfully uploaded/changed/deleted").
The problem is that the forms inside of the part which were reloaded stops working. I need to reload the whole page if I want to delete or edit another image. (The form for submitting a new picture still works, since it's outside of the "reloaded part of the page")
Do I have to reload the javascriptfile or anything else, or what do I need to do?
Do you guys need some parts of the code to check? It feels like I need to add something to my code to prevent this instead of changing the existing.. but hey what do I know...
Best Wishes and Merry Christmas!
UPDATE << with Simplyfied code:
HTML/PHP
<form id="addimg" role="form" method="POST" enctype="multipart/form-data">
<input type="file" name="img">
<input type="text" name="imgtxt">
<input type="submit" name="gallery-submit" value="Add Image">
</form>
<div id="gallery_content">
<?php
$result = mysqli_query($link, "SELECT * FROM gallery");
$count = 1;
while($row = mysqli_fetch_array($result)) {
$filename = $row['filename'];
$imgtxt = $row['imgtxt'];
$id = $row['id'];
echo '<div>';
echo '<img src="gallery/' . $filename . '">';
echo '<form id="editimg' . $count . '" role="form" method="POST">';
echo '<input type="text" name="imgtxt">';
echo '<input type="hidden" name="id">';
echo '<input type="submit" name="changeimgtxt" data-number="' . $count . '" value="Update" class="edit_img">';
echo '</form>';
echo '<button class="delete_img" value="' . $id . '">Delete</button>';
echo '</div>;
}
?>
</div>
JAVASCRIPT/JQUERY
$(document).ready(function() {
$('#addimg').submit(function(e) {
e.preventDefault();
gallery('add', '');
});
$('.edit_img').click(function(e) {
e.precentDefault();
var formNr = $(this).data('number');
var dataString = $('#editimg' + formNr).serialize();
gallery('edit', dataString)
});
$('.delete_img').click(function(e) {
e.preventDefault();
var imgid = $('this').value();
gallery('delete', imgid);
});
function gallery(a, b) {
if (a == 'add') {
var dataString = new FormData($('#addimg')[0]);
$.ajax({
type: "POST",
url: "gallery_process.php",
data: dataString,
success: function(text){
if(text == 'add_success') {
- Show success message -
$('#gallery_content').load(document.URL + ' #gallery_content');
} else {
- Show fail message -
}
},
cache: false,
contentType: false,
processData: false
});
} else if (a == 'edit') {
var dataString = b;
$.ajax({
type: "POST",
url: "gallery_process.php",
data: dataString,
success: function(text){
if(text == 'edit_success') {
- Show success message -
$('#gallery_content').load(document.URL + ' #gallery_content');
} else {
- Show fail message -
}
}
});
} else if (a == 'delete') {
var dataString = 'imgid=' + b;
$.ajax({
type: "POST",
url: "gallery_process.php",
data: dataString,
success: function(text){
if(text == 'delete_success') {
- Show success message -
$('#gallery_content').load(document.URL + ' #gallery_content');
} else {
- Show fail message -
}
}
});
}
}
});
I don't think you need to see my process-file. Any clues?
Your problem is probably the .click function on add and delete image so change it to $('body').on('click', 'delete_img', function() {// do something});
See Here
Your problem is that you only hook up the .click() listeners once on "document ready".
When the $(document).ready() callback is executed the gallery has already been filled and you hook up click listeners on the elements that are currently in the DOM. When you reload the gallery it is no longer the same DOM elements and no click listeners are being set up on these ones. There are a multitude of ways you correct this, for example, jQuery .load() takes a complete callback in which you can set up the event listeners. Your sample adapted with this:
$(document).ready(function() {
var setupGalleryEventListeners = function () {
$('.edit_img').click(function(e) {
e.preventDefault();
var formNr = $(this).data('number');
var dataString = $('#editimg' + formNr).serialize();
gallery('edit', dataString)
});
$('.delete_img').click(function(e) {
e.preventDefault();
var imgid = $('this').value();
gallery('delete', imgid);
});
};
$('#addimg').submit(function(e) {
e.preventDefault();
gallery('add', '');
});
setupGalleryEventListeners(); // Setup initial event listeners on page load
function gallery(a, b) {
if (a == 'add') {
var dataString = new FormData($('#addimg')[0]);
$.ajax({
type: "POST",
url: "gallery_process.php",
data: dataString,
success: function(text){
if(text == 'add_success') {
- Show success message -
$('#gallery_content').load(document.URL + ' #gallery_content', setupGalleryEventListeners); // setupGalleryEventListeners called when load is done
} else {
- Show fail message -
}
},
cache: false,
contentType: false,
processData: false
});
} else if (a == 'edit') {
var dataString = b;
$.ajax({
type: "POST",
url: "gallery_process.php",
data: dataString,
success: function(text){
if(text == 'edit_success') {
- Show success message -
$('#gallery_content').load(document.URL + ' #gallery_content', setupGalleryEventListeners); // setupGalleryEventListeners called when load is done
} else {
- Show fail message -
}
}
});
} else if (a == 'delete') {
var dataString = 'imgid=' + b;
$.ajax({
type: "POST",
url: "gallery_process.php",
data: dataString,
success: function(text){
if(text == 'delete_success') {
- Show success message -
$('#gallery_content').load(document.URL + ' #gallery_content', setupGalleryEventListeners); // setupGalleryEventListeners called when load is done
} else {
- Show fail message -
}
}
});
}
}
});

jTinder Save to Database

I hope it's ok to ask this here. I have searched everywhere, but can't find a solution.
I've found a nice js library called jTinder at https://github.com/do-web/jTinder
Now I am trying to save likes or dislikes in a mysql database and php. But soon I will give up! I've tried a lots of different code, but nothing really happens.
Mostly I crasch the script from working at all.
Can someone help me?
$("#tinderslide").jTinder({
// dislike callback
onDislike: function (item) {
// set the status text
$('#status').html('Dislike image ' + (item.index()+1));
},
// like callback
onLike: function (item) {
// set the status text
$('#status').html('Like image ' + (item.index()+1));
},
animationRevertSpeed: 200,
animationSpeed: 400,
threshold: 1,
likeSelector: '.like',
dislikeSelector: '.dislike'
});
getdata.php looks like this:
$link = mysqli_connect("127.0.0.1", "root", "", "vacation");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$liked = mysqli_real_escape_string($link, $_POST['like']);
$sql = "INSERT INTO destinations (like) VALUES ('$liked')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
mysqli_close($link);
Ajax:
$.ajax({
url: 'getdata.php',
dataType: 'json',
success: function(data)
{
var id = data[0];
var name = data[1];
var count = data[3];
$('#output').html('like('+id+')');
}
There a are many problem in this code so
In your html file where is data coming from in ajax while you are not returning anything in you php code. So your code sholud be somthing like the for test
$("#tinderslide").jTinder({
// dislike callback
onDislike: function (item) {
$.ajax({
url: 'getdata.php',
data: 'DATA_YOU_WANT_TO_SEND',
dataType: 'json',
success: function (data) {
console.log()
//$('#output').html('like(' + id + ')');
}
});
// set the status text
$('#status').html('Dislike image ' + (item.index()+1));
},
// like callback
onLike: function (item) {
// set the status text
$('#status').html('Like image ' + (item.index()+1));
},
animationRevertSpeed: 200,
animationSpeed: 400,
threshold: 1,
likeSelector: '.like',
dislikeSelector: '.dislike'
});
And in php code
You are inserting like into it how do you get a post data in the php file if you are not sending it from the ajax so put data to it.

Categories

Resources