Is there something special about the variables that are passed via AJAX? - javascript

I am trying to access a database and delete a review of a user, I have a method that I pass the user's ID and the ID of the review. This method functions properly using both the SQL command as well as when I call hard-coded variables, however, when I pass the code via AJAX my code says it completed successfully but does not actually do anything. Is there something special about the variables that are passed via AJAX?
This is my method:
public function deleteRating($userid, $reviewID)
{
echo "this is idUsers(IdUsers) = ".$userid." this is reviewID (ID)".$reviewID;
$conn = $this->connect("ratings");
$sql = "DELETE FROM ratedmovies WHERE IdUsers=? AND ID=?";
if(!$stmt = $conn->prepare($sql))
{
echo "False";
}
else
{
$stmt->bind_param("ss", $userid, $reviewId);
if(!$stmt->execute())
{
echo "Failed to delete";
}
else
{
echo "Sucessfull Deletion";
}
}
}
This is the code that calls the method:
<?php
session_start();
include "../Model/Includes/autoLoadCont.inc.php";
$reviews = new Review;
$ratingID = json_decode($_POST['ratingID']);
$user = $_SESSION['userId'];
$reviews->deleteRating($user, $ratingID);
?>
and this is the ajax that calls that function:
var deleteBtns = document.querySelectorAll(".deleteRating");
deleteBtns.forEach(function(button)
{
button.addEventListener("click" , function()
{
$.ajax({
type: "POST",
url: "Controller/deleteReview.php",
data: {ratingID:button.id},
success: function(result)
{
alert(result);
}
});
});
button.id;
});

Related

ajax works, but it doesn't insert into my sql query (js/php)

I don't understand if ajax work this way, but data doesn't add into my mysql database. I checked network tab in my chrome browser and found data has been forwarded.
I had tried like this way
script.js:
$(".btn_ranking").click(function (e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: { "name": name, "time": time }
})
});
file.php:
<?php
require_once "connect.php";
$polaczenie = #new mysqli($host, $db_user, $db_password, $db_name);
$name = $_POST['name'];
$time = $_POST['time'];
if ($polaczenie->connect_errno != 0) {
echo "Error: " . $polaczenie->connect_errno;
} else {
if ($rezultat = #$polaczenie->query("INSERT INTO ranking (id, name, time) VALUES (NULL, $name, $time)")) {
echo "ok";
}
}
?>
First,you had better use PrepareStatement to pass parameter instead of writing them directly into your sql.
For your current code,try change to below code
if ($rezultat = #$polaczenie->query("INSERT INTO ranking (id, name, time) VALUES (NULL, '".$name."', '".$time."')")) {
echo "ok";
}
You should try like as below
$(".btn_ranking").click(function (e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: { name: name, time: time } //Remove double quote
})
});

Communication between JavaScript, PHP and MySQL

