how to get json response in ajax? - php

url : http://localhost/test-mobile/log.php?username=&password=pass
$.ajax({
url:url,
type:'POST',
data:{message:message},
dataType:'json',
json:'members',
success:successData,
error:function(){
alert("error")
}
});
function successData(data){
var response=data.message;
alert(response);
}
json response is {"members":{"httpCode":"400","message":"Username missing"}}
PHP code is given below:
<?php
require_once("class/clsdatabase.php"); //Connect to SQL
$username = $_GET['username'];
$password = $_GET['password'];
//Check Username
if($username == '') {
$user = 'Username missing';
$success = true;
$status = array("httpCode"=>"400", "message"=>$user);
//return $status;
}
//Check Password
if($password == '') {
$pass = 'Password missing';
$success = true;
}
//Create SELECT query
$qry = "select * from user_register where emp_code='$username' AND emp_password='$password' AND active='1';";
$result = mysql_query($qry);
$te = mysql_num_rows($result);
if($te == 0 && $username != '' && $password != '') {
$both = 'Invalid username or password';
$success = true;
}
//If there are input validations, redirect back to the registration form
if($te != 0 && $username != '' && $password != '') {
$row = mysql_fetch_assoc($result);
$name = $row['emp_code'];
$success = true;
$status = array("httpCode"=>"400", "message"=>$name);
//return $status;
}
//echo $_GET['callback']. '(' . json_encode($status) . ');';
echo '{"members":'.json_encode($status).'}';
?>
alert a json response

I would split the pages up into two. One file called ajax.php and another called index.php.
Your index.php will look something like.
<html>
<head>
<script type="text/javascript">
postData={ajax:"testing",id:'123'};
$.post('ajax.php', postData , function (data) {
alert(data);
});
</script>
</head>
<body>
</body>
</html>
And your ajax.php file will look something like
<?php
// its important that this file only outputs json or javascript
// content and nothing else.
if(isset($_REQUEST['ajax'])){
$ajaxRequest = $_REQUEST['ajax'];
if($ajaxRequest == 'testing'){
// do some php stuff here -- if you look at the above example we sent an id variable
$sql = "SELECT FROM table WHERE id = {$_REQUEST['id']}";
$results = query($sql);
echo json_encode($results);
exit; // exit the script here so that only the ajax stuff is output
}
}

The jQuery .ajax function automatically decodes the JSON object if the dataType:'json' parameter is set (which it is in his query). So the 'data' variable passed to the success() function will already be a javascript object.
To access the 'message' value, you would use "data.members.message" since the 'members' object contains the 'message' value.

Related

Returning a variable from PHP to AJAX

how can I return a variable from a PHP query to AJAXA. I want the user to be redirected to the user panel using javascript after successfully entering the login and password. The query in PHP was successfully written but Ajax does not return any results.
Code Javascript:
$(document).ready(function() {
$("#btn-login").click(function() {
const loginAuth = $("#login-auth").val();
const passAuth = $("#pass-auth").val();
$.ajax({
type: "POST", //Request type
url: "http://localhost/game/login.php",
data: {
loginAuth: loginAuth,
passAuth: passAuth
},
cache: false,
success: function(data) {
console.log(data);
}
});
});
});
Code PHP:
<?php
require ('connect.php');
session_start();
// If form submitted, insert values into the database.
if (isset($_POST['loginAuth'])) {
// removes backslashes
$username = stripslashes($_REQUEST['loginAuth']);
// escapes special characters in a string
$username = mysqli_real_escape_string($con, $username);
$password = stripslashes($_REQUEST['passAuth']);
$password = mysqli_real_escape_string($con, $password);
// Checking is user existing in the database or not
$query = "SELECT * FROM `users` WHERE login='$username'
and password='" . md5($password) . "'";
$result = mysqli_query($con, $query) or die(mysql_error());
$rows = mysqli_num_rows($result);
if ($rows == 1) {
$_SESSION['username'] = $username;
// Redirect user to index.php
$arr = 'udało się';
header("Location: panel.php");
}
else {
$arr = false;
header("Location: panelLogin.php");
}
}
else {
}
echo json_encode($arr);
?>
Thank you very much for every help.
you cannot redirect the user from the php script that is being called from ajax call.
because it will redirect but not on your browser instance but the ajax one.
you need to redirect it from javascript.
so you can do
echo "true";
instead of
header("Location: panel.php");
and echo "false"; // in case login failed
as an example but you can print some json text and use more informative messages
and you can check these values from ajax success function then you can do
window.location.href = "the url you want to redirect to";

