Variable isn't considered as object when called by Ajax - php

I have a poll and when user click on one of the options, it sends data through ajax:
$.ajax({
type: 'POST',
url: '/poll.php',
data: {option: option, IDpoll: IDpoll},
dataType: 'json',
async: false,
error: function(xhr, status, error) {
alert(xhr.responseText);
},
success: function(data) {
if(data.msg == "0") {
$( "#pollArea" ).load( "/pollVote.php", { allow: true }, function() {
alert( "Ďakujeme za Váš hlas!" );
});
}
else {
alert(data.msg);
alert("V tejto ankete ste už hlasovali.");}
}
});
This works fine. Now data are passed to the file poll.php:
if (isset($_POST['option']) && isset($_POST['IDpoll'])) {
require 'includes/config.inc.php';
$ip = $_SERVER['REMOTE_ADDR'];
$option = $pdo->quote($_POST['option']);
$IDpoll = $pdo->quote($_POST['IDpoll']);
$date = date("d.m.Y H:i:s");
$poll = new Poll();
$msg = $poll->votePoll($IDpoll, $ip, $option, $date);
$arr = array(
'msg' => $msg
);
echo json_encode($arr);
This also works, the problem happened in class Poll - method VotePoll:
public function votePoll($IDpoll, $ip, $option, $date)
{
try {
$query = "SELECT * FROM `votes` WHERE `IDpoll` = '$IDpoll' AND `ip` = '$ip'";
$result = $this->pdo->query($query);
if ($result->rowCount() == 0) {
/* do stuff */
}
catch (PDOException $e) {
return $e->getMessage();
}
}
And the error message from the ajax call is following: Call to a member function rowCount() on a non-object. I know what this message means, but I can't find out why the variable $result isn't considered as PDO object. Strange thing is, that when I try to call function votePoll manually, it works perfectly and when I use var_dump on result it is PDO object. So where is the mistake?
EDIT: I forgot to say I was just editing this function. Originally it worked with mysqli but I wanted to switch to pdo (so query and stuff like that are okay).

So, this problem was in these lines:
$option = $pdo->quote($_POST['option']);
$IDpoll = $pdo->quote($_POST['IDpoll']);
PDO quote function add quotes to the string so option became 'option' etc. Then it was sent to query where additional quotes were added, so the result was ''option'' and that is error.

Related

Catch an Ajax Query POST error doesn't work

I wrote some code that enters data into my sql database using JQuery and PHP and it works.
However, I need the error block of the Ajax request to be executed when the database server is offline, sql throws an error, or whenever there should be an error.
The problem is, that the error-block of the ajax request never is executed. Always just the success block. No matter if the sql query is wrong or the database server is offline.
I have tried it with a fail-block and with jQuery.$.get() but that doesn't work either. But I prefer an ajax request anyway.
I have written the following code so far:
//JavaScript-function to insert data into a database. The parameter is an SQL-INSERT statement.
function insertIntoDatabase(sqlQuery)
{
var result;
$.ajax({
type: "POST",
url: "../../general/clientHelper.php",
data: {sql: sqlQuery},
async: false,
error: function()
{
if(sqlQuery.split(" ")[0] != "INSERT") console.log("SQL-Query is not an INSERT statement");
result = false;
},
success: function()
{
result = true;
}
});
return result;
}
<?php
//clientHelper.php - Insert data into the database.
if(isset($_POST['sql'])) insertIntoDatabase($_POST['sql']);
function insertIntoDatabase($sqlQuery)
{
$ip = "10.10.10.1";
$port = 3306;
$username = "candidate";
$password = "candidate";
$dbname = "cqtsdb";
$connection = new mysqli($ip, $username, $password, $dbname, $port);
$connection->query($sqlQuery);
$connection->close();
exit();
}
?>
I don't know what to do now :/ Please help <3
UPDATE:
I found out that if I add one parameter to the success function it gets filled with the text of an error if one has occurred. If everything is right the text is just "". So I didn't have to do anything else than check for it :)
success: function(data)
{
if(data == "") result = true;
else result = false;
}
Check the query result, if it was successful then return a certain value to ajax like 1, if it wasn't, return 0.
Then in ajax success function check that value and show a message accordingly or whatever you want to do.
I use procedural PHP and I do it this way
function leave($msg, $conn, $type){
//$msg is the message I want to display to the user.
//$type is the query result type I explained above.
//$conn is to close the connection.
echo json_encode(array(
"msg" => $msg,
"type" => $type
));
mysqli_close($conn);
exit();
}
call this function that way
$result = mysqli_query($conn, $query);
if ($result) {
leave('done', $conn, 1);
} else {
leave('something went wrong', $conn, 0);
}
check the value like that:
...
success: function (response) {
if(response.type == 1){
// do smth
}
else if(repsonse.type == 0){
// do another thing
}
},
...

Display a message from PHP within AJAX call

I have a favourites button calling an ajax request to update a MySQL database.
I would like to have a alert if there are duplicate additions or too many additions.
Can anybody see a way that I could show an alert if there is a duplicate addition? My code is below:
AJAX REQUEST
$.ajax({
type: 'post',
url: 'favaddDB.php',
data: $('#addfaveform').serialize(),
success: function () {
alert('Added To Favourites');
}
});
PHP
$db = new PDO("mysql:host=localhost;dbname=favourites", 'root', '');
$query1="SELECT * FROM `$email` ";
$stat1=$db->prepare($query1);
$stat1->execute();// IMPORTANT add PDO variables here to make safe
//Check if fave adds >9
$count = $stat1->rowCount();
$fave=$count;
if ($fave>9) {die(); exit();} // HERE I WISH TO RUN AN ALERT OR SEND BACK A MESSAGE TO DISPLAY
else {$fave=$fave+1;}
Just return the text to alert to your javascript:
$db = new PDO("mysql:host=localhost;dbname=favourites", 'root', '');
$query1="Query here ($email/similar should NOT BE HERE! Add them via execute/prepare.";
$stat1=$db->prepare($query1);
$stat1->execute();// IMPORTANT add PDO variables here to make safe
//Check if fave adds >9
$count = $stat1->rowCount();
$fave=$count;
if ($fave>9) {die("Here is a message");} // HERE I WISH TO RUN AN ALERT OR SEND BACK A MESSAGE TO DISPLAY
else {$fave=$fave+1; die("Here is another message"); }
Ajax request:
$.ajax({
type: 'post',
url: 'favaddDB.php',
data: $('#addfaveform').serialize(),
success: function (message) {
alert(message);
}
});
Additionally, you should consider using JSON, to pass back entire objects to your javascript, and parse it there:
$db = new PDO("mysql:host=localhost;dbname=favourites", 'root', '');
$query1 = "Query here ($email/similar should NOT BE HERE! Add them via execute/prepare.";
$stat1 = $db->prepare($query1);
$result = $stat1->execute();// IMPORTANT add PDO variables here to make safe
// Tell javascript we're giving json.
header('Content-Type: application/json');
if (!$result) {
echo json_encode(['error' => true, 'message' => 'A database error has occurred. Please try again later']);
exit;
}
//Check if fave adds >9
$count = $stat1->rowCount();
$fave = $count;
if ($fave > 9) {
echo json_encode(['error' => false, 'fave' => $fave, 'message' => 'Fave > 9!']);
} // HERE I WISH TO RUN AN ALERT OR SEND BACK A MESSAGE TO DISPLAY
else {
$fave = $fave+1;
echo json_encode([
'error' => false,
'fave' => $fave,
'message' => 'Current fave count: ' . $fave
]);
}
And in your ajax, make sure you set dataType: 'json', which will automatically parse it into an object:
$.ajax({
type: 'post',
url: 'favaddDB.php',
data: $('#addfaveform').serialize(),
dataType: 'JSON',
success: function (res) {
if (res.error) {
//Display an alert or edit a div with an error message
alert(res.message);
} else {
//Maybe update a div with the fave count
document.getElementById('#favcount').value = res.fave;
alert(res.message);
}
}
});
Simple is better, in most cases.
By returning messages, you can do whatever you want on the frontend side, depending on the message.
PHP:
<?php
$db = new PDO("mysql:host=localhost;dbname=favourites", 'root', '');
$query1 = "SELECT * FROM " . $email;
$stat1 = $db->prepare($query1);
$stat1->execute();
$count = $stat1->rowCount();
$fave = $count;
if ($fave > 9) {
echo "tooMany"; exit();
} else {
echo "addedFav"; $fave++;
}
JS:
jQuery.post({
url: 'favaddDB.php',
data: jQuery('#addfaveform').serialize()
}).then(function (code) {
switch (code) {
case "addedFav":
alert('Added To Favourites');
break;
case "tooMany":
alert('Too many favourites');
break;
}
}).catch(function (error) {
console.log(error);
});

PHP value not being caught by AJAX

I have some code that sends a variable (pin) to php via AJAX the database is then queried and if a result is found the php echo's a value of 1. Everything is working fine, except that the Ajax does not recognise the value returned by the php.
Here is my code
$(document).ready(function () {
$("form.submit").submit(function () {
var pin = $(this).find("[name='pin']").val();
// ...
$.ajax({
type: "POST",
url: "http://www.example.com/pin.php",
data: {
pin : pin,
},
success: function (response) {
if (response == "1") {
$("#responsecontainer").html(response);
window.location.href = "home.html?user=" + user;
// Functions
} else { // Login failed
alert("LOGIN FAILED");
}
}
});
this.reset();
return false;
});
});
And here is my PHP code, I know that the code below returns a value of 1. When Ajax is triggered it returns a value that generates a login fail message. Is there a way to see what Ajax is sending, if i swap out the ajax and directly submit the for to the server it also returns a 1 on the php echo.
$pin = $_GET["pin"];
$db = new PDO("mysql:host=localhost;dbname=xxxxx;charset=utf8", "xxxx", "xxxx");
$count = $db->query("SELECT count(1) FROM users WHERE pin='$pin'")->fetchColumn();
echo $count;
It's recommended to return JSON data as result for an ajax request.
So try this :
Edit: I've updated the php code to make the sql query with PDO prepare() method taking into account #Dominik's commentary
$pin = $_POST['pin'];
$db = new PDO('mysql:host=localhost;dbname=xxxxx;charset=utf8', 'xxxx', 'xxxx');
$stmt = $pdo->prepare('SELECT count(1) FROM users WHERE pin = :pin');
$stmt->execute(array('pin' => $pin));
return json_encode([
"count" => $stmt->fetchColumn()
]);
And in your ajax success callback :
...
success: function(response) {
var count = JSON.parse(response).count;
if (count == "1") {
$("#responsecontainer").html(response);
window.location.href = "home.html?user="+ user;
} else {// Login failed
alert("LOGIN FAILED");
}
},
error: function(error) {
...
}
Hope it's helps you :)

Show PHP error with AJAX. If there are no errors, show output from PHP function

Alright, this is probably super simple but I've been breaking my head over this all day and I cannot get it to work.
I have a page that displays a list of users from a mysql query. On this page it should also be possible to add users. To do this, I'm sending an AJAX call to process.php which does some validation and sends an error if there is one. If there is no error, I want AJAX to update the page.
The problem is, that if there are no errors (a user has been added), I want to return the updated userlist. This means storing the output of my getUsers(); function in an array, which isn't possible.
How can I achieve this?
p.s. I realise this is crappy code and I should be using OOP/PDO, but this isn't for a production environment and it works. So I'll leave it like this for the time being.
users.php
<article>
<ul>
<?php getUsers(); ?>
</ul>
</article>
<form id="addUserForm">
...
<input type="hidden" name="addUser">
</form>
$("#addUserForm").on("submit",function() {
event.preventDefault();
var data = $("#addUserForm").serialize();
$.ajax({
type: "POST",
url: "process.php",
data: data,
dataType: "json",
success: function(response) {
if (response.success) {
$("article ul).html(response.data);
} else {
$(".errorMessage).html("<p>" + response.error + </p>");
}
}
});
});
functions.php
function getUsers()
{
global $db;
$query = mysqli_query($db, "SELECT * FROM users");
while($row = mysqli_fetch_assoc($query))
{
echo "<li>" . $row["user_firstname"] . "</li>";
}
}
function addUser($email, $password)
{
global $db;
$result = mysqli_query($db, "INSERT INTO users ... ");
return $result
}
process.php
if (isset($_POST["addUser"]))
{
... // Serialize data
if (empty ...)
{
$responseArray = ["success" => false, "error" => "Fields cannot be empty"];
echo json_encode($responseArray);
}
// If user is successfully added to database, send updated userlist to AJAX
if (addUser($email, $password))
{
$responseArray = ["success" => true, "data" => getUsers();];
echo json_encode($responseArray)
}
}
Your getUsers() function is printing and not returning the data to json connstructor
function getUsers()
{
global $db;
$query = mysqli_query($db, "SELECT * FROM users");
while($row = mysqli_fetch_assoc($query))
{
echo "<li>" . $row["user_firstname"] . "</li>";
}
}
it has to be something like this
function getUsers()
{
global $db;
$query = mysqli_query($db, "SELECT * FROM users");
$list = "";
while($row = mysqli_fetch_assoc($query))
{
$list. = "<li>" . $row["user_firstname"] . "</li>";
}
return $list;
}
And there is a syntax error in the following line
if (addUser($email, $password)
close it with ")"
You can capture the output of the getUsers function without changing the current behavior if that's what you're after. In the success output change
$responseArray = ["success" => true, "data" => getUsers();];
echo json_encode($responseArray)
to
ob_start();
getUsers();
$usersList = ob_get_clean();
$responseArray = ["success" => true, "data" => $usersList];
echo json_encode($responseArray)
What this does is captures the output and stores it into a varable $usersList which you can then return as a string.
You'd be better off returning the users as an array and dealing with generating the markup on the client side IMO, but that's up to you. This is just another way to get what you have working.
More information about php's output buffer here
Are you trying to get the error returned by ajax or you want to have custom error? (e.g. string returned by your php script). If you're referring to ajax error you should have this:
EDIT: Since you mentioned you want a custom error returned by process.php
Process.php
if (isset($_POST["addUser"]))
{
... // Serialize data
if (empty ...)
{
$responseArray = ["success" => false, "error" => "Fields cannot be empty"];
echo json_encode($responseArray);
}
// If user is successfully added to database, send updated userlist to AJAX
if (addUser($email, $password))
{
$responseArray = ["success" => true, "data" => getUsers();];
echo json_encode($responseArray)
}else{
echo 1;
}
//I added else echo 1;
}
Your ajax will be:
$("#addUserForm").on("submit",function() {
event.preventDefault();
var data = $("#addUserForm").serialize();
$.ajax({
type: "POST",
url: "process.php",
data: data,
dataType: "json",
success: function(response) {
if(response != 1){
$("article ul").html(response.data);
}else{
alert('Custom error!');
}
},
error: function(jqXhr, textStatus, errorThrown){
console.log(errorThrown);
}
});
});
BTW you're missing ) in your posted code if (addUser($email, $password))
This is how I do:
try{dataObj = eval("("+response+")");}
catch(e){return;}
alert(dataObj->example_key);

jquery ajax not parsing json data from php

I'm facing a strange problem for the last 10 hours and its really very annoying. The problem is with jquery printing json data from php. The php script is running fine, but when the ajax call returns in complete: event i'm not getting any valid otput.
here is the jquery code::
list_choice = "A";
content_choice = "Artists"; //globals to store default value
$(document).ready(function() {
$('.list-nav > a').click(function() {
var ltext = $(this).text();
list_choice = ltext;
console.log(ltext+" <------> ");
$.ajax({
url: 'retrieveFileFront.php',
data: {type: content_choice, navtext: list_choice},
type: 'POST',
dataType: 'json',
complete: function(data) {
console.log(data['message']['Album_Name']);
}
});
return false;
});
});
i had to use complete: event as success: didn't worked at all. Atleast i'm getting some sort of output from the complete: event, although its giving undefined or [object][Object] which is totally ridiculous.
here is the retrieveFileFront.php:
<?php
require './retrieveFiles.php';
$type = $_POST['type'];
$nav_text = $_POST['navtext'];
$ret_files = new retrieveFiles($type, $nav_text);
$data = $ret_files->retFiles();
if ($data['success'] == FALSE) {
$data = array('success' => FALSE, 'message' => 'Sorry an Error has occured');
echo json_encode($data);
} else {
echo json_encode($data);
}
?>
and here is the /retrieveFiles.php
<?php
class retrieveFiles {
public $content_type;
public $list_nav;
public $connection;
public $result;
public $result_obj;
public $tags_array;
public $query;
public $row;
public function __construct($type, $nav_text) {
$this->content_type = $type;
$this->list_nav = $nav_text;
}
public function retFiles() {
#$this->connection = new mysqli('localhost', 'usr', 'pass', 'data');
if(!$this->connection) {
die("Sorry Database connection could not be made please try again later. Sorry for the inconvenience..");
}
if ($this->content_type == "Artists") {
$this->query = "SELECT album_name, album_art FROM album_dummy NATURAL JOIN album_images_dummy WHERE artist_name LIKE '$this->list_nav%'";
try {
$this->result = $this->connection->query($this->query);
$this->row = $this->result->fetch_row();
if (isset($this->row[0]) && isset($this->row[1])) {
$this->tags_array = array("success" => true, "message" => array("Album_Name" => $this->row[0], "Album_Art" => $this->row[1]));
return $this->tags_array;
}
} catch (Exception $e) {
echo 'Sorry an Error has occurred'.$e;
return false;
}
}
}
}
?>
I'm getting a 200 response in console in firebug, which indicates that its running okay.
<!DOCTYPE HTML>
{"success":true,"message":{"Album_Name":"Streetcleaner","Album_Art":"\/var\/www\/html\/MusicLibrary\/Musics\/1989 - Streetcleaner\/folder.jpg"}}
Now this is making me even more confused as i can see that the json is formatted properly. Please provide any sort of suggestion on how to solve this problem.
Thanks in advance..
JSON encoded data is usually not sent like
data['message']['Album_Name']);
But rather like:
data.message.Album_Name;
You're calling your results the wrong way. These are not associative arrays anymore but are now objects, as the name JSON (JavaScript Object Notation) suggests.
You need to parse the json response using
data = $.parseJSON(data)
Use success event instead of complete in ajax and we can able to parse JSON encoded data in javascript/jQuery by using JSON.parse
well after a long period of trauma, i finally found a solution, turns out that i needed to parse the response text and then access the objects, individually.
Here is the working code
list_choice = "A";
content_choice = "Artists"; //globals to store default value
$(document).ready(function() {
$('.list-nav > a').click(function() {
var ltext = $(this).text();
list_choice = ltext;
console.log(ltext+" <------> ");
$('#loading').css('visibility', 'visible');
$.ajax({
url: 'retrieveFileFront.php',
data: {type: content_choice, navtext: list_choice},
type: 'POST'
dataType: 'json',
complete: function(data) {
var res = data.responseText;
res = res.replace(/<!DOCTYPE HTML>/g, "");
res = res.trim();
console.log(res);
var arr = JSON.parse("[" + res +"]"); //needed to parse JSON object into arrays
console.log(arr[0].message.Album_Name);
console.log(arr[0].message.Album_Art);
$('#loading').css('visibility','hidden');
}
});
return false;
});
This works fine and gives the desired response. Anyways thanks for the help, guys.

Categories