PHP and JQuery weird behaviour - javascript

I have a 3-tier architecture. The db is oracle, the business/logic layer is php, while the front end is html/JavaScript. My business/logic layer have a bunch of unit tests that only pass if the requirements are met. The problem occurs when I wire the business layer and front end via javascript. After a lot debugging, I found the sources of the problem:
JavaScript code causing error.
function getAllUsers() {
var allUsers = [];
$.ajax ({
url: '../php/get-all-users.php',
success:function(data){
allUsersJSON = JSON.parse(data);
console.log(allUsersJSON);
for (var i = 0; i < allUsersJSON.length; i++){
allUsers[i] = allUsersJSON[i].USER_NAME;
}
console.log(allUsers);
}
});
return allUsers;
}
../php/get-all-users.php
<?php
include_once 'Database.php'
$db = Database::instance(); // Singleton to initialize db.
echo json_encode($db->getAllUsers());
?>
Database.php fragment.
public function createConnection($username, $password, $connectionString){
$this->_connection = oci_connect($username, $password, $connectionString);
if (!$this->_connection) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
throw new Exception("Database connection failed. Please check constructor arguments.");
}else{
//print "Database connection established.\n";
}
}
In one of my tests, I tried echo json_encode($db->getAllUsers()); and get a result, "[\"USER_NAME\":\"userName\"]". In get-all-users.php, if I comment out everything, and echo the string I get from the tests, the web page now loads fine, but of course this is not what I desired. Furthermore, if I uncomment include_once 'Database.php' in get-all-users.php and comment out oci_connect in my Database.php, the web page loads fine. This made me conclude that the root of the problem is oci_connect.
Did anyone else have a similar experience? I tried googling but found no result. If you need more information to make light of this problem, I'd gladly spew them out.
Edit:
I'm working in linux. My team mate is working with Windows and he have no problems like this.

Related

How can I send HTML data to PHP using JSON?

I can't seem to understand how to send data from my Client-side HTML to my Server-side PHP (Which already means their not in the same folder and are not running in the server) and only get a Notice of an unidentified variable and a Fatal error: Cannot access empty property.
I tried the methods in W3Schools and still no luck. And just to be sure I tried to copy paste it. Still the same.
So my question is: How can I send this simple Client-side HTML/JavaScript data:-
<script>
function sender(){
obj = "tblname";
// how to send that data to the php server-side.
}
</script>
To this PHP:-
<?php
header("Content-Type: application/json; charset=UTF-8");
$obj = json_decode($_GET["x"], false);
$conn = new mysqli("localhost", "root", "", "mydb");
$result = $conn->query("SELECT * FROM ".$objData);
$outp = array();
$outp = $result->fetch_all(MYSQLI_ASSOC);
echo json_encode($outp);
?>
Using JSON?
If anyone could elaborate and show me a sample it would be great.
Again, I am a noob/newb in using JSON and have no long term background (I just started like a week ago and that had a lot of problems already) and am completely clueless when it comes to this type of client-to-server communication.
I Just need the simple sender code (from the JavaScript) and the receiving code (from the Php) one or two lines will do; with a short description on how they work.
I'm using Windows 7, Wamp3.0.6 and Chrome.
PS: I got that from W3Schools. Yes it didn't work. And please don't be Vague. Thank you!
You can make ajax call form client side to server file and can send data with get method
// Using the core $.ajax() method
$.ajax({
// The URL for the request
url: "path of your php file",
// The data to send (will be converted to a query string)
data: {
id: 123
},
// Whether this is a POST or GET request
type: "GET",
// The type of data we expect back
dataType : "json",
})
// Code to run if the request succeeds (is done);
// The response is passed to the function
.done(function( json ) {
})
// Code to run if the request fails; the raw request and
// status codes are passed to the function
.fail(function( xhr, status, errorThrown ) {
alert( "Sorry, there was a problem!" );
})
// Code to run regardless of success or failure;
.always(function( xhr, status ) {
alert( "The request is complete!" );
})
-_-
Everyone seems to try and over complicate and over think this when the simple answer would have been this code.
function caller(){
myData = "myTbl";
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "bring.php?q="+myData,true); //sends myData to the php. You can change the GET to POST if ya want to be extra safe but either way, the php won't care anyways.
xmlhttp.send();
}
The above code is from the client server and sends the data of myData to this Server-side php.
<?php
$q = $_REQUEST['q']; //the receiver of the data. You can use explode() to separate them into pieces and turn it into a jigsaw puzzle if ya want.
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "Mydb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} // how to connect is not important in my question but it is important for you to be able to connect to the database.
// now for the important stuff
$sql = "SELECT * FROM ".$q." "; // I had to extend it with a space because sometimes it's misunderstood.
$result = mysqli_query($conn, $sql) or die("Error in Selecting " . mysqli_error($conn));
$outp = array();
while($row=mysqli_fetch_assoc($result))
{
$outp[] = $row;
}
echo json_encode($outp); //sends the data gathered from the database table back to the client as a JSON file, and you are done.
?>
It took me 6 hours worth of studying with a lot of internet surfing and trials and errors.
And like I said; I am a newb at JSON so it's pretty much understood that I don't understand AJAX. Like, AT ALL.
I'm sorry if ya think I sound like an idiot but let's face it, almost all of us were idiots at one point while trying to learn programming. So, I'm surprised why some people are just plain rude here. Thanks. Somehow I'm not really surprised that their also like this here. Makes my internet social life a bit more boring.
So next time, do me a favor and instead of being totally rude, just answer the question if you have one.
You cannot transfer an object via HTTP as it is. You need to transform it into a string you can put into the body of your HTTP-POST Request:
try {
var jsonString = JSON.stringify(anyJsonObject);
//send it to the server
} catch(ex) {
//handle error if anyJsonObject wasn't a valid JSON object. Remember: Not every JS object is a JSON object too.
}
The opposite way is:
try {
var jsonObject = JSON.parse(anyJsonString);
} catch(ex) {
//handle error if anyJsonString was malformed
}