how to use user id stored in session with ajax

When the user login I am storing the userid into session and then I want to pass that user id to the ajax to retriever other information form the data base.
userid stored in session is not being passed to allResult.php
My login page code snippet where i make the session:
$msg = '';
if (isset($_POST['login']) && !empty($_POST['username'])
&& !empty($_POST['password']))
{
$username1 = $_POST['username'];
$password1 = $_POST['password'];
$password2 = md5($password1);
$sql= "SELECT * FROM users WHERE userName='$username1' AND password='$password2'";
if($query_run = mysqli_query($conn, $sql))
{
$query_num_rows = mysqli_num_rows($query_run);
$stmt =mysqli_prepare($conn, $sql);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
if($query_num_rows==1)
{
$row = mysqli_fetch_assoc($query_run);
$user_id = $row['id'];
$name=$row['Name'];
//creating session
$_SESSION['loggedin_time'] = time();
$_SESSION['userid'] = $user_id;
$_SESSION['name'] = $name;
}
}
else {
$msg = '*Wrong username or password';
}
}
Now after login the user will be taken to dashboard:
<?php
session_start();
include("functions.php");
if(isset($_SESSION["userid"])) {
if(isLoginSessionExpired()) {
header("Location:loginPage.php");
}
}
if($_SESSION['userid']=="" && $_SESSION['name']==""){
header("location: loginPage.php");
}
require 'dbconnect.php';
$userId = $_SESSION['userid'];
echo "$userId";
?>
in the dashboard i am trying to access the other data of the user with ajax
<script id="source" language="javascript" type="text/javascript">
$(function() {
$( "#tabs" ).tabs({active:0});
$.ajax({
url: 'allResult.php',
method:"POST",
data: ({uid:'$userId'}),
dataType: 'json',
success: function(data)
{
var date= data[0]['date'];
var time= data[0]['time'];
var ip= data[0]['ip'];
var lux= data[0]['lux'];
var press= data[0]['press'];
var acc_x= data[0]['acc_x'];
var acc_y= data[0]['acc_y'];
var acc_z= data[0]['acc_z'];
$("#tabs-1").html("<b>date: </b>"+date+"<b> time: </b>"+time+"<b> ip: </b>"+ip+"<b> lux: </b>"+lux+"<b> press: </b>"+press+"<b> acc_x: </b>"+acc_x+"<b> acc_y: </b>"+acc_y+"<b> acc_z: </b>"+acc_z);
} ,
error : function(request,error)
{
alert (error);
alert("Request: "+JSON.stringify(request));
}
});
});
I need to get the user id in order to run allResult.php
allResult.php
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require 'dbconnect.php';
$user_id = $_POST["uid"]
$sql_query = "SELECT * FROM data where id like '$user_id';";
$result = mysqli_query($conn,$sql_query);
if(mysqli_num_rows($result) >0 )
{
$row = mysqli_fetch_assoc($result);
$output [] = $row ;
echo json_encode($output);
}
else
{
echo "Error finding data..";
}
?>
Make all your user logged in data to be called into a json format.
Assuming you have all data under
somedomain.com/userData.php
<?php
#userData.php
if ($user == "loggedin") {
$data['name'] = $_SESSION[1]; //name
$data['email'] = $_SESSION[2]; //email
$data['extra'] = $_SESSION[3]; //etc.
echo json_encode($data, JSON_PREETY_PRINT);
}
?>
Then get data into realtime using jQuery Ajax.
Looks like you're missing session_start()

