I have an UI in which the user can add objects (stored as JSON in my database). So, when the user is clicking on a button, it calls the ajax wich calls my php to get the desired JSON code.
The problem is that my ajax returns me "success" but with no JSON code. I don't know where the problem is located.
Here's my JS/AJAX:
var object, objectJson;
var objectName = $(this).attr("attr-lib");
var objectId = $(this).attr("attr-id");
$.ajax({
url: 'scriptObject.php',
type: 'POST',
data: {objectId: objectId},
dataType: 'json',
success: function(response) {
console.log("success");
console.log(response);
}
});
Here's my scriptObject.php:
$objectId = $_POST["objectId"];
$query = "SELECT objectJson FROM object WHERE objectId = ' $objectId '";
$result = mysql_query($query);
if($result)
{
if(mysql_num_rows($result) > 0)
{
$objJSON = mysql_fetch_array($result);
$res = array("status"=>"success", "objectJson" => $objJSON['objectJson']);
}
else
{
$res = array("status"=>"error", "message" => "No records found.");
}
}
else
$res = array("status"=>"error", "message" => "Problem in fetching data.");
echo json_encode($res);
[EDIT]
It answers me:
{"status":"error","message":"Problem in fetching data."}
Try following
<script type="text/javascript">
var object, objectJson;
var objectName = $(this).attr("attr-lib");
var objectId = $(this).attr("attr-id");
$.ajax({
url: 'scriptObject.php',
type: 'POST',
dataType : 'json',
data: { objectId: objectId },
success: function(response) {
var json = $.parseJSON(response);
if(json.status == 'error')
console.log(json.message);
else if(json.status == 'success')
console.log(json.objectJson);
}
});
</script>
and in scriptObject.php
<?php
// your database connection goes here
include 'config.php';
$objectId = $_POST["objectId"];
$query = "SELECT objectJson FROM object WHERE objectId = ' $objectId '";
$result = mysql_query($query);
if($result)
{
if(mysql_num_rows($result) > 0)
{
$objJSON = mysql_fetch_array($result);
$res = array("status"=>"success", "objectJson" => $objJSON['objectJson']);
}
else
{
$res = array("status"=>"error", "message" => "No records found.");
}
}
else
$res = array("status"=>"error", "message" => "Problem in fetching data.".mysql_error());
echo json_encode($res);
?>
scriptObject.php
if(isset($_POST['objectId']))
{
$objectId = $_POST["objectId"];
$query = "SELECT objectJson FROM object WHERE objectId = ' $objectId '";
$result=mysql_query($query);
echo json_encode($result);
die;
}
you are execution the php code inside a function.
how does the compiler or the interpreter know to execute a function inside your php file.
Add dataType to your ajax options
$.ajax({
url: 'scriptObject.php',
type: 'POST',
data: objectId,
dataType : 'json',
success: function(response) {
console.log("success");
console.log(response);
}
});
then your php code
function getObjectJson() {
$objectId = $_POST["objectId"];
$query = "SELECT objectJson FROM object WHERE objectId = ' $objectId '";
$result=mysql_query($query);
echo json_encode($result);
}
Related
I need to get data from the database with ajax and put that data in the 'select' tag. I need to have every name in a different 'option'... View the code:
Index.php:
<label>Select:</label>
<select id="users"></select>
JS:
$(document).ready(function() {
setInterval(function() {
$.get("frombase.php", function(data) {
data = JSON.parse(data);
for (var id in data) {
$("#users").empty();
$("#users").append("<option value='"+ id +"'>"+ data[id] +"</option>")
}
});
}, 1000);
});
And frombase.php:
$sql = "SELECT * FROM `users`";
$result = mysqli_query($db, $sql);
$name = array();
while ($row = mysqli_fetch_assoc($result)) {
$name[] = $row['name'];
}
echo json_encode(array("name" => $name));
mysqli_close($db);
Look at the result (I do not need this)
(My english is not good, because I use Google Translate)
I would do in this way...
JS:
$(document).ready(function() {
$.ajax({
url :'frombase.php',
type: "POST",
dataType: "json",
success : function(data){
$("#users").empty();
$(data['options']).each(function(k,v){
$("#users").append("<option value='"+ v['id'] +"'>"+ v['name'] +"</option>");
});
},
error:function(){
alert('Error of server comunication');
}
});
});
PHP:
$db = 'YOUR CONNECTION';
$query = $db->prepare("SELECT id,name FROM users");
$query->execute();
$query->bind_result($id,$name);
while ($query->fetch()) {
$result[] = array('id'=>$id,'name'=>$name);
}
$root['options'] = $result;
$root = json_encode($root);
$db->close();
echo $root;
I am currently trying to firstly post the name of the user that I am trying to retrieve from the database to my php code using ajax. Then in the success part of the call I am trying to make a function to retrieve data from a database which matches the name of the user the I previously sent to the page, however no data is coming back to the javascript code.
Here is the function with my ajax calls.
function checkPatientAnswers(event) {
window.open("../src/clinicreview.php", "_self");
var patientname = event.data.patientname;
var dataToSend = 'patientname=' + patientname;
var clinicquestions = getQuestionsForClinic();
var answers = [];
$.ajax({
type: "POST",
url: "../src/getselectedpatient.php",
data: dataToSend,
cache: false,
success: function(result) {
$.ajax({
url: "../src/getselectedpatient.php",
data: "",
dataType: "json",
success: function(row) {
answers = row;
console.log(row);
}
})
}
})
console.log(answers);
for (i in clinicquestions) {
$('#patientanswers').append("<h2>" + clinicquestions[i] + " = " + answers[i]);
}
$('#patientanswers').append("Patient Status = " + answers[answers.length - 1]);
}
And here is my PHP code:
<?php
session_start();
$con = mysql_connect("devweb2015.cis.strath.ac.uk","uname","mypass") or ('Failed to connect' . mysql_error());
$currentdb = mysql_select_db('yyb11163', $con) or die('Failed to connect' . mysql_error());
$patientname = $_POST['patientname'];
$_SESSION['patient'] = $POST['patientname'];
$data = array();
$query = mysql_query("SELECT question1, question2, question3, question4, patient_status FROM patient_info where real_name = '$patientname'");
$data = mysql_fetch_row($query);
echo json_encode($data);
mysql_close($con);
?>
jQuery
var dataToSend = {'patientname':patientname};
$.ajax({
type : "POST",
url : "../src/getselectedpatient.php",
data : dataToSend,
dataType : "json",
cache : false,
success: function(result) {
console.log(result);
}
})
PHP
<?php
session_start();
$_SESSION['patient'] = $POST['patientname'];
$con = mysql_connect("devweb2015.cis.strath.ac.uk","uname","mypass") or ('Failed to connect' . mysql_error());
$currentdb = mysql_select_db('yyb11163', $con) or die('Failed to connect' . mysql_error());
$query = mysql_query("SELECT question1, question2, question3, question4, patient_status FROM patient_info where real_name = '".$_POST['patientname']."'");
$data = mysql_fetch_row($query);
mysql_close($con);
echo json_encode($data);
?>
For the record, I do not condone the use of your mysql_* shenanigans. It has been completely REMOVED in PHP 7 and don't try telling me that you will ride PHP 5 till death do you part.
Secondly, you are 8000% open to SQL injection.
I understand that you are most likely just a student at a school in the UK but if your teacher/professor is OK with your code then you are not getting your money's worth.
You probably forgot to set data on the second call:
$.ajax({
url : "../src/getselectedpatient.php",
data : result,
or result.idor whatever.
I'm having issues with an Ajax login function. There was another question similar to mine that I was able to find but it proved no use.
I have no idea what is the issue, this works on another program as well with no issues, hopefully someone can see my mistake
From testing I think the issue is in the "checkLogIn" function because when I run the application the alert within the function shows
Ajax:
$("#checkLogIn").click(function()
{
$.ajax({
type: 'POST',
contentType: 'application/json',
url: rootURL + '/logIn/',
dataType: "json",
data: checkLogIn(),
})
.done(function(data)
{
if(data == false)
{
alert("failure");
}
else
{
alert("Success");
$.mobile.changePage("#page");
}
})
.always(function(){})
.fail(function(){alert("Error");});
});
function checkLogIn()
{
alert();
return JSON.stringify({
"userName": $("#enterUser").val(),
"password": $("#enterPass").val(),
});
}
I'll also include the PHP but the PHP works 100% after testing it.
PHP:
$app->post('/logIn/', 'logIn');
function logIn()
{
//global $hashedPassword;
$request = \Slim\Slim::getInstance()->request();
$q = json_decode($request->getBody());
//$hashedPassword = password_hash($q->password, PASSWORD_BCRYPT);
$sql = "SELECT * FROM users where userName=:userName AND password=:password";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("userName", $q->userName);
$stmt->bindParam("password", $q->password);
$stmt->execute();
//$row=$stmt->fetch(PDO::FETCH_ASSOC);
//$verify = password_verify($q->password, $row['password']);
$db = null;
//if($verify == true)
//{
// echo "Password is correct";
//}
//else
// echo "Password is incorrect";
echo "Success";
} catch (PDOException $e) {
echo $e->getMessage();
}
}
I have commented out any and all hashing until I can get this working properly
There is no problem with the ajax script. From my assumption you always get Error alert. That is because you added dataType: "json", which means you are requesting the response from the rootURL + '/logIn/' as json Object. But in the php you simply echoing Success as a plain text. That makes the ajax to get into fail function. So, You need to send the response as json. For more details about contentType and datatype in ajax refer this link.
So you need to change echo "Success"; to echo json_encode(array('success'=>true)); in the php file. Now you'll get Success alert. Below I added a good way to handle the json_encoded response in the php file.
$app->post ( '/logIn/', 'logIn' );
function logIn() {
global $hashedPassword;
$request = \Slim\Slim::getInstance ()->request ();
$q = json_decode ( $request->getBody () );
$hashedPassword = password_hash($q->password, PASSWORD_BCRYPT);
$sql = "SELECT * FROM users where userName=:userName";
try {
$db = getConnection ();
$stmt = $db->prepare ( $sql );
$stmt->bindParam ( "userName", $q->userName );
$stmt->execute ();
$row=$stmt->fetch(PDO::FETCH_ASSOC);
$verify = false;
if(isset($row['password']) && !empty($row['password']))
$verify = password_verify($hashedPassword, $row['password']);
$db = null;
$response = array();
$success = false;
if($verify == true)
{
$success = true;
$response[] = "Password is correct";
}
else
{
$success = false;
$response[] = "Password is incorect";
}
echo json_encode(array("success"=>$success,"response"=>$response));
} catch ( PDOException $e ) {
echo $e->getMessage ();
}
}
And I modified the ajax code. There I showed you how to get the response from the json_encoded Object.
$("document").ready(function(){
$("#checkLogIn").click(function()
{
var post_data = JSON.stringify({
"userName": $("#enterUser").val(),
"password": $("#enterPass").val(),
});
$.ajax({
type: 'POST',
contentType: 'application/json',
url: rootURL + '/logIn/',
dataType: "json",
data: post_data,
})
.done(function(data)
{
// data will contain the echoed json_encoded Object. To access that you need to use data.success.
// So it will contain true or false. Based on that you'll write your rest of the code.
if(data.success == false)
{
var response = "";
$.each(data.response, function(index, value){
response += value;
});
alert("Success:"+response);
}
else
{
var response = "";
$.each(data.response, function(index, value){
response += value;
});
alert("Failed:"+response);
$.mobile.changePage("#page");
}
})
.always(function(){})
.fail(function(){alert("Error");});
});
});
Hope it helps.
I have tried removing the JSON.stringify and changing the post to get change cache to false and true. I am at a loss as to what needs to happen. It always goes to the else statement in my php and returns the default JSON. I have allowed crossdomain in my php with the wildcard so that is definitely not the problem.
Code:
$(document).ready(function() {
$('.check').click(function(){
var thisID = $(this).attr('id');
alert(thisID);
$.ajax({
type: "POST",
crossDomain: true,
url: "retrieveColumn.php",
data: JSON.stringify({ ID: thisID}),
cache: true,
async:true,
datatype: "json",
success: function(data)
{
console.log(data);
alert(data);
}
});
});
});
PHP which always goes to the else condition:
if(isset($_POST['ID']))
{
$ID = $_POST['ID'];
{
$stmt = $mysqli->query("SELECT * FROM group2.menu WHERE ItemID = $ID ");
if($stmt->num_rows) //if there is an ID of this name
{
$row = $stmt->fetch_assoc();
echo $row;
print json_encode($row);
}
}
}
else
{
$stmt = $mysqli->query("SELECT * FROM group2.menu WHERE ItemID = 2");
$row = $stmt->fetch_assoc();
print json_encode($row);
}
Unless this is part of a larger document, you have unnecessary brackets which might be causing problems.
if(isset($_POST['ID'])){
$ID = $_POST['ID'];
{ /* <!-- HERE! What is this?? */
$stmt = $mysqli->query("SELECT * FROM group2.menu WHERE ItemID = $ID ");
if($stmt->num_rows) //if there is an ID of this name{
$row = $stmt->fetch_assoc();
echo $row;
print json_encode($row);
}
}
}
else
{
$stmt = $mysqli->query("SELECT * FROM group2.menu WHERE ItemID = 2");
$row = $stmt->fetch_assoc();
print json_encode($row);
}
You don't need to stringify the object you submit as data here:
data: JSON.stringify({ ID: thisID}),
Use:
data: { ID: thisID},
I do not understand because when the data were entered into the login are correct and I make this comparison response.success == "success" nothing happens, I check with firebug and the result is this:
Response
[{"ncontrol":"09680040","nombre":"Edgardo","apellidop":"Ramirez","apellidom":"Leon","tUser":"Admin","status":"success"}]
jQuery.ajax script to send data
// jQuery.ajax script to send json data to php script
var action = $("#formLogin").attr('action');
var login_data = {
ncontrol: $("#ncontrolLogin").val(),
password: $("#passwdLogin").val(),
is_ajax: 1
};
$.ajax({
type: "POST",
url: action,
data: login_data,
dataType: "json",
success: function(response)
{
**if(response.status == "success")** {
$("#status_msg").html("(+) Correct Login");
}
else {
$("#status_msg").html("(X) Error Login!");
}
}
});
return false;
And is PHP Script for processing variables from jQuery.ajax
$ncontrolForm = $_REQUEST['ncontrol'];
$passForm = $_REQUEST['password'];
$jsonResult = array();
$query = "SELECT * FROM users WHERE ncontrol = '$ncontrolForm' AND cve_user = SHA('$passForm')";
$result = mysqli_query($con, $query) or die (mysqli_error());
$num_row = mysqli_num_rows($result);
$row = mysqli_fetch_array($result);
if( $num_row >= 1 ) {
$_SESSION['n_control'] = $row['ncontrol'];
$_SESSION['t_user'] = $row['tUser'];
$jsonResult[] = array (
'ncontrol' => $row['ncontrol'],
'nombre' => $row['nombre'],
'apellidop' => $row['apellidop'],
'apellidom' => $row['apellidom'],
'tUser' => $row['tUser'],
'status' => 'success',
);
header('Content-Type: application/json');
echo json_encode($jsonResult);
}
You have an array, so do it this way:
if(response[0].status == "success") {
The object is the first item in the array.
EDIT:
Looking more closely at your PHP, it looks like you might be intending to loop through several rows in your query response and add them to your $jsonResult. Am I seeing it right?