Issue with retrieving a parameter from a $.ajax call - php

Hey guys I have the following $.ajax call:
$.ajax({
type: "POST",
dataType: "json",
url: '/pcg/popups/getNotes.php',
data:
{
'nameNotes': notes_name.text(),
},
success: function(response) {
$('#notes_body').text(response.the_notes);
alert(response.the_notes);
}
)};
Now focus on the data: lets say I sent 'BillCosby'. That will be sent over to the file specified and i have this inside that file:
$username_notes = $_POST['nameNotes'];
Now lets say I was to just have $username_notes return in the json like this...
$returnArray = array( 'the_notes' => $username_notes );
echo json_encode($returnArray);
This would work and the response would be BillCosby. Now with that out of the way, when I try to get a value for BillCosby from my MySQL database using PDO it will return null....Before I show the code for the whole file I just want to make clear that the PDO works perfect, if I were to give the variable $username_notes the direct value of 'BillCosby' I would run through the database perfect, it only returns null if I have the $_POST['nameNotes']; in front.
getNotes.php:
$username_notes = $_POST['nameNotes'];
grabNotes($username_notes);
function grabNotes($xusername)
{
.....
$newUser = $xusername;
try {
# MySQL with PDO_MYSQL
$DBH = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch(PDOException $e) {
echo "I'm sorry, I'm afraid I can't do that.";
file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
}
$sql = "SELECT notes FROM csvdata WHERE username = :username";
$getmeminfo = $DBH->prepare($sql);
$getmeminfo->execute(array(':username' => $newUser));
$row = $getmeminfo->fetch(PDO::FETCH_ASSOC);
$notes = $row['notes'];
$returnArray = array( 'the_notes' => $row['notes'],);
echo json_encode($returnArray);
$DBH = null;
}
So my question is, why can I not get the return value back from the PDO statement? It will work perfect if I told the PDO statement the name - 'BillCosby' inside the file that the $.ajax file calls to. But it will not work and returns null if I get the value through $_POST from the $.ajax. the funny thing is I can return the same value that was sent in.
Thanks for your time guys!

Try trimming it :
$username_notes = trim( $_POST['nameNotes'] );
Sometimes spaces in the string will cause this sort of error, and they can be hard to spot.

I often have to add the ?callback=?. So your JQuery ajax request will look like the following:
$.ajax({
type: "POST",
dataType: "json",
url: '/pcg/popups/getNotes.php?callback=?',
data:
{
'nameNotes': notes_name.text(),
},
success: function(response) {
$('#notes_body').text(response.the_notes);
alert(response.the_notes);
}
)};
Also, preferrably you'd use the jQuery.getJSON method.

Related

Passing JS object (associative array) via Ajax to PHP not working

I am trying to pass a JS object (associative array) that I create dynamically to a PHP / MySQLi query.
- When I write the JS object (transferData) to the console it appears as intended (see below).
- When I test the PHP / MySQLi query separately it works too.
- I therefore assume my problem is with the Ajax call that I use to pass the JS object to PHP / MySQLi.
Can someone tell me how the correct Ajax call should look like here (e.g. using JSON etc.) or what I have to change on the PHP / MySQLi side ?
My JS object:
0: {vId: "04567901", rId: "DE-002"}
1: {vId: "04567902", rId: "DE-005"}
2: {vId: "04567903", rId: "DE-007"}
length: 3
__proto__: Array(0)
My jQuery / Ajax:
$('#btnConfirm').click(function() {
$.ajax({
type: 'POST',
url: 'updateIds.php',
data: {
transferData: transferData
},
success: function(result){
$('#modalSuccess').modal('show');
}
});
});
My PHP / mySQLi:
$postData = $_POST;
$transferData = $_POST['transferData'];
$conn = new mysqli($host, $username, $password, $database);
if($conn->connect_error) {
die("Connection Error: " . $conn->connect_error);
}
$stmt = $conn->prepare("UPDATE myTable l SET l.rId = ? WHERE l.vId = ?");
foreach($transferData as $vId => $rId) {
$stmt->bind_param('ss', $rId, $vId);
$stmt->execute();
}
$stmt->close();
$conn->close();
Update:
My focus is on the Ajax call as I think there is the reason why the data does not reach the PHP page.
Many thanks for any help with this,
Tom
just get your data in php like this:
$postData = file_get_contents("php://input");
$transferData = json_decode($postData, true)['transferData'];
When you use the POST request is better to indicate the data type you're expecting from the server-side use "dataType" in your ajax request, and then parse the data to a valid javascript object in your success handler using JSON.parse().
$('#btnConfirm').click(function() {
$.ajax({
type: 'POST',
url: 'updateIds.php',
dataType: 'JSON', // I'm expecting a json response
data: {
transferData: transferData
},
success: function(result){
// parse json
const data = JSON.parse(result);
$('#modalSuccess').modal('show');
}
});
});

JQuery ajax call failing but the direct URL works

I have a simple Jquery code which makes an ajax call to a php code.
$(document).ready(function(){
var $isbn = $('#isbn');
var $authorName = $('#authorName');
var $bookTitle = $('#bookTitle');
$('#searchButton').click(function(){
var isbnValue = $isbn.val();
var authorNameValue = $authorName.val();
var bookTitleValue = $bookTitle.val();
alert(isbnValue);
$.ajax({
type: "GET",
url: "php/getBooks.php",
dataType: "json",
data: {
isbn: isbnValue
},
success: function (data) {
alert(data);
},
error: function(data) {
alert(data);
}
});
});
});
And my PhP code connects to the Database and fetches data based on the query string. Here is my PhP code.
<?php
$dsn = 'mysql:dbname=library;host=localhost';
// 'mysql:host=localhost;dbname=myDatabase'
$username = 'root';
$password = 'maddie';
$isbnValue = $_GET["isbn"];
try {
$db = new PDO($dsn, $username, $password); // also allows an extra parameter of configuration
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$isbn = $db->quote($isbnValue);
$rows = $db->query("SELECT isbn, title FROM book WHERE isbn = $isbn");
$names = array();
foreach ($rows as $row) {
$names[] = array($row['isbn'], $row['title']);
}
print json_encode($names);
} catch(PDOException $e) {
die('Could not connect to the database:<br/>' . $e);
}
?>
When I execute from jQuery I get the below error object as response
Object {readyState: 0, responseText: "", status: 0, statusText: "error"}
Wherease if I directly call the php code using the URL -
http://localhost/LibraryManagement/php/getBooks.php?isbn=970880812
I get the json object as the result. I am not sure where the error is. Any help would be helpful. Thanks in advance.
The code you supplied seems functional. I even tested it locally with jQuery 1.12.1 and had no problems at all.
The error you are receiving is indicative of an ajax call being interrupted before it gets completed. there are many things that can cause this. The most common include cross domain issues and using links or forms actions in concert with your ajax call.
See the following article for more details on this:
http://www.justinball.com/2013/02/25/jqxhr-returning-readystate-0-and-status-0/
A quick google search for:
{readyState: 0, responseText: "", status: 0, statusText: "error"}
will reveal a number of other situations where that can occur as well.
Hope this helps ;)