I'm trying to learn JavaScript to code for Cordova.
I read many tutorials, but none of them helped me with the folowing problem.
My cordova app is for testing very simple. Just a textbox and 2 buttons. Both Buttons calls a PHP script on my server. One button sends data to the PHP script to insert the value of the textfield in a MySQL database, the second button calls the same script and should write the values of the database to my cordova app.
Here is my
<?PHP
$response = array();
require_once __DIR__ . '/db_config.php';
$db_link = mysqli_connect (
DB_SERVER,
DB_USER,
DB_PASSWORD,
DB_DATABASE
);
mysqli_set_charset($db_link, 'utf8');
if (!$db_link)
{
die ('keine Verbindung '.mysqli_error());
}
if(isset($_POST['action']) && $_POST['action'] == 'insert'){
$name = $_POST['name'];
$sql = "INSERT INTO test.testTable (name) VALUES ('$name')";
$db_erg = mysqli_query($db_link, $sql);
if (!$db_erg){
echo "error";
}else{
echo "ok";
}
}
if(isset($_POST['action']) && $_POST['action']=='read'){
$sql = "SELECT * FROM testTable";
$db_erg = mysqli_query( $db_link, $sql );
if (!$db_erg )
{
$response["success"] = 0;
$response["message"] = "Oops!";
echo json_encode($response);
die('Ungültige Abfrage: ' . mysqli_error());
}
while ($zeile = mysqli_fetch_array( $db_erg, MYSQL_ASSOC))
{
//$response["success"] = $zeile['pid'];
//$response["message"] = $zeile['name'];
$response[]=$zeile;
}
echo json_encode($response);
mysqli_free_result( $db_erg );
}
?>
and here are my 2 functions in the cordova app:
function getNameFromServer() {
var url = "appcon.php";
var action = 'read';
$.getJSON(url, function (returnedData) {
$.each(returnedData, function (key, value) {
var id = value.pid;
var name = value.name;
$("#listview").append("<li>" + id + " - " + name) + "</li>";
});
});
}
function sendNameToServer() {
console.log("sendNameToServer aufgerufen");
var url2send = "appcon.php";
var name = $("#Name").val()
var dataString = name;
console.log(dataString);
if ($.trim(name).length>0) {
$.ajax({
type: "POST",
url: url2send,
data: { action: 'insert', name: dataString },
crossDomain: true,
cache: false,
beforeSend: function () {
console.log("sendNameToServer beforeSend wurde aufgerufen");
},
success: function (data) {
if (data == "ok") {
alert("Daten eingefuegt");
}
if (data == "error") {
alert("Da ging was schief");
}
}
});
}
}
My Questions/Problems:
The sendNameToServer funtion works in that case, that the data will be inserted in my Database. But I never get the alert (the success: never called).
How can I pass "action = read" to the PHP script in the getNameFromServer() function?
The third question is a bit off topic, but is this art of code "save" or is it simple to manipulate the data between the cordova app and the server? What's the better way or how can I encrypt the transmission?
Here is one part answer to your question.
$.getJSON has a second optional parameter data that can be an object of information you want to pass to your script.
function getNameFromServer() {
$.getJSON("appcon.php", { action: 'read' }, function (returnedData) {
$.each(returnedData, function (key, value) {
var id = value.pid;
var name = value.name;
$("#listview").append("<li>" + id + " - " + name) + "</li>";
});
});
}
Edit: Since you are using $.getJSON(), the request method is a GET, which means you have to use $_GET in your third if statement in your PHP script.
if(isset($_GET['action']) && $_GET['action'] == 'read'){

Ajax returns success but doesn't change the database

I'm developing a small script of js to edit a profile in the way facebook used to be (click a button, edit and save without reloading the page). The problem is that when I run it, the ajax function returns sucess but akes no changes on the database. The function os js is this:
$('.savebtn').click(function(){
var editdata = $(".editbox").val();
var parameter = $(this).closest("td").find("#parameter").text();
var datastring = "data="+editdata+"&parameter="+parameter;
var $t = $(this);
console.log(datastring);
$.ajax({
type: "POST",
url: BASE_URL + "/API/update_profile.php",
data: datastring,
cache: false,
success: function()
{
$t.closest('td').find('.curr_value').html(editdata);
$t.closest('td').find('.curr_value').hide;
console.log(editdata);
$(this).prev(".edit").hide();
$(this).prev(".curr_value").show();
$(this).prev('.edit_link').show();
$(this).hide();
}
});
});
(Ignore the $t thing, somehow this works like this, but not if I use $(this))
Ajax executes the code for sucess but doesn't update anything on the database.
The PHP code for the database is:
<?php
include_once("../../config/connect_db.php");
include_once("../../database/cliente.php");
$parameter = $_POST['parameter'];
$data = $_POST['data'];
$id = $_SESSION['id'];
var_dump($_POST);
try {
updateProfile($parameter, $data, $id);
}
catch (PDOException $e)
{
echo 'Caught exception: ', $e->getMessage(), "\n";
}
?>
function updateProfile($parameter, $data, $id)
{
global $conn;
$stmt = $conn->prepare("UPDATE biofood.users
SET ? = ?
WHERE id = ?");
$stmt->execute(array($parameter, $data. $id));
}
EDIT: As pointed out, this could be a problem with trying to pass a column name as a parameter. Changed the code to the following, but with no sucess:
function updateProfile($parameter, $data, $id)
{
global $conn;
$query = "UPDATE biofood.users
SET $parameter = $data
WHERE id = $id";
$stmt = $conn->prepare($query);
$stmt->execute();
}
This line:
$stmt->execute(array($parameter, $data. $id));
I think should be
$stmt->execute(array($parameter, $data, $id));
(notice the comma after $data)
This might not solve your problem, but it might give you a better indication on where your problem is.
First, you are not checking whether it works or not as your updateProfile function returns nothing.
Modify your updateProfile function, so that it returns the number of rows affected. (BTW this is a safer way to write your function. If you can check or limit the value of $parameter prior to calling this function, it will be less prone to SQL injection.)
function updateProfile($parameter, $data, $id)
{
global $conn;
$stmt = $conn->prepare("UPDATE biofood.users SET $parameter = ? WHERE id = ?");
$stmt->execute(array($data, $id));
return $stmt->rowCount(); // # of rows affected
}
In the script that calls this function, get the value and send it back as a response. We'll send back a JSON.
$response = array();
try {
$response['success'] = updateProfile($parameter, $data, $id);
} catch (PDOException $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
header('Content-Type: application/json');
echo json_encode($response);
In your JavaScript file, make the following change:
$.ajax({
type: "POST",
url: BASE_URL + "/API/update_profile.php",
data: datastring,
cache: false,
success: function (data) {
if (data.success) {
$t.closest('td').find('.curr_value').html(editdata);
$t.closest('td').find('.curr_value').hide;
console.log(editdata);
$(this).prev(".edit").hide();
$(this).prev(".curr_value").show();
$(this).prev('.edit_link').show();
$(this).hide();
}
},
dataType: 'json'
});

data not passed between pages in live server

I came across weird problem with my site only after uploaded it to the live server. In localhost I've no issue with these.
The problem is for login and register function. Let me talk about login first.
I keyed in the credentials and found that the page is called in the f12 network tab.However that page doesn't retrieve any data! So I put aside this jquery/ajax for a while and manually checked the php pages if they return any data but still they don't.
Now the flow like this:
login form filled up by user-> ajax request from php script-> php request from class file and return to ajax -> ajax give access to admin dashboard.
Now as I told you, I excluded ajax request and only checked with php and class file. Again it doesn't return anything from the class file to the php script though I only echoed "something"! Its not even go through any function!
Then I omitted, class file, checked the php script with ajax file.I only echo "wexckdsewndxw" and changed tha datatype in ajax to 'text'..still it doesn't get any value!
So in conclusion, data between pages are not passed at all! SO I suspect its something to do with crossDomain issue as mentioned here:
How does Access-Control-Allow-Origin header work?
But not sure how this works and how I should alter my code.
My code for reference:
login-user.js
/*login user*/
<!--login form submission starts-->
$("document").ready(function(){
$("#login-user").submit(function(){
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "login-this-user.php",
data: data,
success: function(data) {
alert(data);
console.log(data);
var i;
for (i = 0; i < data.length; i++)
{
console.log(data[i].email);
console.log(data[i].activate);
console.log(data[i].status);
if($.trim(data[i].status)=='0')
{
//alert("not verified");
$('.invalid-popup-link').trigger('click');
}else
{
//alert("verified");
location.replace("admin/dashboard.php");
}
}//end for
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
}
});
return false;
});
});
<!--login form submission ends-->
login-this-user.php
<?php
session_start();
include('config.php');
include('class.login.php');
$return = $_POST;
//$return ='{"email":"admin#gmail.com","pass":"admin","action":"test"}';
//$return['json']= json_encode($return);
//
//below code to store in database
$data = json_decode($return, true);
$login = new checkLogin();
$status = $login->checkLogin2($data["email"],$data["pass"]);
$_SESSION['user_id']=$status;
$login = new checkLogin();
$profile = $login->check_profile($data["email"]);
$activated_id=array();
foreach($profile as $k=>$v){
array_push($activated_id,array("email"=>$v['email'],"activate"=>$v['activate'],"status"=>'0'));
$_SESSION['email'] = $v['email'];
$_SESSION['activated_id'] = $v['activate'];
}
//header('Content-Type: application/json');
echo json_encode($activated_id);
?>
class
<?php
session_start();
?>
<?php
class checkLogin
{
public $email;
public $password;
public $userId;
public $salt;
public $hpass;
public function __construct()
{
}
public function checkLogin2($param1, $param2)
{
$this->email=$param1;
$this->password=$param2;
$sql = "SELECT * FROM authsessions WHERE email='{$this->email}'";
$statement = connection::$pdo->prepare($sql);
$statement->execute();
while( $row = $statement->fetch()) {
$salt=$row['salt'];
$hashAndSalt=$row['hashpword'];
$user_id=$row['UUID'];
}
if (password_verify($this->password, $hashAndSalt)==true) {
$status = "verified";
$_SESSION['user_id'] =$user_id;
$_SESSION['logged_in']=1;
}else
{
$status = "not verified";
$_SESSION['user_id'] =0;
$_SESSION['logged_in']=0;
}
return $_SESSION['user_id'] = 1;
}
public function check_profile($param)
{
$this->email = $param;
$sql="SELECT * FROM authsessions WHERE email = '{$this->email}'";
$stmt =connection::$pdo->prepare($sql);
$stmt->execute();
$profile=array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$profile[] = $row;
}
return $profile;
}
}
?>