Server error 500 in PHP

So today I have another small little issue with my PHP, that is causing me to get a server error. You see, I have this javascript function:
$.post('script.php', { limit: str }, function(result) {
console.log(result);
});
which of course makes a call to my php file:
require_once("../data/db-settings.php");
require_once("../data/file.php");
global $pdo;
$list = array();
$limit = $_POST["limit"];
chop($limit, ";");
$stmt = $pdo->prepare("SELECT cust_id, cust_addr FROM project WHERE " . $limit . " = cust_id");
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$list[] = $row;
}
echo $list;
The point of the php is to grab some information from a database that a user can dynamically change and use. The issue, I'm assuming, is with how I'm using PDO, because the code I'm using is in working order in another section. I also know that my function call is sending data and working properly, because when I check for just what I send, it sends properly.
Thanks for any help guys.
Check your query FROMproject can not be together.
Your query should look like this:
$pdo->prepare("SELECT cust_id, cust_addr FROM project WHERE " . $limit . " = cust_id");
It is an unobvious error!
So you step by step following the : http://pcsupport.about.com/od/findbyerrormessage/a/500servererror.htm
PDO doesn't throw Internal server error. Must be require_once.
checkout db-settings.php and file.php files. Require_once throws 500 error if it can't find files.
If the paths are correct, then check out included files.
proper way: check your log files.

Unable to get data from database using AJAX & PHP