Ajax / JSON / PHP database data

I'm more of a designer but I need to grab some data from a database. I would be able to get what I need without problem using PHP but I'm creating a mobile app in Phonegap so can't use anything other than HTML, CSS or JS.
I've read that this can be done in a PHP file on the server, encoded to JSON and then grabbed in the HTML with Ajax.
Can anyone show me how do I do this, as simply as possible please?
Javascript file
$.ajax({
type: "GET",
dataType: "JSON",
url: "php/phpDb.model.php",
data: {
sataVariable: "here is some data send with GET method"
},
success: function(data) {
console.log(data);
},
error: function(data) {
console.log(data);
}
});
php file (phpDb.model.php)
// Connect to database
$con = mysqli_connect("host", "userName", "password", "database")
or die('{ "error" : true, "errorMessage" : "Cannot connect to database '.mysqli_error($con).'"}');
// Query
$sqlCalling = "SELECT * FROM table WHERE ";
$result = mysqli_query($con,$sqlCalling);
$rowCalling = mysqli_fetch_array($resultCalling);
mysqli_close($con);
//getting column_1 and column_2
$column_1 = $rowCalling['column_1'];
$column_2 = $rowCalling['column_2'];
// Return a JSON parseable array
return array(
"column_1" => $column_1 ,
"column_2" => $column_2 ,
);
This solution is very generic, you will most likely just replace the name of the tables and the name of column with what they actually are in your database.
This is a very basic example using jQuery:
//hello_world.js
$.ajax({
url:'hello_world.php',
type: 'POST'
data: { 'var' : 'Hello World' }
}).done(function(response){
alert(response); //Well now alert an json string based on your query..
});
//hello_world.php
$STH = $DBH->prepare("SELECT blabla FROM table WHERE column = ?");
$STH->execute(array($_POST['var']));
$STH->setFetchMode(PDO::FETCH_ASSOC);
$resultQuery = $STH->fetchAll();
echo json_encode($resultQuery); //