Ajax login issues

I'm having issues with an Ajax login function. There was another question similar to mine that I was able to find but it proved no use.
I have no idea what is the issue, this works on another program as well with no issues, hopefully someone can see my mistake
From testing I think the issue is in the "checkLogIn" function because when I run the application the alert within the function shows
Ajax:
$("#checkLogIn").click(function()
{
$.ajax({
type: 'POST',
contentType: 'application/json',
url: rootURL + '/logIn/',
dataType: "json",
data: checkLogIn(),
})
.done(function(data)
{
if(data == false)
{
alert("failure");
}
else
{
alert("Success");
$.mobile.changePage("#page");
}
})
.always(function(){})
.fail(function(){alert("Error");});
});
function checkLogIn()
{
alert();
return JSON.stringify({
"userName": $("#enterUser").val(),
"password": $("#enterPass").val(),
});
}
I'll also include the PHP but the PHP works 100% after testing it.
PHP:
$app->post('/logIn/', 'logIn');
function logIn()
{
//global $hashedPassword;
$request = \Slim\Slim::getInstance()->request();
$q = json_decode($request->getBody());
//$hashedPassword = password_hash($q->password, PASSWORD_BCRYPT);
$sql = "SELECT * FROM users where userName=:userName AND password=:password";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("userName", $q->userName);
$stmt->bindParam("password", $q->password);
$stmt->execute();
//$row=$stmt->fetch(PDO::FETCH_ASSOC);
//$verify = password_verify($q->password, $row['password']);
$db = null;
//if($verify == true)
//{
// echo "Password is correct";
//}
//else
// echo "Password is incorrect";
echo "Success";
} catch (PDOException $e) {
echo $e->getMessage();
}
}
I have commented out any and all hashing until I can get this working properly
There is no problem with the ajax script. From my assumption you always get Error alert. That is because you added dataType: "json", which means you are requesting the response from the rootURL + '/logIn/' as json Object. But in the php you simply echoing Success as a plain text. That makes the ajax to get into fail function. So, You need to send the response as json. For more details about contentType and datatype in ajax refer this link.
So you need to change echo "Success"; to echo json_encode(array('success'=>true)); in the php file. Now you'll get Success alert. Below I added a good way to handle the json_encoded response in the php file.
$app->post ( '/logIn/', 'logIn' );
function logIn() {
global $hashedPassword;
$request = \Slim\Slim::getInstance ()->request ();
$q = json_decode ( $request->getBody () );
$hashedPassword = password_hash($q->password, PASSWORD_BCRYPT);
$sql = "SELECT * FROM users where userName=:userName";
try {
$db = getConnection ();
$stmt = $db->prepare ( $sql );
$stmt->bindParam ( "userName", $q->userName );
$stmt->execute ();
$row=$stmt->fetch(PDO::FETCH_ASSOC);
$verify = false;
if(isset($row['password']) && !empty($row['password']))
$verify = password_verify($hashedPassword, $row['password']);
$db = null;
$response = array();
$success = false;
if($verify == true)
{
$success = true;
$response[] = "Password is correct";
}
else
{
$success = false;
$response[] = "Password is incorect";
}
echo json_encode(array("success"=>$success,"response"=>$response));
} catch ( PDOException $e ) {
echo $e->getMessage ();
}
}
And I modified the ajax code. There I showed you how to get the response from the json_encoded Object.
$("document").ready(function(){
$("#checkLogIn").click(function()
{
var post_data = JSON.stringify({
"userName": $("#enterUser").val(),
"password": $("#enterPass").val(),
});
$.ajax({
type: 'POST',
contentType: 'application/json',
url: rootURL + '/logIn/',
dataType: "json",
data: post_data,
})
.done(function(data)
{
// data will contain the echoed json_encoded Object. To access that you need to use data.success.
// So it will contain true or false. Based on that you'll write your rest of the code.
if(data.success == false)
{
var response = "";
$.each(data.response, function(index, value){
response += value;
});
alert("Success:"+response);
}
else
{
var response = "";
$.each(data.response, function(index, value){
response += value;
});
alert("Failed:"+response);
$.mobile.changePage("#page");
}
})
.always(function(){})
.fail(function(){alert("Error");});
});
});
Hope it helps.

Categories

Resources