Update: The first part of this question has been solved and has been updated below with the working code.
~
I’m working on a Javascript application and I’m having difficultly getting an AJAX call to work.
I’m able to successfully insert data into my database using AJAX POST & PHP but I can’t seem to pull data from the database.
I have a Javascript application which uses an image, currently it gets this image from a location in the root folder like this:
img.src = 'picture1.jpg';
Instead of doing this, I want to select a random image from a table in the database every time the Javascript application loads.
I’ve created a table with a single column, and populated this with the addresses/locations of images contained in a folder in my root directory.
For example:
/images/00001.jpg
/images/00002.jpg
/images/00003.jpg
This is the PHP file (located at /scripts/imagerandomizer.php) I’m using to call a random image address:
<?php
session_start();
$servername = "localhost";
$username = "myusername";
$password = "mypassword";
$dbname = "mydatabase";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sqlrandomize = mysqli_query($conn,"SELECT images FROM `images` ORDER BY RAND( ) LIMIT 0 , 1");
$row = mysqli_fetch_row($sqlrandomize);
header('Content-Type: application/json');
echo json_encode($row);
mysqli_close($conn);
?>
And the AJAX which initiates the PHP & listens for the echo:
function getRandomImage() {
$.ajax({
url: 'scripts/imagerandomizer.php',
data: "",
dataType: 'json',
success: function(response){
alert(response);
}});
};
I’m trying to use alert(data); to have the randomly chosen image location/address appear in an alert box (just to see if it’s working). But it’s not working for me, I’m pretty sure I've made a mistake somewhere, and I’m not sure if json is the right data type to use here?
I would like to have the returned address replace the current img.src = 'image.jpg'; , so that when the Javascript application starts, it will receive a random image from the img.src = section of code.
Thanks for any help on this!
UPDATE:
The Javascript can now correctly display a random address (using either “alert” or “console.log”) every time it’s loaded. The last part of my question concerns how to have a .js file read this string, and use it as the location of an image that it then fetches.
This is how my game is set up:
I have a file named “game.js”, it contains the code needed for the game to operate, right now, part of that code is this: img.src = 'images/image00001.jpg'; Right now that image is permanently defined and doesn’t change. I’m trying to replace this static definition with the randomized one. Basically I’m trying to get the randomized address to appear after img.src = whenever game.js loads.
I also need to make sure that this event happens before the rest of the game.js code initiates, as I need the randomly chosen image file to be in place before the rest of the game loads.
I’ve tried defining img.src by including img.src=(response) in the AJAX call at the top of the game.js file but it’s failing to load any image into the game. I’m thinking that maybe this is the wrong way to do this?
2nd UPDATE
Hi #PHPGlue
I’ve been trying to get this to work for days now but I’m still missing something.
This is my function to grab the randomized image, and I’ve tried to place the code to run the game in the success function if (img.src) {//code to run the game here}:
Function getRandomImage() {
$.ajax({
url: 'scripts/imagerandomizer.php',
data: "",
dataType: 'json',
success: function(response){
$('#imageId').attr('src', data.image);
img.src = $('#imageId');
if (img.src) {
//code to run the game here
}
}});
};
I’m definitely missing something here, I think I’m not understanding what you mean correctly. I’d really appreciate any advice on this and thank you again for taking the time to look at my question!
3rd Update
Hi, my current code is:
function getRandomImg(gameFunc){
$.post('scripts/imagerandomizer.php', {randImg:1}, function(data){
var im = $('#imageId');
im.attr('src', data.image);
im.load(function(){
gameFunc(img.src=im);
}
}, 'json');
}
getRandomImg(function(){
javascriptgame();
});
function javascriptgame(){
//in this area I’ve placed all the code to make the game work
}
When you said /* pass args to gameFunc here */ I entered img.src=im. (I’m not sure I understand you correctly but I think I’m supposed to define the img.src= for the game to call in this line?
When you said // game code here - could also pass function name instead of Anonymous function, I created a new function called javascriptgame, inside which I placed the game’s code, and then called this function at this line. I’m not sure if that’s what you meant for me to do?
Unfortunately right now there’s still no image loading into the game, I want to thank you again for taking the time to help me with this and if you could offer any more advice that would be awesome! Thanks so much.
The problem is with your mysqli_query()
It should be like
mysqli_query(connection,query,resultmode)
Where connection and query are required and resultmode is optional.
Example:
mysqli_query($conn,"SELECT images FROM images ORDER BY RAND( ) LIMIT 0 , 1");
For more details please check out
mysqli_query
First you should make a separate secure PHP connection page
// connection.php
<?php
function db(){
return new mysqli('host', 'username', 'password', 'database');
}
?>
You're problem is that you don't actually get any results by just making a query. You still have to get the query results and use them in your code:
<?php
include 'connection.php'; $db = db(); $r = array();
if(isset($_POST['randImg'])){
if(+$_POST['randImg'] === 1){
if($iq = $db->query('SELECT images image FROM images ORDER BY RAND() LIMIT 1')){
if($iq->num_rows > 0){
$fi = $iq->fetch_object(); $r['image'] = $fi->image;
}
else{
// no results were found
}
$iq->free();
}
else{
// connection failure
}
}
else{
// randImg hack
}
}
echo json_encode($r);
$db->close();
?>
Get that in JavaScript as data.image inside your success function.
function getRandomImg(gameFunc){
$.post('scripts/imagerandomizer.php', {randImg:1}, function(data){
var im = $('#imageId');
im.attr('src', data.image);
im.load(function(){
gameFunc(/* pass args to gameFunc here */);
}
}, 'json');
}
getRandomImg(function(){
// game code here - could also pass function name instead of Anonymous function
});

Mysqli query is returning a null value for a simple row of strings from a DB

I am trying to retrieve a single row from a MySQL table using a mysqli statement. I've tried several different iterations of code, subtly changing the structure based on various previous questions from this forum, and others, but can't seem to get any result other than 'null'.
This is part of a larger script which is called via an Ajax request with jQuery. I've included both the PHP and the Javascript below, though I'm fairly confident in the JS being OK (preparing to be told otherwise now...).
Any suggestions as to where I'm going wrong would be very much appreciated as I can't see the wood from the trees anymore, and am just going around in circles.
PHP:
//initiate new mysqli object
$retrieve_link = new AuctionMySQLi($db_host, $db_user, $db_password, $db_name); //custom subclass, this definitely works as is used in other scripts on the server
//prepares DB query. Query has been tested on phpmyadmin and returns the expected data set
$stmt = $retrieve_link->prepare("SELECT `item_number`,`item_name`,`item_category`,`end_date`,`auction_type`,`high_bid_number` FROM `item` WHERE `item_number`=2");
$stmt->execute(); //no params to bind, so execute straight away
$stmt->bind_result($item);
$stmt->fetch();
$dataset = $item->fetch_row();
$response[0] = $dataset; //returned data forms part of larger dataset
echo json_encode($response); //return the entire dataset to a jquery Ajax request
die;
JS:
//this definitely works as objects have been returned via the 'success' function as the code was being developed
$.ajax({
url : "items/populate-home-page-script.php",
type : "GET",
data : {data:toSend},
dataType : "json",
success : function(data){
alert(data[0]);
},
error : function(jqXHR, textStatus, errorThrown){
alert(textStatus+','+errorThrown);
}
});
return false;
I have also tried using fetch_assoc() and fetch_row() as part of the PHP query, taking direction from the PHP reference material here and here. I have also read through these questions from Stackoverflow this, this, and this, but I still seem to get a return of null for every different code combination I try.
As I've said in a code comment, I know that the link to the DB works as I've used it in other scripts, and in other areas in this script - so there's no reason why this object wouldn't work either. I also know that the query returns the expected data when inputted to phpmyadmin.
The returned data is just a number of strings, any all I would like to do is store around 16 returned datasets to an array, as part of a loop, and then return this array to the Ajax request.
You are using "AuctionMySQLi" which appears to extend the regular Mysqli driver. I'll assume it does this correctly.
You're using prepared statements which is probably an overkill in this case. You could accomplish the same thing with something like this (php 5.3, mysqli + mysqlnd):
$retrieve_link = new AuctionMySQLi($db_host, $db_user, $db_password, $db_name);
$result = $retrieve_link->query("SELECT `item_number`,`item_name`,`item_category`,`end_date`,`auction_type`,`high_bid_number` FROM `item` WHERE `item_number`=2");
if($result !== false) {
echo json_encode($result->fetch_all());
} else {
echo json_encode(array());
}
$retrieve_link->close();
If you're using an older php version, or mysqlnd is not available, you can also do
$retrieve_link = new AuctionMySQLi($db_host, $db_user, $db_password, $db_name);
$result = $retrieve_link->query("SELECT `item_number`,`item_name`,`item_category`,`end_date`,`auction_type`,`high_bid_number` FROM `item` WHERE `item_number`=2");
if($result !== false) {
$output = array();
while($row = $result->fetch_assoc()) {
$output[] = $row;
}
echo json_encode($output);
} else {
echo json_encode(array());
}
$retrieve_link->close();
I also understand that you want to limit the number of results. In both cases, a good way of getting it done is to use a LIMIT statement in SQL. This is lower the overhead overall at source. Otherwise you can array_slice to slice the output of result->fetch_all() in solution 1, or $output in solution 2.
Finally, if you insist in using prepared statement read the note at
http://ca2.php.net/manual/en/mysqli-stmt.bind-result.php
and analyze provided example:
$retrieve_link = new AuctionMySQLi($db_host, $db_user, $db_password, $db_name);
$stmt = $retrieve_link->prepare("SELECT `item_number`,`item_name`,`item_category`,`end_date`,`auction_type`,`high_bid_number` FROM `item` WHERE `item_number`=2");
$stmt->execute();
$stmt->bind_result($itemName, $itemCat, $endDate, $auctionType, $highBidder);
$output = array();
while($stmt->fetch()) {
$output[] = array($itemName, $itemCat, $endDate, $auctionType, $highBidder);
}
echo json_encode($output);
$retrieve_link->close()
It looks to me like you may have some confusion about ->fetch() and ->fetch_row(). You should use one or the other, but not both.
Try this to retrieve your result set:
$stmt->execute();
while ($dataset = $stmt->fetch_row()) {
$response[] = $dataset; //returned data forms part of larger dataset
}
This will append each row of your result set to your $response array.

Ajax and jquery not sending data correctly to php

I created a basic form that uses jquery (ajax) to send data to php. PHP should insert a new record based on the data to a mysql database. The reason for this is because I want to make insertions to the database without having to submit the whole form and then use the submit action for something else later. It seems that the jquery works fine since the alert() shows the correct output for the variables, but the PHP does not insert the data and I don't get an error. I can't figure out why this isn't working? I think it is a problem with my $post() because the function underneath does not execute but I can't pinpoint the error. Any help debugging this would be really appreciated. Or if anyone knows another way to get the same functionality that would be great too? Thanks. (The code below works fine now. I figured out it was a type cast error, and I fixed it. Hopefully someone can find this useful!)
<script type="text/javascript">
function submitgrade(){
alert("In it");
var classID = $("#classSelect").val();
var student = $("#studentSelect").val();
var exam = $("#Exam").val();
var grade = $("#grade").val();
alert(classID+" - "+student+" - "+exam+" - "+grade);
$.post('submitgrade.php',{postclassSelect:classID,poststudentSelect:student,postExam:exam,postgrade:grade}, /*1*/
function(data){
$("#grade").html("");
});
};
</script>
<?php /*submitgrade.php*/
$con=mysqli_connect("localhost","root","","studentbase");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$classID = $_POST['postclassSelect'];
$studentID = $_POST['poststudentSelect'];
$examID = $_POST['postExam'];
$grade = $_POST['postgrade'];
echo $studentID[0]." examID: ". $examID[0];
$gradequery = "INSERT INTO grade VALUES(".intval($studentID).", '".$classID."', ".intval($examID).", ".intval($grade).");";
$result = $con->query($gradequery);
while($row = $result->fetch_assoc())
{
echo "<br /><p>Grade of ". $grade." submitted for exam ". $row['exam_id'] ." in ". $row['class_ID'] ."</p>";
}
?>
Have you include this line in your html page ??
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
An example is here again, may help you
<script>
$(document).ready(function(){
$("input").keyup(function(){
txt=$("input").val();
$.post("my_page.asp",{suggest:txt},function(result){
$("span").html(result);
});
});
});
but your code seems correct too buddy !!
I suggest to continue debugging by attaching an error handler to your $.post call, your code could look this:
$.post('submitgrade.php', {postclassSelect:classID,poststudentSelect:student,postExam:exam,postgrade:grade})
.done(function(response) {
// success
}).fail(function(response) {
// failure
});
Further more you should check:
Is the script running on a server? ajax might not work on a file:/// address
Is the path from javascript location to php file correct?
what do the browser developer tools say about the request that is initiated?
I fixed it. It was actually just a syntax error in my SQL and a type difference error with one of my database columns. The $grade variable is passed into PHP as a string. Once I wrapped all of my variables in intval() it worked as intended. Stare at the code to long, sometimes you go blind. Haha.
Thank you omnidan for the tip about sanitization. Here is a good guide that I used to apply it to my app:
http://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data

Categories