mysql query doesn't work together with cross domain in ajax - javascript

my problem is the following...
I made some php code that reads records from a mysql database:
$host = $_SESSION['host'];
$username = $_SESSION['username'];
$password = $_SESSION['password'];
$db = $_SESSION['db'];
$con = mysqli_connect($host,$username,$password,$db);
$sql = "SELECT * FROM `table`";
$result = $con->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
...
}
}
my html:
<button onclick="list">submit</button>
<div id="output"></div>
<script>
var thisHost = "host.php";
function list() {
$.ajax({
type: 'POST',
url: thisHost,
data: "list=true",
success: function(data)
{
$("#output").html(data);
},
error: function (responseData, textStatus, errorThrown)
{
console.warn(responseData, textStatus, errorThrown);
}
});
}
</script>
as far as that everything is working fine. However now i want to call the php code from another host. Therefor the html file is on the other host (localhost:81) and the php file stays on the old host (localhost:80).
now I noticed that i need a something to cross the domain because ajax doesn't seem to work with other hosts. So all i did was adding these lines to the php code right at the beginning:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Content-Type');
and change the value of the thisHost var in javascript to
"http://localhost:80/host.php"
after that the ajax part works again and the php response. However every time i want to make a query by doing something like this:
$sql = "SELECT * FROM `table`";
i will get this error:
Fatal error: Uncaught Error: Call to a member function query() on null
in C:\path\to\host.php:71 Stack trace: #0 {main} thrown in
C:\path\to\host.php on line 71
i'm pretty sure that the query is correct. So what do i need to change?

Calling a method on an invalid handle will produce errors like this. Always check that your connection request succeeded and handle any errors that could have occurred.
Turning on mysqli exceptions makes these things a lot harder to ignore.

Related

500 Internal Server Error From PHP - Insert Data Into VFP9 Database

