jTinder Save to Database - javascript

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.

Related

$.ajax missing some data on post to php

I have a problem where some of my data is not getting through to php. I think the problem lies in ajax sending it. I send about 10 attributes, from which some are strings and some are integers. This is just simplified example of what I did. Few of the values given that it misses are integers, I think. And some values are got from cordova.Localstorage with storage.getItem("itemkeyname"); There's no problem with connection, because I get at least error message back saying "missing data" etc, etc..
I've tried PHP's isset() instead of empty(), which didn't change anything.
var_dump() returns array of send attributes, but few last attributes are cut-off or missing.
//when submitbtn is pressed
$("#submitbtn").click(function () {
// First I get data from input elements from page
$name = $("#name").val();
$name2 = $("#name2").val();
//debug to see $name's value
alert("name: " + $name + ", name2: " + $name2);
// then I check it's not empty/null
if ($name && $name2) {
//then call ajax and send data to server
$.ajax({
url: "http://localhost:1234/phpfile.php",
type: "POST",
data: {
name: $name,
name2: $name2
},
dataType: "text",
success: function (response) {
alert(response);
},
error: function (err) {
$output = JSON.stringify(err);
alert($output);
}
});
}
});
On the server side phpfile.php
<?php header('Content-Type: text/html; charset=utf-8');
//store missing data on array
$data_missing = array();
if(empty($_POST['name'])) {
$data_missing[] = "name";
} else {
$name = trim($_POST['name']);
}
if(empty($_POST['name2'])) {
$data_missing[] = "name2";
} else {
$name2 = trim($_POST['name2']);
}
//check there's no data missing
if(empty($data_missing)) {
//do stuff
} else {
echo 'missing data: ';
foreach($data_missing as $missing) {
echo '$missing , ';
}
}
?>
echo '$missing , ' won't work should be echo "$missing , "
In your JS code the dataType is defined as "text" (plain), while PHP defines its response as text/html.
Try to check the input values as:
if( !isset($_POST["name"]) || strlen(trim($_POST["name"])) == 0 ) {
$data_missing[] = "name";
}

Ajax PHP Follow Script - Nothing stored in the database

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

AJAX Post values not received in PHP