How to return simple text from php web service using ajax and jquery [duplicate]

This question already has answers here:
Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error, while Postman does not?
(13 answers)
Closed 7 years ago.
I want to do this simple log in task using php web service. I am just trying to authenticate username and password on the basis of text result I am echoing in my php.
PHP:
<?php
// Include confi.php
include_once('confi.php');
$found = false;
$email = isset($_POST['email']) ? mysql_real_escape_string($_POST['email']) : "";
$password = isset($_POST['password']) ? mysql_real_escape_string($_POST['password']) : "";
if(!empty($email) && !empty($password)){
$login=mysql_num_rows(mysql_query("select *
from `login`
where `email`='$email'
and `password`='$password'"));
$result =array();
if($login!=0)
{
echo "success";
}
else
{
echo "failed";
}
}
#mysql_close($conn);
/* Output header */
header('Content-type: text/plain');
?>
If the username and password match; it displays success.
Jquery
<script>
$(function () {
$("#logon").click(function () {
var email = $("#username").val();
var password = $("#pass").val();
var dataString = "email=" + email + "&password=" + password;
if ($.trim(email).length > 0 & $.trim(password).length > 0) {
$.ajax({
type: "POST",
url: "http://*****/login.php",
data:dataString,
crossDomain: true,
cache: false,
beforeSend: function () { $("#logon").html('Connecting...'); },
success: function (data) {
if (data == "success") {
alert(result+"You are in");
localStorage.login = "true";
localStorage.email = email;
window.location.href = "test.html";
}
else if (data == "failed") {
alert("Login error");
$("#logon").html('Login');
}
}
});
}
});
});
</script>
you are missing the json function you have to encode what ever you want to send to back to request
<?php
/*output the header here*/
header("Content-Type: application/json");
// Include confi.php
include_once('confi.php');
$response['Status'];// declare a variable to store msg
$found = false;
$email = isset($_POST['email']) ?
mysql_real_escape_string($_POST['email']) : "";
$password = isset($_POST['password']) ?
mysql_real_escape_string($_POST['password']) : "";
if(!empty($email) && !empty($password)){
$login=mysql_num_rows(mysql_query("select *
from `login`
where `email`='$email'
and `password`='$password'"));
$result =array();
if($login!=0)
{
$response['Status']=""success";
}
else
{
$response['Status']="failed";
}
}
#mysql_close($conn);
here make the change
$result= json_encode($message);
echo $result;
?>
in you jquery data to ajax function add
dataType:"json",
success: function (data) {
if (data.Status == "success") { //here check the condition
alert(result+"You are in");
localStorage.login = "true";
localStorage.email = email;
window.location.href = "test.html";
}
else if (data.Status== "failed") { //here check the condition
alert("Login error");
$("#logon").html('Login');
}
}

How to indirect call php file by ajax with post type and get json return then parse it to table

I have 2 php file, one is "Db_function.php" and "index.php", "index.php" will make a function call in "Db_function.php".
I want to make a call to "index.php" by ajax, here's my code
Html file
<Html>
<body>
<script type="text/javascript" src="js/index.js"></script>
<input type="button" value="Get" onclick="get()">
</body>
</html>
Js file
function get() {
$.ajax({ url: 'index.php',
data: {tag:'get_backup', email:'mail#mail.com', password:'123'},
type: 'post',
datatype:'json'
success: function(output) {
alert(output);
}
});
}
index.php
/*with connect value*/
if ($tag == 'get_backup'){
// store user
$email = $_POST['email'];
$password = $_POST['password'];
$user = $db->get_backup($email, $password);
Db_funtion.php
public function get_backup($email, $password) {
$result = mysql_query("SELECT * FROM users WHERE email = '$email'") or die(mysql_error());
// check for result
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
$result = mysql_fetch_array($result);
$salt = $result['salt'];
$encrypted_password = $result['encrypted_password'];
$hash = $this->checkhashSSHA($salt, $password);
// check for password equality
if ($encrypted_password == $hash) {
// user authentication details are correct
$response = array();
$result2 = mysql_query("SELECT * FROM contact_store WHERE (email ='$email' AND backup_name='$email')") or die(mysql_error());
if (mysql_num_rows($result2) > 0) {
// looping through all results
// contact_stores node
$response["contact_stores"] = array();
while ($row = mysql_fetch_array($result2)) {
// temp user array
$contact_store = array();
$contact_store["backup_name"] = $row["backup_name"];
$contact_store["email"] = $row["email"];
$contact_store["data"] = $row["data"];
// push single contact_store into final response array
array_push($response["contact_stores"], $contact_store);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no contact_stores found
$response["success"] = 0;
$response["message"] = "No contact_stores found";
// echo no users JSON
echo json_encode($response);
}
}
} else {
// user not found
return false;
}
}
Json return like this
{"contact_stores":[{"backup_name":"nhi#gmail.com","email":"nhi#gmail.com","data":"[]"}],"success":1}
But my problem is when i press get button in html file, nothing happen.
Any help for me ?
It seems like you are not defining the get() function that you provide in the input element.
Try this HTML:
<input id="get" type="button" value="Get">
with this javascript:
$('#get').click(function() {
$.ajax({ url: 'index.php',
data: {tag:'get_backup', email:'mail#mail.com', password:'123'},
type: 'post',
datatype:'json'
success: function(output) {
alert(output);
}
})
});

Checking if username exists in Database jQuery

I want to check if the username is already taken, here is my script, which outputs "undefined". Can anyone help me, please? :)
This is in my jQuery - $("#registerusername").val() is the value of an input.
$.post('checkregister.php',{username: $("#registerusername").val()}, function(data){
window.alert(data.exists);
if(data.exists){
window.alert("Name already found");
}else{
window.alert("Name NOT found");
}
}, 'JSON');
This is in my checkregister.php
header('content-type: text/json');
if(!isset($_POST['username']))
exit;
$db = new PDO('mysql:host=localhost;dbname=testdatabase','root','pw000');
$query = $db->prepare("SELECT * FROM users WHERE username = '" . $_POST['username'] . "'");
$query->execute();
echo json_encode(array('exists' => $query->rowCount() > 0));
First, You might want to strengthen your php against sql injection by 'sanitizing' the input.
Next why return JSON from the php? It would be much simpler to just return either true or false.
$db = new PDO('mysql:host=localhost;dbname=testdatabase','root','pw000');
$query = $db->prepare("SELECT * FROM users WHERE username = '" . $_POST['username'] . "'");
$query->execute();
if( $query->rowCount() > 0 ){
echo 'true';
}
else{
echo 'false';
}
Then in your javascript:
$.post('checkregister.php',{username: $("#registerusername").val()}, function(data){
window.alert(data);
if(data == 'true'){
window.alert("Name already found");
}else{
window.alert("Name NOT found");
}
});
edit---
You could also just return a boolean variable from php rather than a string, but either will work
Simple Example..
Jquery
var username = $.trim($('#username').val());
if(username != '') {
$.ajax({
url : 'localhost/phpScript.php',
data : {username : username},
dataType : 'JSON',
type : 'POST',
cache : false,
success : function(result) {
if(result == '1') { alert('Username Found.'); }
else if(result == '0') { alert('Username Not Found!'); }
},
error : function(err) {
console.log(err);
}
});
}
PHP/MySQL (Make sure that you escape value for user input, Before giving it to MySql)
if(isset($_POST['username'])) {
$username = $_POST['username'];
$sql = "SELECT username FROM users WHERE username = '".$username."' LIMIT 1";
$query = mysql_query($sql);
if(mysql_num_rows($query) == '1') {
echo '1';
} else {
echo '0';
}
}

Categories