I have create a php file that generates json data. As shown below but it does not seem to return any data.
When i try to get data.status i get an undefined error. it seems to be connecting to the file no problem as previously i have coded an alert which drags back all the data but i cant seem to get a specific value.
Below i have trying to retrieve the status: ok value.
Json Data:
{"status":"ok","Results":{"SiteId":"1","SiteCode":"RWP50","DateCreated":"2019-09-25 09:14:23","DateClosed":null}}
Ajax Code
$('#ddlsite').change(function () {
var SiteCode = $('#ddlsite').val();
alert(SiteCode);
$.ajax({
type: 'GET',
url: 'GetSites.php',
datatype: 'json',
contentType: "application/json; charset=utf-8",
success:function(data){
alert(data.status);
if(status == "ok"){
alert('It Worked');
}else{
alert('It Failed');
}
}
});
});
PHP File
<?php
// if(!empty($_POST['SiteCode'])){
$data = array();
// Create connection
include 'connecting_test.php';
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// sql to delete a record
$sql = "SELECT * FROM Site";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
// while($row = $result->fetch_assoc()) {
$SiteData = $result->fetch_assoc();
$data['status'] = 'ok';
$data['Results'] = $SiteData;
// }
} else {
echo "0 results";
}
echo json_encode($data);
$conn->close();
// }else {
// echo "hello";
// }
?>
you just need to update your ajax
$.ajax({
type: 'GET',
url: 'xhr.php',
datatype: 'json',
contentType: "application/json; charset=utf-8",
success:function(data){
data = JSON.parse(data);
if(data.status == "ok"){
alert('It Worked');
}
else{
alert('It Failed');
}
}
});
Because you need to parse json which are return from php file
I assume your ajax api call is working fine, and returns correctly, as the datatype is json,
So the alert should work perfectly but the if statement
if(status == "ok") can't find the reference of variable status. It should be data.status if it's not declared somewhere else then type error will be thrown...
Related
I am trying to create a real time update using php and javascript. For example, If the user added a new client, the number of rows should be reflect on the element of the HTML using javascript. Can someone teach me how to do that? I have this code below, and trying to retrieved it, but it does not have a value.
PHP:
<?php
include("pConfig.php");
session_start();
$cntPending = 0;
$sql = "SELECT * FROM ci_account_info Where Status = 0";
$result = mysqli_query($db,$sql);
if (!$result) {
printf("Error: %s\n", mysqli_error($db));
exit();
}
$cntPending = mysqli_num_rows($result);
?>
JAVASCRIPT:
function getTimeSheetValue() {
$.ajax({
type: 'POST',
url: '../back_php_Code/pCntPending.php',
dataType: 'json',
data: '',
contentType: 'application/json; charset=utf-8',
success: function (response) {
var cells = eval("(" + response.d + ")");
document.getElementById("lblPending").innerHTML = cell[0].value;
},
});
}
HTML:
<h4 id="lblPending" class="m-b-0">0</h4>
Thank you and Regards
You have to add echo line in PHP when query is success, then php could send message back to ajax, so change your PHP code:
<?php
include("pConfig.php");
session_start();
$cntPending = 0;
$sql = "SELECT * FROM ci_account_info Where Status = 0";
$result = mysqli_query($db,$sql);
if (!$result)
{
printf("Error: %s\n", mysqli_error($db));
exit();
}
else
{
$cntPending = mysqli_num_rows($result);
echo $cntPending;
}
?>
And your javascript need to change a little bit:
function getTimeSheetValue(user, pass) {
$.ajax({
type: 'POST',
url: '../back_php_Code/pCntPending.php',
dataType: 'text',
contentType: 'application/json; charset=utf-8',
success: function (response) {
var cell = response;
document.getElementById("lblPending").innerHTML = cell;
},
});
}
I want to call php file from javascript, and this php file will update id=1
like this way:
javascript:
if(lastTemp >= document.getElementById("TempSet").value){
var jsonData2 =$.ajax({
url: "setpp.php",
dataType: "json",
async: false
}).responseText;
var obj2 = JSON.parse(jsonData2);
console.log(obj2);
}
else {
}
php file:
<?php
$DATABASE_HOST = 'localhost';
$DATABASE_USER = 'use';
$DATABASE_PASS = 'pass';
$DATABASE_NAME = 'database';
// Try and connect using the info above.
$db = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS,
$DATABASE_NAME);
if (!$db){
die("Connection Failed: ". mysqli_connect_error());
}
$db_update = "UPDATE setpoint_control SET status='ON' WHERE id=1";
$result = mysqli_query($db, $db_update);
?>
<?php
$data = array();
if(mysqli_num_rows($result)>0){
while($row = mysqli_fetch_array($result)){
array_push($data, $row['status']);
}
}
echo json_encode($data);
?>
the code is executed and the status in database table is changed but I got error in console : SyntaxError: JSON.parse: unexpected character at line 4 column 2 of the JSON data
How can I solve this issue which I think I need to rewrite json_encode but I don't know how?
$.ajax({
type: 'post',
dataType: 'json',
cache: false,
url: 'setpp.php',
success: function (response) {
$.each(response, function(i, item) {
alert(item);
});
},
error: function () {
alert("error");
},
});
example php answer setpp.php
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
array_push($data, $row['status']);
}
die(json_encode($data));
} else {
$answer = array(
'No Records'
);
die(json_encode($answer));
}
I think the problem is the value returned by setpp.php.
remember to die(), otherwise the php answer will not be correct
How do I convert Ajax response into plain text string?I have global variable and I store the ajax response to it but when I'm going to compare it with javascript string when even they are equal It returns false.
Here is my code:
function checkUsn(){
var usn = document.getElementById("usn").value;
if(usn){
$.ajax({
type: 'post',
url: 'checkdata.php',
data: {
emp_username: usn,
},
success: function(response){
console.log(response);
myGlobalContainer.usn = response; //convert it to compare with string
$('#status').html(response);
}
});
}
}
in console when I type the existing username in database it logs OK. This OK stores in myGlobalContainer.usn, but when I do comparison like code below it return false.
if(myGlobalContainer.usn == "OK"){
return true;
}else{
return false;
}
I will add php file.
<?php
header("Content-Type: text/plain");
include 'db_config.php';
$conn = new mysqli($db_servername, $db_username, $db_password, $db_name);
if(isset($_POST['emp_username'])){
$usn = $_POST['emp_username'];
$checkdata = "SELECT emp_username FROM emp_details where emp_username='$usn'";
$query = mysqli_query($conn, $checkdata);
if(mysqli_num_rows($query) > 0){
echo "OK";
}else{
echo "Your Username not exist";
}
exit();
}
if(isset($_POST['emp_pw']) && isset($_POST['emp_usn'])){
$pw = $_POST['emp_pw'];
$usn = $_POST['emp_usn'];
$get_pw = "SELECT emp_password FROM emp_details where emp_username='$usn'";
$query = mysqli_query($conn, $get_pw);
//$get_num_rows = mysqli_num_rows($query);
//echo $get_num_rows;
$row = mysqli_fetch_assoc($query);
//echo $row["emp_password"];
// check if password is match with username
if($pw == $row["emp_password"]){
echo "MATCH";
}else{
echo "Wrong password";
}
exit();
}
?>
Please help Thanks!
By default, jQuery's ajax function will determine the type of data it is receiving from the Content-Type response header.
You can override that with the dataType parameter.
$.ajax({
dataType: "text",
// etc etc
});
… however, since the response seems to be "OK" and not HTML, it is likely that your PHP should be adjusted so it outputs the correct Content-Type:
<?php
header("Content-Type: text/plain"); # Override the default (text/html)
echo "OK";
So also make sure that the response is really simply "OK" and that you are not outputting (for example) "OK" followed by a new line.
I've change my code to
success: function(response){
console.log(response);
myGlobalContainer.usn = response.trim(); //convert it to compare with string
$('#status').html(response);
and It works but Guys thanks for your help very appreciated!
also thanks to this question
Ajax response doesn't equal what I think it should
i seem you should use a function in ajax success.
var myGlobalContainer.usn = "";
function signAndCompare(str)
{
myGlobalContainer.usn = str
if(myGlobalContainer.usn == "OK")
{
console.log("true");
return true;
}
console.log("false");
return false;
}
function checkUsn(){
var usn = document.getElementById("usn").value;
if(usn){
$.ajax({
type: 'post',
url: 'checkdata.php',
data: {
emp_username: usn,
},
success: function(response){
console.log(response);
signAndCompare(response);//this line: **compare** and sign response
$('#status').html(response);
}
});
}
I have a written code in AJAX which checks whether password exists or not. if yes it sends "OK" as output else "Incorrect " as output . i want to success handler in AJAX call's response to do task based on that. How can handle it? I want if password is correct , to remove Attribute of disabled in a form element else i want i want that form element's attribute remained back as disabled.
AJAX code goe like this :
$("#currentpassword").keyup(function() {
var name = $(this).val();
if (name.length > 5) {
$("#result").html('checking...');
$.ajax({
type: 'POST',
url: 'checkPassword.php',
data: $(this).serialize(),
success: function(data) {
if (data == "1") {
$("#result").html(data);
$("#newpassword").removeAttr("disabled");
$("#confirmpassword").removeAttr("disabled");
} else {
$("#result").html(data);
}
}
});
return false;
} else {
$("#result").html('');
}
});
checkpassword php file looks like below :
<?php
include_once 'includes.php';
// Submitted form data
$currentpassword=$_POST['currentpassword'];
$result = mysqli_query($db,"SELECT * FROM `users` WHERE `password`='$currentpassword' AND `username`='$session_username'");
$row = mysqli_num_rows($result);
if($row!=1) {
echo "<span style='color:red;'>Incorrect Password !!!</span>";;
}
else {
echo "OK";
}
// Output status
?>
The Good way is The PHP file should look like this
<?PHP
header('Content-type:application/json;charset=utf-8');
include_once 'includes.php';
$currentpassword=$_POST['currentpassword'];
$result = mysqli_query($db,"SELECT * FROM `users` WHERE `password`='$currentpassword' AND `username`='$session_username'");
$count = mysqli_num_rows($result);
if($count! = 1) {
header('HTTP/1.1 401 Unauthorized', true, 401);
echo json_encode('In Correct Password');
} else {
header('HTTP/1.1 404 Not Found', true, 404);
echo json_encode('Not Found');
}
And your Jquery will be
$.ajax({
type: 'POST',
url: 'checkPassword.php',
data: $(this).serialize(),
success: function(data) {
// Only 200 comes here
}, error(jqXHR, exception) {
// All errors except 200 comes here.
}
});
Hope this helps
I have read many answers on stack overflow but I can't find an apt answer. I want to send multiple variables from php file to a javascript file. I want to use those variables later separately. So please explain with a simple example of how to get the variables from php file and how to use them separately later.
This is my js.
<script>
function here(card_numb) {
alert("pk!");
$.ajax({
url: 'details.php',
type: "GET",
dataType: 'json',
data: ({
card_number: card_numb
}),
success: function(data) {
console.log('card_number:'+data.card_number+'book_issued:'+data.book_isued);
}
});
}
I'm getting the alert 'pk!'. But $.ajax ain't working.
This is details.php
<?php
if(isset($_GET['card_number'])){
$card_number = $_GET['card_number'];
$query = "Select * from users where card_number = '".$card_number."'";
$query_run = mysqli_query($link,$query);
$row_numb =#mysqli_num_rows($query_run);
if($row_numb == 0){
echo "<div class='bdiv1'>No such number found!</div>";
} else{
$row=mysqli_fetch_assoc($query_run);
$book1 = $row['user_name'];
$arr = array('isued_book' => $book1,'card_number' => $card_number);
echo json_encode($arr);
exit();
}
}
?>
Thank you!
somthing.js - ur jspage
<script>
function here(card_numb) {
$.ajax({
url: 'details.php',
type: 'GET',
dataType: 'json',
data: {
card_number: card_numb
},
success: function(data) {
console.log('card_number:'+data.card_number+'book_issued:'+data.isued_book);
}
});
}
success: function(result){
console.log('variable1:'+result.var1+'variable2:'+result.var2+'variable3:'+result.var3);
} });
details.php
<?php
if(isset($_GET['card_number'])){
$card_number = $_GET['card_number'];
$query = "Select * from users where card_number = ".$card_number;
$query_run = mysqli_query($link,$query);
$row_numb =#mysqli_num_rows($query_run);
if(!$query_run){
echo "<div class='bdiv1'>No such number found!</div>";
} else {
$row=mysqli_fetch_assoc($query_run);
$book1 = $row['user_name'];
$arr = array('isued_book' => $book1,'card_number' => $card_number);
echo json_encode($arr);
exit();
}
if the currect value get in $row you can get the result in console