Variable isn't considered as object when called by Ajax

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.

Returned JSON data undefined when using PDO with bindParam

I've been all over stackoverflow trying to figure this out. I'm using jQuery's ajax method to send in some form data, and PDO to prepare and return data based on the form input. I have one parameter in the prepared statement, which is taken from the form data, and set using the PDO bindParam method.
Using the form data, the json data I get back is undefined. If I hardcode the string parameter rather than use the form data, I get back the data I'm looking for. I've echoed out the exact value and type of the variable I'm passing in, and it's the same as the hardcoded string. I've tried explicitly setting the encoding to ensure it's utf8 as well.
This is what my php looks like (EDIT: includes execute method, which is included in my code, but got left out initially in the post):
$endorsers = array();
// Takes in the values from checkbox form data
foreach($_POST as $k => $v) {
if($v == 'on') {
$endorsers[] = $k;
}
}
// Set variable to first checkbox value
$endorser = $endorsers[0];
try {
$connection = new PDO('mysql:host=localhost;dbname=*****;charset=utf8', $username, $password);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$statement = $connection->prepare('SELECT DISTINCT c.name AS cand_name, e.name AS end_name FROM candidates c JOIN end_cand ec ON (ec.end_id = c.id) JOIN endorsements e ON (e.abbrev = :endorser)');
$statement->bindParam(':endorser', $endorser, PDO::PARAM_STR);
$statement->execute();
$results = $statement->fetchAll();
if (isset($results)) {
echo json_encode($results);
} else {
$error = array('error_message' => 'Sorry, Charlie');
echo json_encode($error);
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
And the ajax:
$("document").ready(function() {
$("form").submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "get-endorsements.php",
success: function(data) {
console.log(data[0]);
console.log(data[1]);
}
})
})
});
If I do a regular form submission just to view the echoed json encoded results, I get the same thing whether using a hardcoded string or the form data - it's in this form:
[{"key1":"value1","key2":"value2"},{"key1":"value3","key2":"value4"}].
The data returned via ajax is undefined when using the form data variable though, and I can't figure out why this is making a difference.
SOLUTION:
$("form").submit(function(e) {
e.preventDefault();
var data = $(this).serialize();
console.log(data);
$.ajax({
type: "POST",
//contentType: "application/json; charset=utf-8",
dataType: "json",
data: data,
url: "get-endorsements.php",
success: function(data) {
console.log(data[0]);
console.log(data[1]);
}
})
})
Had to pass in data via $.ajax (thanks #David-SkyMesh), and NOT set the contentType (since this is the contentType for data passed to the server, not data received). Got myself very confused thinking that the data was available simply via the $_POST variable b/c it was, of course, when I tested the PHP return values with a standard post method on the form instead of via Ajax.
I think you lost:
$results->execute();
before
$results = $statement->fetchAll();
$endorsers = array();
// Takes in the values from checkbox form data
foreach($_POST as $k => $v) {
if($v == 'on') {
$endorsers[] = $k;
}
}
// Set variable to first checkbox value
$endorser = $endorsers[0];
try {
$connection = new PDO('mysql:host=localhost;dbname=*****;charset=utf8', $username, $password);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$statement = $connection->prepare('SELECT DISTINCT c.name AS cand_name, e.name AS end_name FROM candidates c JOIN end_cand ec ON (ec.end_id = c.id) JOIN endorsements e ON (e.abbrev = :endorser)');
$statement->bindParam(':endorser', $endorser, PDO::PARAM_STR);
$results->execute();
$results = $statement->fetchAll();
if (isset($results)) {
echo json_encode($results);
} else {
$error = array('error_message' => 'Sorry, Charlie');
echo json_encode($error);
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}

Categories