I'm trying to write an API script in PHP to insert records into a Foxpro 9 database but i'm getting the "500 Internal Server Error" message when the API is called. I'm a Foxpro developer but pretty new to PHP.
I've gone through several questions & comments on the topic on this site and other sites and have implemented almost all of the suggested solutions to no avail. Below are the steps i've taken so far:
IIS & PHP are installed and configured. (phpinfo() is displaying correctly)
VFP 9 is fully installed. (with VFPOLEDB driver)
I've fully cleared browsing data severally.
I'm not sure where the problem is (as the "500 internal server error" message could be a problem with the PHP script or PHP configuration. Could somebody please take a look at the PHP script below to help figure out the problem?
TIA.
<?php
// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
// database connection
$conn = new COM("ADODB.Connection");
$conn->Open("Provider=VFPOLEDB.1;Data Source=C:\inetpub\wwwroot\sonreceipt\RECEIPT.DBC;Collating Sequence=Machine");
// get posted data
$data = json_decode(file_get_contents("php://input"));
// set payment values received
$jrefnum = $data->refnum;
$jpaydate = $data->paydate;
$jcustname = $data->custname;
$jcustemail = $data->custemail;
$jdemandno = $data->demandno;
$jdemanddate = $data->demanddate;
$jamount = $data->amount;
$jrecpdesc = $data->recpdesc;
$jpaybank = $data->paybank;
$jpayref = $data->payref;
// create the payment
if(create()){
echo "Payment was created.";
}
// if unable to create the payment, tell the user
else {
echo "Unable to create payment.";
}
// create payment
function create(){
// query to insert record
$query = "INSERT INTO SON2100 (refnum, paydate, custname, custemail, demandno, demanddate, amount, recpdesc, paybank, payref)
VALUES ($srefnum, $spaydate, $scustname, $scustemail, $sdemandno, $sdemanddate, $smount, $srecpdesc, $spaybank, $spayref)";
// prepare query
global $conn
$stmt = $conn->prepare($query);
// sanitize
global $jrefnum, $jpaydate, $jcustname, $jcustemail, $jdemandno, $jdemanddate, $jamount, $jrecpdesc, $jpaybank, $jpayref;
$srefnum=htmlspecialchars(strip_tags($jrefnum));
$spaydate=htmlspecialchars(strip_tags($jpaydate));
$scustname=htmlspecialchars(strip_tags($jcustname));
$scustemail=htmlspecialchars(strip_tags($jcustemail));
$sdemandno=htmlspecialchars(strip_tags($jdemandno));
$sdemanddate=htmlspecialchars(strip_tags($jdemanddate));
$samount=htmlspecialchars(strip_tags($jamount));
$srecpdesc=htmlspecialchars(strip_tags($jrecpdesc));
$spaybank=htmlspecialchars(strip_tags($jpaybank));
$spayref=htmlspecialchars(strip_tags($jpayref));
// execute query
if($stmt->execute()){
return true;
}
return false;
}
?>
Below is the javascript that calls the API.
<script>
function sendData(data) {
var XHR = new XMLHttpRequest();
var jsonData = {"refnum":"1111-2222-3333", "paydate":"01-06-2018", "custname":"O. A. BECKLEY VENTURES", "custemail":"beckleyventures#gmail.com", "demandno":"DEMAND NOTE 001", "demanddate":"01-06-2018", "amount":"15550.00", "recpdesc":"SONCAP", "paybank":"ZENITH BANK PLC", "payref":"0123456789"};
// Define what happens on successful data submission
XHR.addEventListener('load', function(event) {
window.alert('Yeah! Data sent and response loaded.');
});
// Define what happens in case of error
XHR.addEventListener('error', function(event) {
window.alert('Oops! Something goes wrong.');
});
// Set up our request
XHR.open('POST', 'http://localhost/sonreceipt/api/create_payment.php', true);
// Add the required HTTP header for form data POST requests
XHR.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
// Finally, send our data.
XHR.send(jsonData);
}
</script>
Here is the edited script but still not working. As indicated earlier, i'm still new to PHP.
<?php
// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
// database connection
$conn = new COM("ADODB.Connection");
try {
$conn->Open('Provider=VFPOLEDB.1;DSN=RECEIPT;Mode=ReadWrite;Password="";Collating Sequence=MACHINE;');
if (! $conn) {
throw new Exception("Could not connect!");
}
}
catch (Exception $e) {
echo "Error (File:): ".$e->getMessage()."<br>";
}
if (!$conn)
{exit("Connection Failed: " . $conn);}
echo "Connection Sucessfull";
// get posted data
$data = json_decode(file_get_contents("php://input"));
// set payment values received
$jrefnum = $data->refnum;
$jpaydate = $data->paydate;
$jcustname = $data->custname;
$jcustemail = $data->custemail;
$jdemandno = $data->demandno;
$jdemanddate = $data->demanddate;
$jamount = $data->amount;
$jrecpdesc = $data->recpdesc;
$jpaybank = $data->paybank;
$jpayref = $data->payref;
// create the payment
if(create()){
echo "Payment was created.";
}
// if unable to create the payment, tell the user
else {
echo "Unable to create payment.";
}
// create payment
function create(){
global $conn;
global $jrefnum, $jpaydate, $jcustname, $jcustemail, $jdemandno, $jdemanddate, $jamount, $jrecpdesc, $jpaybank, $jpayref;
// sanitize
$srefnum=htmlspecialchars(strip_tags($jrefnum));
$spaydate=htmlspecialchars(strip_tags($jpaydate));
$scustname=htmlspecialchars(strip_tags($jcustname));
$scustemail=htmlspecialchars(strip_tags($jcustemail));
$sdemandno=htmlspecialchars(strip_tags($jdemandno));
$sdemanddate=htmlspecialchars(strip_tags($jdemanddate));
$samount=htmlspecialchars(strip_tags($jamount));
$srecpdesc=htmlspecialchars(strip_tags($jrecpdesc));
$spaybank=htmlspecialchars(strip_tags($jpaybank));
$spayref=htmlspecialchars(strip_tags($jpayref));
// query to insert record
$query = "INSERT INTO SON2100 (refnum, paydate, custname, custemail, demandno, demanddate, amount, recpdesc, paybank, payref)
VALUES ($srefnum, $spaydate, $scustname, $scustemail, $sdemandno, $sdemanddate, $smount, $srecpdesc, $spaybank, $spayref)";
// prepare query
$stmt = $conn->prepare($query);
// execute query
if($stmt->execute()){
return true;
}
return false;
}
?>
You haven't declared the variables used in the value portion of the SQL in your create() function and you're missing a semicolon
// you have
global $conn
// should be
global $conn ;
Use
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
to find your error.

Parsing JSON data with a local AJAX request