Below is my ajax file. Here I passed all my text box values.
And I post that values to edu.php. There I want to update two tables like details and test.
But nothing is updating in my database.While I checked the value with var_dump the string seems to be empty.But while passing from ajax I checked it with an alert it shows all the values in text box. So I believe problem is happening while posting from ajax to php.
AJAX Code
$('#edubackgroundsubmit').click(function (event) {
event.preventDefault();
alert("Hello");
var per_email = $('#per_email').val();
var master_overall = $('#master_overall').val();
var master_pass_year = $('#master_pass_year').val();
var master_college = $('#master_college').val();
var master_univ = $('#master_univ').val();
var data1 ="master_qual="+master_qual+"&master_overall="
+master_overall+"&master_pass_year="+master_pass_year+"&master_college="+master_college+"&master_univ="+master_univ
+"&edu_flag="+edu_flag;
alert(data1);
$.ajax({
type:"POST",
url: "edu.php?per_mobile="+per_mobile,
dataString1: data1
}).done(function( dataString1 )
{
alert(dataString1);
$('#edu_alert').append(
'<div class="alert alert-success text-center">' +
'<button type="button" class="close" data-dismiss="alert">' +
'×</button>' + dataString1 + '</div>');
});
});
PHP File
if (isset($_POST['pass_year_12'])) {
$pass_year_12 = $_POST['pass_year_12'];
} else {
$pass_year_12 = "";
}
$l1 = "UPDATE test
SET edu_flag='$edu_flag'
WHERE per_mobile='$per_mobile'";
$l2 = "UPDATE details
SET master_qual='$master_qual',
master_overall='$master_overall',
master_pass_year ='$master_pass_year ',
master_college='$master_college'
WHERE per_mobile='$per_mobile'";
$exec = mysqli_query($link, $l1);
if (mysqli_query($link, $l2)) {
echo "Education Details Updated Successfully";
} else {
echo "Error updating record: " . mysqli_error($link);
}
This is wrong. What's this bit:
dataString1: data1
You need to change it as:
data: data1
The function $.ajax() POSTs only those given in the data attribute.
Problem with your code is hat you are sending the data at edu.php?per_mobile
so you need to add isset condition before the code... like this
if(isset($_REQUEST['per_mobile'])){ //write your code here }
and also replace datastring to data.
and then try.
Hope it may help.
For instance you can also use jQuery get or post method, that is more reliable and easy to learn.

Submitting form using JQuery, AJAX and PHP

I have a form which submits it to the database using JQuery, AJAX and PHP. The problem is, whenever I click the submit button of the form, the JavaScript alert says that the record (data from the form) has successfully recorded (to the database). I would then check my database but the data is not recorded, leaving the database empty and no changes at all. My question is, there something wrong with the script? Or with the PHP code?
Here's the script addnew.js:
$(document).ready(function() {
$("#submit").click(function() {
var transMonth = $("#transMonth").val();
var transDay = $("#transDay").val();
var transYear = $("#transYear").val();
var voucherNum = $("#voucherNum").val();
var expType = $("#expType").val();
var acctsPayable = $("#acctsPayable").val();
var amount = $("#amount").val();
var dataString = 'transMonth1='+ transMonth + 'transDay1='+ transDay + 'transYear1='+ transYear + 'voucherNum1='+ voucherNum + 'expType1='+ expType + 'acctsPayable1='+ acctsPayable + 'amount1='+ amount;
if(voucherNum=='') {
alert("Please fill a valid voucher number.");
}
else {
$.ajax ({
type: "POST",
url: "addnew.php",
data: dataString,
cache: false,
success: function(result) {
alert(result);
}
});
}
return false;
});
});
Here's the PHP code addnew.php:
<?php
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("mydb", $connection);
//fetch values
$transMonth2 = $_POST['transMonth1'];
$transDay2 = $_POST['transDay1'];
$transYear2 = $_POST['transYear1'];
$voucherNum2 = $_POST['voucherNum1'];
$expType2 = $_POST['expType1'];
$acctsPayable2 = $_POST['acctsPayable1'];
$amount2 = $_POST['amount1'];
//query
$query = mysql_query("insert into anotherSample(transMonth, transDay, transYear, voucherNum, expenseType, acctPayable, amount) values ('$transMonth2', '$transDay2', '$transYear2', '$voucherNum2', '$expType2', 'acctsPayable2', '$amount2')");
echo "Record added successfully";
mysql_close($connection);
I think your dataString in addnew.js should be transMonth1='+ transMonth + '&transDay1='+ transDay + '&transYear1='...,
otherwise the $transDay2,$transYear2..would be null, if your transDay or more set NOT NULL in mysql, there will occur a mysql error. :)
You should check returned result. You can do this by the following code:
$result = mysql_query("insert into anotherSample(transMonth, transDay, transMonth, transYear, voucherNum, expenseType, acctPayable, amount) values ('$transMonth2', '$transDay2', '$transYear2', '$voucherNum2', '$expType2', 'acctsPayable2', '$amount2')");
if (!$result) {
die('Invalid query: ' . mysql_error()); // only for development, in production you shouldn't print error to client!
}
echo "Record added successfully";
mysql_close($connection);
PS. Also, I advice you to read about SQL-injections, because your code is vulnerable.
I see a problem in insert statement, insert into anotherSample(transMonth, transDay, transMonth, transYear,....) values ('$transMonth2', '$transDay2', '$transYear2, .....) 'transMonth' is repeated twice and eight columns with seven values.
In your addnew.js file you should use an ampersand (&) between each key/value pair like this:
var dataString = 'transMonth1='+ transMonth + '&transDay1='+ transDay + '&transYear1='+ transYear + '&voucherNum1='+ voucherNum + '&expType1='+ expType + '&acctsPayable1='+ acctsPayable + '&amount1='+ amount;
This way you will ensure that each variable will have a value when you are reading them in your addnew.php file.
Check fetched values in addnew.php
and echo mysql_error($connection) to check if mysql error was occurred.

Ajax validator function doesn't work

I have to validate my form which does a scheduling. I used ajax and php to do a query and search that time - that was choosen in a select - in the database. If there's one row saved, it returns 1 (or false), if doesn't, returns 0 (or true). Anyway, in the function callback, even it's true, the validate error appears, as if it had a real error. Printing the value, we see the value, but i dont know why it shows the error. I've tried everything, and nowhere i found the answer for this.
The js file: alteraDiv.js
jQuery.validator.addMethod('confereDia', function(value){
alert("entrou no método");
if (conf(value) == '0'){
alert("entrou no if");
return true;
}else{
alert("entrou no else");
return false;
}
});
var verifica;
function setVerifica(x){
verifica = x;
}
function conf(value){
$.ajax({
async: false,
url: 'confereDia.php?horarioInicial='+value,
dataType: 'text',
success: function(data) {
alert("entrou no success");
setVerifica(data);
alert("value:"+value);
return verifica;
},
error: function(data){
alert("ERROR. Dados: " + data);
}
});
}
The php file: confereDia.php
$horarioInicial = $_GET["horarioInicial"];
$query = "SELECT idAgendamento FROM agendamento WHERE horarioInicial = '$horarioInicial'";
$results = mysql_query($query);
if (mysql_num_rows($results) == 0) {
echo '0'; //good to register
} else {
echo '1'; //already registered
}
There are more codes in the files, but i think these are necessary for you understand and help me.. THANK YOU!!!

Categories

Resources