I am trying to post 4 variables to a database on an external server using a mobile application created using Cordova 4.0.0.
I have already had a look a countless posts similar to this trying, POST, GET, contentType etc. and none of these seem to work. I have worked with JSONP before and it worked fine (I used that code as a template), but this doesn't seem to work.
Here is the console log:
2015-01-30 09:19:09.817 Alert[1253:353531] {"readyState":4,"status":200,"statusText":"load"}
2015-01-30 09:19:09.817 Alert[1253:353531] parsererror
2015-01-30 09:19:09.817 Alert[1253:353531] {"line":2,"column":2097,"sourceURL":"file:///private/var/mobile/Containers/Bundle/Application/D1746CD9-C9B3-4A31-9965-E4A6AAED3347/Alert.app/www/js/jquery-2.1.3.min.js"}
Here is my AJAX Post request.
function pushToDataLog(beaconid, uuid, timestamp, status)
{
jQuery.ajax({
type: "POST", // HTTP method POST or GET
url: "http://url.co.uk/ips/pushdata.php", //Where to make Ajax calls
dataType:"jsonp", // Data type, HTML, json etc.
jsonp: "callback",
data : {beaconid: beaconid, uuid: uuid, timestamp: timestamp, status:status},
crossDomain: true,
contentType: 'application/json',
success:function(response){
//console.log(JSON.stringify(response));
},
error:function (xhr, ajaxOptions, thrownError){
console.log(xhr);
console.log(ajaxOptions);
console.log(thrownError);
}
});
}
I dont understand what is causing the parse error..
EDIT
Here is my PHP file stored on the server:
<?php
if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
$beaconid = NULL;
$entertimestamp= NULL;
$exittimestamp = NULL;
//GET THE VARIABLES FROM JAVASCRIPT
if(isset($_REQUEST['beaconid'])){
$beaconid = $_REQUEST['beaconid'];
}
if(isset($_REQUEST['uuid'])){
$uuid = $_REQUEST['uuid'];
}
if(isset($_REQUEST['timestamp'])){
$timestamp = $_REQUEST['timestamp'];
}
if(isset($_REQUEST['status'])){
$status = $_REQUEST['status'];
}
define('DB_SERVER', 'a');
define('DB_USER', 'a');
define('DB_PASSWORD', 'a');
define('DB_DATABASE', 'a');
$mysqli = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
if (!$mysqli) {
trigger_error('mysqli Connection failed! ' . htmlspecialchars(mysqli_connect_error()), E_USER_ERROR);
}else{
print '<p>Database Connected!</p>';
}
//if( isset($name) && $name != '' ){
$stmt = $mysqli->prepare("INSERT INTO a(BeaconID,UUID,Timestamp,Status) VALUES (?, ?, ?, ?)");
if ($stmt === false) {
trigger_error('Statement failed! ' . htmlspecialchars(mysqli_error($mysqli)), E_USER_ERROR);
}
$bind = mysqli_stmt_bind_param($stmt, "isii", $beaconid, $uuid, $timestamp, $status);
if ($bind === false) {
trigger_error('Bind param failed!', E_USER_ERROR);
}
$exec = mysqli_stmt_execute($stmt);
if ($exec === false) {
trigger_error('Statement execute failed! ' . htmlspecialchars(mysqli_stmt_error($stmt)), E_USER_ERROR);
}
printf ("New Record has id %d.\n", mysqli_insert_id($mysqli));
//CLOSE THE SQL QUERY/STATEMENT
mysqli_stmt_close($stmt);
$json = json_encode("Success");
echo $_GET['callback'].'('.$json.')';
//}
mysqli_close($mysqli);
}
?>
With the help of #briosheje I managed to solve this issue. In case anyone has a similar problem in the future here is how I solved it:
The problem AJAX request was fine, the issue was in the PHP file on the server. To solve this I sent a json encoded array back containing success / failure messages.
Here is the full php file:
<?php
$beaconid = NULL;
$uuid = NULL;
$timestamp = NULL;
$status = NULL;
//GET THE VARIABLES FROM JAVASCRIPT
if(isset($_REQUEST['beaconid'])){
$beaconid = $_REQUEST['beaconid'];
}
if(isset($_REQUEST['uuid'])){
$uuid = $_REQUEST['uuid'];
}
if(isset($_REQUEST['timestamp'])){
$timestamp = $_REQUEST['timestamp'];
}
if(isset($_REQUEST['status'])){
$status = $_REQUEST['status'];
}
/*$beaconid = 1;
$uuid = "1213sdfdsdf";
$timestamp = 3424;
$status = 1;*/
define('DB_SERVER', 'xxx');
define('DB_USER', 'xxx');
define('DB_PASSWORD', 'x');
define('DB_DATABASE', 'x');
if($beaconid != '' && $uuid != '' && $timestamp != '' && $status != ''){
$mysqli = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
if (!$mysqli) {
trigger_error('mysqli Connection failed! ' . htmlspecialchars(mysqli_connect_error()), E_USER_ERROR);
$arr = array ('state'=>'connection failed');
}else{
$stmt = $mysqli->prepare("INSERT INTO datalog(BeaconID,UUID,Timestamp,Status) VALUES (?, ?, ?, ?)");
$arr = array ('state'=>'data pushed to the datalog');
if ($stmt === false) {
trigger_error('Statement failed! ' . htmlspecialchars(mysqli_error($mysqli)), E_USER_ERROR);
$arr = array ('state'=>'statement failed');
}
$bind = mysqli_stmt_bind_param($stmt, "isii", $beaconid, $uuid, $timestamp, $status);
if ($bind === false) {
trigger_error('Bind param failed!', E_USER_ERROR);
$arr = array ('state'=>'build param failed');
}
$exec = mysqli_stmt_execute($stmt);
if ($exec === false) {
trigger_error('Statement execute failed! ' . htmlspecialchars(mysqli_stmt_error($stmt)), E_USER_ERROR);
$arr = array ('state'=>'statemente execute failed');
}
}
$arr = json_encode($arr); //response send to the app
echo $_GET['callback'].'('.$arr.')'; //need this to prevent parsererror
//CLOSE THE SQL QUERY/STATEMENT
mysqli_stmt_close($stmt);
mysqli_close($mysqli);
}
?>
Related
Here is my php script for the registration page, the data is still being entered into the correct table but this problem is persistent.
Edit: I've seen comments asking for the javascript code, I've included it below the php code now.
`<?php
session_start();
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: *");
main();
function main(){
require 'connectToDB.php';
// echo "\nreached the php file";
$response = array("code" => 0, "message" => "");
$request = file_get_contents('php://input');
$jsonRequest = json_decode($request);
var_dump($jsonRequest);
if (checkForExistingUser($conn, $jsonRequest) != 0){
$response["code"] = 2;
$response["message"] = "User already exists";
}
// else if($response["code"] == 1){
// // $userID = $conn->lastInsert();
// // header("Location: UniqueUserID.php");
// exit;
// }
else{
$response = addUser($conn, $jsonRequest);
// header("Location: UniqueUserID.php");
exit;
}
// printf(json_encode($response));
// var_dump($response);
$conn = null;
return json_encode($response);
}
function checkForExistingUser ($conn, $jsonRequest){
$stmt = $conn->prepare("
SELECT COUNT(Email) as noOfUsers
FROM user_main
WHERE Email = :confirmemailadd");
// $stmt -> bindParam(':confirmemailadd', $jsonRequest->confirmemailadd);
if (isset($jsonRequest->confirmemailadd)) {
$stmt->bindValue(':confirmemailadd', $jsonRequest->confirmemailadd);
} else {
$stmt->bindValue(':confirmemailadd', '');
}
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
$results = $stmt->fetchAll();
$noOfResults = $results[0]["noOfUsers"];
// echo($noOfResults);
return $noOfResults;
}
function addUser($conn, $jsonRequest){
$response = array("code"=>0, "message"=>"");
// echo ("Reached addUser \n");
$firstname = sanitise($jsonRequest->firstname);
$surname = sanitise($jsonRequest->surname);
$username = sanitise($jsonRequest->username);
$confirmemailadd = sanitise($jsonRequest->confirmemailadd);
$phonenum = sanitise($jsonRequest->phonenum);
$retypepassword = sanitise($jsonRequest->retypepassword);
function encryptPassword($retypepassword) {
$key = openssl_random_pseudo_bytes(32);
$iv = openssl_random_pseudo_bytes(16);
$encrypted = openssl_encrypt($retypepassword, 'AES-256-CBC', $key, 0, $iv);
$hash = hash_hmac('sha256', $encrypted, $key);
return $hash . ':' . base64_encode($iv) . ':' . base64_encode($encrypted);
}
$stmt = $conn->prepare("
INSERT INTO user_main (Name, Surname, Username, Email, PhoneNum, PWD)
VALUES (:firstname, :surname, :username, :confirmemailadd, :phonenum, :retypepassword) ");
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':surname', $surname);
$stmt->bindParam(':username', $username);
$stmt->bindParam(':confirmemailadd', $confirmemailadd);
$stmt->bindParam(':phonenum', $phonenum);
$stmt->bindParam(':retypepassword', $retypepassword);
try{
$stmt->execute();
$userID = $conn->lastInsertId();
$response["code"] = 1;
$response["message"] = "successfully added";
$response["user_id"] = $userID;
}
catch (PDOException $e){
$response["code"] = 0;
$response["message"] = $e->getMessage();
}
// echo json_encode($response);
return $response;
}
function sanitise($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
`
I'm still relatively new to the back-end development side of things but I cannot figure this one out, I've tried to google it and research other solutions on stack overflow but couldn't find anything useful
document.addEventListener('DOMContentLoaded', function () {
const form = document.querySelector('form');
form.addEventListener('submit', handleFormSubmit);
}, false)
function handleFormSubmit(event) {
event.preventDefault();
checkEmails();
checkPasses();
processForm();
// redirectToPage()
}
function checkEmails(){
var emailValue = document.getElementById("emailadd").value;
var retypeEmailValue = document.getElementById("confirmemailadd").value;
if (emailValue !== retypeEmailValue){
window.alert("Emails do not match.");
}
}
function checkPasses(){
var passValue = document.getElementById("password").value;
var retypeValue = document.getElementById("retypepassword").value;
if (passValue !== retypeValue){
window.alert("Passwords do not match.");
}
}
function processForm(){
var userDetails = gatherData()
console.log(userDetails);
postRequest(userDetails)
}
function gatherData(){
//gather the data from the form fields into JSON
var userDetails = {
firstname : document.getElementById("firstname").value,
surname : document.getElementById("surname").value,
username : document.getElementById("username").value,
confirmemailadd: document.getElementById("confirmemailadd").value,
phonenum: document.getElementById("phonenum").value,
retypepassword: document.getElementById("retypepassword").value,
}
return userDetails;
}
async function postRequest(userDetails){
// make an AJAX POST request to server
try{
const response = await fetch("../php/register.php",{
method: 'POST',
headers: {
'Origin' : 'http://localhost/',
'Content-Type': 'application/json', // sent request
'Accept': 'application/json' // expected data sent back
},
body: JSON.stringify(userDetails),
});
const data = await response.json();
console.log(data);
handleResponseCode(data);
}catch (error){
console.log('Error:',error);
}
}
function handleResponseCode(data){
console.log("response code: ", data.code);
console.log("response message: ", data.message);
if (data.code == 1){
alert ("Your account has been successfully created")
}
else if (data.code == 2 ){
alert (data.message );
}
}
You can try to catch the root cause of this error:
try {
$jsonResponse = json_encode($response);
} catch (Exception $e) {
// Handle JSON encoding error
die("JSON encoding error: " . $e->getMessage());
}
This will catch any exceptions thrown during the encoding process and allow you to handle them appropriately.
Edit:
function main(){
// ...
try {
$jsonResponse = json_encode($response);
} catch (Exception $e) {
// Handle JSON encoding error
die("JSON encoding error: " . $e->getMessage());
}
$conn = null;
return $jsonResponse;
}
you can put this catch error inside a function you wanna trace
Just remove the var_dump(...). Because that var_dump is already sending content back.
I am working on a scanner reader, so I used ajax when the code is read by the scanner, it should insert data to the database. The problem is the data is not inserting.
Inside the script / Ajax - query is the variable I used to get the data (name)
var query = $('#scanned-QR').val();
fetch_customer_data(query);
$(document).on('keyup', '#scanned-QR', function(){
var query = $(this).val();
fetch_customer_data(query);
});
function fetch_customer_data(query = '')
{
$.ajax({
url:"validScan.php",
method: 'GET',
data:{query:query},
dataType: 'json',
success:function(data) {
console.log(data);
if (data.status == '1') {
decoder.stop();
alert('Sucess!');
}
else if(data.status=='0'){
decoder.stop();
alert('Fail!');
}
},
error:function(err){
console.log(err);
}
});
}
My Input/Textarea
<textarea id="scanned-QR" name="scanQR" readonly></textarea>
MySQL
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$link = mysqli_connect("localhost","root","");
mysqli_select_db($link, "schedule");
$query = $_GET['query'];
$res = mysqli_query($link,"INSERT INTO attendance (name) VALUES ('$query')");
if (mysqli_num_rows($res) > 0) {
$respose = array('status'=>'1');//1 for success
echo json_encode($respose );
} else {
$respose = array('status'=>'0');//0 for fail
echo json_encode($respose );
}
mysqli_close($link);
?>
For insert query, result will return as boolean, So mysqli_num_rows($res) won't accept boolean argument. mysqli_num_rows() expects parameter 1 to be mysqli_result
So you can simply check by below, whether it is inserted or not:
if ($res) {
$respose = array('status'=>'1');//1 for success
echo json_encode($respose);
exit;
} else {
$respose = array('status'=>'0');//0 for fail
echo json_encode($respose);
exit;
}
mysqli_close($link);
You should use exit try following code :
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$link = mysqli_connect("localhost","root","");
mysqli_select_db($link, "schedule");
$query = $_GET['query'];
$res = mysqli_query($link,"INSERT INTO attendance (name) VALUES ('$query')");
if (mysqli_num_rows($res) > 0) {
$respose = array('status'=>'1');//1 for success
echo json_encode($respose );
exit;
} else {
$respose = array('status'=>'0');//0 for fail
echo json_encode($respose );
exit;
}
mysqli_close($link);
exit;
mysqli_num_rows() is for getting the number of rows returned from a SELECT query. You need to check the number of affected rows instead.
You should also be using a prepared statement, and I also recommend that you set up MySQLi to throw errors. I also prefer the object-oriented approach.
<?php
// Configure MySQLi to throw exceptions on failure
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// Init connection
$link = new mysqli("localhost", "root", "", "schedule");
$response = [];
// Prepare the statement and execute it
$stmt = $link->prepare("INSERT INTO attendance (name) VALUES (?)");
$stmt->bind_param("s", $_GET['query']);
$stmt->execute();
// Check the number of inserted rows
if ($stmt->affected_rows) {
$response['status'] = 1;
} else {
$response['status'] = 0;
}
// Close the statement and connection
$stmt->close();
$link->close();
echo json_encode($response);
I am performing an AJAX PUT request which is coming back as successful but not updating on the database.
Have checked to make sure the variables going into the array are correct before being converted to JSON.
var recycle = {
id:document.getElementById('id').value,
year:document.getElementById('year').value,
materialThousandTonnes:document.getElementById('material').value,
packagingWasteArising:document.getElementById('packaging').value,
totalRecoveredRecycled:document.getElementById('total').value,
achievedRecoveryRecyclingRate:document.getElementById('achieved').value,
euTargetRecoveryRecyclingRate:document.getElementById('target').value
};
$.ajax({
url: '/recycle',
method: 'PUT',
data: JSON.stringify(recycle),
contentType: "application/json;charset=utf-8",
success: function (data) {
alert("hi");
},
error: function (jqXHR, textStatus, errorThrown) {
alert(jqXHR + '\n' + textStatus + '\n' + errorThrown);
}
});
The alert "hi" appears everytime however it doesn't actually PUT the data into my database please help!
EDIT:
Here is server-side code for PUT request
public function performPut($url, $parameters, $requestBody, $accept)
{
global $dbserver, $dbusername, $dbpassword, $dbdatabase;
$newRecycle = $this->extractRecycleFromJSON($requestBody);
$connection = new mysqli($dbserver, $dbusername, $dbpassword, $dbdatabase);
if (!$connection->connect_error)
{
$sql = "update recycledb set year = ?, materialThousandTonnes = ?, packagingWasteArising = ?, totalRecoveredRecycled = ?, achievedRecoveryRecyclingRate = ?, euTargetRecoveryRecyclingRate = ? where id = ?";
// We pull the fields of the book into local variables since
// the parameters to bind_param are passed by reference.
$statement = $connection->prepare($sql);
$id = $newRecycle->getId();
$year = $newRecycle->getYear();
$materialThousandTonnes = $newRecycle->getMaterialThousandTonnes();
$packagingWasteArising = $newRecycle->getPackagingWasteArising();
$totalRecoveredRecycled = $newRecycle->getTotalRecoveredRecycled();
$achievedRecoveryRecyclingRate = $newRecycle->getAchievedRecoveryRecyclingRate();
$euTargetRecoveryRecyclingRate = $newRecycle->getEuTargetRecoveryRecyclingRate();
$statement->bind_param('iisiiss', $id, $year, $materialThousandTonnes, $packagingWasteArising, $totalRecoveredRecycled, $achievedRecoveryRecyclingRate, $euTargetRecoveryRecyclingRate);
$result = $statement->execute();
if ($result == FALSE)
{
$errorMessage = $statement->error;
}
$statement->close();
$connection->close();
if ($result == TRUE)
{
// We need to return the status as 204 (no content) rather than 200 (OK) since
// we are not returning any data
$this->noContentResponse();
}
else
{
$this->errorResponse($errorMessage);
}
}
}
So I found the solution to my issue after much a struggle
On this line:
$statement->bind_param('iisiiss', $id, $year, $materialThousandTonnes, $packagingWasteArising, $totalRecoveredRecycled, $achievedRecoveryRecyclingRate, $euTargetRecoveryRecyclingRate);
The id variable needed to be moved to the end of the statement...
Like this:
$statement->bind_param('iisiiss', $year, $materialThousandTonnes, $packagingWasteArising, $totalRecoveredRecycled, $achievedRecoveryRecyclingRate, $euTargetRecoveryRecyclingRate, $id);
$statement->bind_param('iisiiss', $year, $materialThousandTonnes, $packagingWasteArising, $totalRecoveredRecycled, $achievedRecoveryRecyclingRate, $euTargetRecoveryRecyclingRate, $id);
I have a problem, clicking in a < tr > of a table I call a javascript function which in turn calls a function in php to get data in a database. The click on the table row works, sql works, and from the console.log command I know there is an answer in reponseText. but it does not work and I get the error back, I'll post the code. I hope you can help me.
file config.php
//database credentials
define('DBHOST','localhost');
define('DBUSER','root');
define('DBPASS','');
define('DBNAME','toor');
try{
//create PDO connection
$db = new PDO("mysql:host=".DBHOST.";charset=utf8mb4;dbname=".DBNAME, DBUSER, DBPASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
} catch(PDOException $e) {
//show error
echo '<p class="bg-danger">'.$e->getMessage().'</p>';
exit;
}
//include the user card, pass in the database connection
include($_SERVER['DOCUMENT_ROOT'].'cards.php');
$card = new card($db);
file cards.php
<?php
class card
{
private $_db;
function __construct($db){
$this->_db = $db;
}
public function view_card_id($id)
{
$rows = array();
$statement = $this->_db->prepare('SELECT * FROM card_details WHERE card_id = :card_id');
$statement->execute(array(':card_id' => $id));
$numrows = $statement->fetch(PDO::FETCH_ASSOC);
if($numrows < 1) {
$this->error = "Error";
return false;
} else {
$statement->bindColumn("card_id", $cid);
$statement->bindColumn("a", $a);
$statement->bindColumn("b", $b);
$rows[] = array('card_id' => $numrows['card_id'], 'a' => $numrows['a'], 'b' => $numrows['b']);
while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
$row = array('card_id' => $cid, 'a' => $a, 'b' => $b);
$rows[] = $row;
}
return $rows;
}
}
file index.php
<?php
//include config
require_once($_SERVER['DOCUMENT_ROOT'].'config.php');
?>
html code ....
<script src="/js/Cards.js" type="text/javascript"></script>
file Cards.js
$('#table-cards tr').click(function() {
var id = $(this).find("a").text();
$.ajax({
type: 'POST',
url: '/classes/cardsFunc.php',
dataType:'text',
data: {functionname: "view_card", id: id },
success: function(response){
//Use response
alert("Server echo: "+response);
console.log(response);
},
error: function(msg){
console.log(msg);
alert("Error: "+msg);
}
});
});
In the Cards.js file, once the $ .ajax function is called, it does not return to success but to error, but in the console.log I see the array of the executed query under the responseText entry.
that is, in the error response, I see the result of the query, which in theory should be in the response of success.
I also tried to use
$.post('/classes/cardsFunc.php', { functionname: 'view_card', id: id }, function(data){
});
but nothing
file cardsFunc.php
<?php
//include config
require_once($_SERVER['DOCUMENT_ROOT'].'config.php');
if(isset($_POST['functionname']) && $_POST['functionname'] == "view_card"){
$card_view = $card->view_card_id($_POST['id']);
print json_encode($card_view);
}
?>
thank you for the time you have dedicated to me
I noticed that if I recreate the connection to the db in the file cardsFunc.php, everything works, but I do not understand why, since everything is in the config.php file.
Like this:
file cardsFunc.php
<?php
//database credentials
define('DBHOST','localhost');
define('DBUSER','root');
define('DBPASS','');
define('DBNAME','toor');
try{
//create PDO connection
$db = new PDO("mysql:host=".DBHOST.";charset=utf8mb4;dbname=".DBNAME, DBUSER, DBPASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
} catch(PDOException $e) {
//show error
echo '<p class="bg-danger">'.$e->getMessage().'</p>';
exit;
}
//include the user card, pass in the database connection
include($_SERVER['DOCUMENT_ROOT'].'cards.php');
$card = new card($db);
if(isset($_POST['functionname']) && $_POST['functionname'] == "view_card"){
$card_view = $card->view_card_id($_POST['id']);
print json_encode($card_view);
}
?>
I wrote the ajax in the JavaScript function. That code is
function getValidate(checkID)
{
alert(checkID);
$.ajax({
type: 'post',
url: 'checkval.php',
datatype: 'json',
data: {checkID : checkID},
success: function (response) {
if (response === "OK"){
alert("Validation Successed.");
}else if(response === "NG"){
alert("Check Already Exists.");
}
},
error : function(err, req) {
alert("Error Occurred");
}
});
}
this code is outputs only "Error Occurred".
the connected php script is
<?php
echo("welcome");
$check = $_POST['checkID'];
$host = 'localhost';
$database = 'database';
$username = 'root';
$password = 'root';
$dbc = mysqli_connect($host,$username,$password,$database);
$checkno = $check;
$sql = "select claimno from check_details where checkno = $checkno";
$result = mysqli_query($dbc,$sql);
$rows = mysqli_num_rows($result);
if($rows != 0)
{
echo "NG";
}
else
{
echo "OK";
}
?>
at a time of calling the JavaScript function php file not executed......
please give me the idea to success it...........
Try this :
if($rows != 0)
{
$return = "NG";
}
else
{
$return = "OK";
}
echo json_encode($return);
Also you set datatype to json so response data must be json type
$.ajax({ dataType:"json"});
In php, store result in one variable and return json_encode
<?php
echo("welcome");
$check = $_POST['checkID'];
$host = 'localhost';
$database = 'database';
$username = 'root';
$password = 'root';
$dbc = mysqli_connect($host,$username,$password,$database);
$checkno = $check;
$sql = "select claimno from check_details where checkno = '$checkno'"; //use single quote
$result = mysqli_query($dbc,$sql);
$rows = mysqli_num_rows($result);
if($rows != 0)
{
$res = "NG";
}
else
{
$res = "OK";
}
echo json_encode($res);
?>
You are getting error occurred, because of below code. Try logging something meaningful to triag this.
error : function(err, req) {
alert("Error Occurred");
}
Please try below code to get a clue of the error
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
Reference: Take a look at this query
It seems that the php script is not working well.
Debug it with try and catch and see what output is comming.