I've got a php file on a webserver that executes queries to a MySQL database.
I'm testing a site on my pc (locally) that uses a js file with an AJAX request to get JSON data from that php file.
Is it possible to do it like this, or the js file must be put on the same domain server of the php file?
Because the console.log of the parsed data gives me this error:
Uncaught SyntaxError: Unexpected token I
This is the ajax call
$.ajax({
method:"POST",
crossDomain:true,
url:"url for the php file",
data:{
query: "SELECT * FROM course_categories;"
},
success: function(response){
var course_categories=JSON.parse(response);
console.log(course_categories);
var el="";
console.log(course_categories.length);
for(var i=0;i<(course_categories.length);i++)
{
}
},
error: function(request,error){
console.log("ERROR: Request " + request + "\nSpecific Error: " + error);
}
While this is the PHP call
<?php
//get all the courses from the database and reply using the JSON structure
//$mysqli=new msqli("localhost","username","password","dbname");
$mysqli=new mysqli("localhost","hey","","db_name");
if(mysqli_connect_errno()) //returns a number of the error if there is any, if not
{
echo json_encode("Error to connect to DBMS".mysqli_connect_error());
exit(); //closes the connection
}
else
{
$query=$_POST["query"];
//$query="SELECT * FROM course_categories";
$result=$mysqli->query($query); //do a query (->query) setted by $query, using the $mysqli variable, and store the data in $result
if($result->num_rows >0) //if there is at least one row...
{
$myArray= array(); //...create an array...
while($row = $result->fetch_array(MYSQL_ASSOC))
{
//...and fetch it. Everytime this operation returns a row,
$myArray[]=$row; //...and added to myArray ([] means autoincrement).
}
}
echo json_encode(utf8ize($myArray));
//free result
$result->close();
//close connection
$mysqli->close();
}
I did it. All I had to do, was to remove the crossDomain:true line so that the JSON could actually parse the data.

How do I connect my ajax post to php and mysql?

I spent hours testing all my code, step by step, and still can't make it work. I eventually got the php file to send a test object to the mysql database but I still can't get the jQuery ajax post to connect to php. Can anyone spot the issue? I get the "500 internal server error" message when I run the code.
Javascript:
var jsonEntry = {"timestamp":"2015/01/21 22:18:00","note":"hi there","tags":["one", "two"]};
// send json converted object to php file via ajax
$("#sendButton").click(function () {
$.ajax({
url: 'php/ajax.php',
type: 'POST',
dataType: 'JSON',
data: jsonEntry,
error :
function(xhr, status, error) {
alert(xhr.status);
alert(error);
},
success :
function(data) {
console.log('send success');
}
});
});
PHP code from "ajax.php:"
<?php
if(isset($_POST["data"])) {
$json = file_get_contents('php://input');
$obj = json_decode($json, true);
$timeStamp = $obj[timestamp]; //added semicolon here
$note = $obj[note];
$tags = $obj[tags];
//Connecting to a database
//Connection info
$hostname = "localhost";
$username = "root";
$password = "root";
//Code to connect
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
// Select database to work with
$selected = mysql_select_db("notes", $dbhandle)
or die("Could not select examples");
//Execute SQL query and return records
mysql_query("INSERT INTO notes (dateAndTime, noteBody, noteTags) VALUES ('$timestamp', '$note', '$tags')");
// Close the connection
mysql_close($dbhandle);
}
?>
UPDATE:
I have added the semicolon where needed in the php file but now get error 200, "SyntaxError: JSON Parse error: Unexpected EOF."
I think the problem is a missing semicolon here:
$timeStamp = $obj[timestamp]
With this error fixed, you switch this line:
$json = file_get_contents('php://input');
to:
$json = $_POST['data'];

Ajax PHP error while passing data from ajax to php

My ajax code from javascript
function makeRequest(button) {
alert(button.value);
var no =button.value;
$.ajax({
url: "findques.php",
type: 'POST',
dataType:"json",
data: {id:no},
success: function(response) {
$.each(response, function(idx, res){
alert(res.question);
});
},
error:function(err){
console.log(err);
}
});
}
My php code to retrive data is as follows
<?php
$connect =mysql_connect('localhost', 'root', 'password');
mysql_select_db('test');
if($connect->connect_error)
{
die("connection failed : ".$connect->connect_error);
}
if(isset($_POST['id']))
{
$var = mysql_real_escape_string(htmlentities($_POST['id']));
error_log($var);
}
$data = "SELECT * FROM `questions` WHERE no=$var";
if(mysql_query($data)==TRUE)
{
$result=mysql_query($data);
$row = mysql_fetch_assoc($result);
$details =array( "id"=>$row['no'],"question"=>$row['Ques'],"op1"=>$row['op1'],"op2"=>$row['op2'],"op3"=>$row['op3'],"op4"=>$row['op4']);
echo json_encode($details);
}
else{
echo "error";
}
$connect->close();
?>
Im trying to retrive data from Mysql database from ajax through php but it shows me "error.jquery.min.js:6 GET 500 (Internal Server Error)"
Is that a problem with my ajax part or PHP part?? Im using Ubuntu 14.04 with apache 2 server.Some suggest there is a problem with server permissions??
You're using type: 'GET', and in PHP you're using $_POST['id'].
Change type to type: 'POST',
Your problem is invalid php code.
It appears you are using some strange mix of different examples on the server side:
$connect =mysql_connect('localhost', 'root', 'password');
This line returns a handle (a numeric value), and not an object which is what you try to use later on:
if($connect->connect_error)
This leads to an internal error.
To debug things like this you should start monitoring the error log file of your http server. That is where such errors are logged in detail. Without looking into these log files you are searching in the dark. That does not make sense. Look where there is light (and logged errors)!
I used mysqli instead of mysql_connect() and error is gone since mysql_connect() is deprecated on suggestions of patrick
Try changing this...
if(mysql_query($data)==TRUE)
{
$result=mysql_query($data);
$row = mysql_fetch_assoc($result);
$details =array( "id"=>$row['no'],"question"=>$row['Ques'],"op1"=>$row['op1'],"op2"=>$row['op2'],"op3"=>$row['op3'],"op4"=>$row['op4']);
echo json_encode($details);
}
To this...
$result = mysql_query($data);
if(mysql_num_rows($result)>0)
{
$row = mysql_fetch_assoc($result);
$details =array(
"id"=>$row['no'],
"question"=>$row['Ques'],
"op1"=>$row['op1'],
"op2"=>$row['op2'],
"op3"=>$row['op3'],
"op4"=>$row['op4']);
echo json_encode($details);
}
Not 100% sure that's the problem, but that's how I structure my basic DB functions, and it works fine.
I would also note that if this is going to to be a public page where users can enter data, I recommend using PHP PDO to handle your database interactions.

Validating availability using javascript and php

I want to make a javascript function which checks the database whether the id requested by the user is available or not. My code is:
HTML:
<button type="button" onclick="chkId()">Check Availability</button><span id="chkresult"></span>
Javascript code:
function chkId()
{
$("#chkresult").html("Please wait...");
$.get("check_id.php", function(data) { $("#chkresult").html(data); });
}
The check_id.php file:
<?php
require 'connect.php';
$id_query = mysql_query("SELECT COUNT(*) AS TOTAL FROM `Table4` WHERE `Unique ID` = '$id'");
list ($total) = mysql_fetch_row($id_query);
if ($total == 0)
{
echo "Available!";
}
else if ($total > 0)
{
echo "Not Available!";
}
?>
But when the button is clicked, nothing happens. I just get a 'Please wait...' message, but as expected by the code, after 'Please wait...' it should change either to Available or to Not Available. But I only get the 'Please Wait...' message, and the result Available or Not Available is not printed on the screen. Please help me what changes do I need to make in my code.
I do not see the $id variable in your PHP script that is used by your $id_query.
Try adding that above $id_query
A few things I notice:
Your javascript is not passing the id parameter to your php backend. See the documentation for the proper syntax to pass that id param.
Your PHP is calling the mysql_query method and one of the parameters that it is passing in is the $id - but $id has not been declared. Check your PHP logs and you'll see where it is choking.
Because the PHP code is likely failing due to the unresolved variable, it is returning an error code. When JQuery receives the error code, it goes to call your ajax failure handler, but you have not declared one! Try adding a .fail(function(){}); to your get call as the docs describe - and you'll likely see the php error message show up.
EDIT: Obligatory php sql injection attack warning. Make sure to escape client input!!!
$.ajax({
type: "POST",
url: "check_id.php",
data: {
id:id; //the id requested by the user.You should set this
},
dataType: "json",
success: function(data){
$('#chkresult').html(data);
}
},
failure: function(errMsg) {
alert(errMsg);
}
});
In your php
<?php
require 'connect.php';
$id_query = mysql_query("SELECT COUNT(*) AS TOTAL FROM `Table4` WHERE `Unique ID` = '$id'");
list ($total) = mysql_fetch_row($id_query);
if ($total == 0)
{
header('Content-type: application/json');
echo CJavaScript::jsonEncode('Available');
}
else if ($total > 0)
{
header('Content-type: application/json');
echo CJavaScript::jsonEncode('Not available');
}
?>

Categories

Resources