I want to write select query in php to get data from database using variable from front-end. In other words I need to do something like this:
SELECT email FROM users WHERE token = '$token'
What I currently have, I have code which posts my variables to back end:
app.controller('customersCtrl', function($scope, $http,$templateCache) {
$scope.subscribe = function (gameId){
$scope.codeStatus = "";
$http({
url: "php/test.php",
method: "POST",
data: {
userId: JSON.parse(localStorage.getItem('loggedUserInfo')),
gameId: gameId,
token:JSON.parse(localStorage.getItem('token'))
},
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
cache: $templateCache
}).success(function(response) {
$scope.codeStatus = response.data;
console.log(response);
});
};
});
And here is my php code:
<?php
$lnk = mysql_connect('localhost', 'root', '')
or die ('Not connected : ' . mysql_error());
mysql_select_db('pitch', $lnk) or die ('Can\'t use db : ' . mysql_error());
$data = json_decode(file_get_contents("php://input"));
$token=$data->token;
$dump1 = mysql_query("SELECT email FROM users where token = '$token' ");
if(!$dump1) exit("Error - ".mysql_error());
$getList = array();
$outp = "";
while ($row = mysql_fetch_assoc($dump1)) {
$relations = array();
$getList[] = $row;
}
$output = json_encode(array('users' => $getList));
echo $output;
?>
The weirdest thing for me is that when I try to go to url localhost/php/test.php I get an Notice: Trying to get property of non-object in /Applications/XAMPP/xamppfiles/htdocs/php/test.php on line 8, which means I guess that $token is empty, but when I console.log(response) in angular it shows me my token in console which I think means that data from front-end was passed to back-end. Or my understanding is wrong?
Will be really thankful for help!
first thing is try to var_dump($_POST), or try to var_dump($data) on your test.php
Related
Kindly help me with the ajax / jQuery to fetch all the objects of a array.
I am using the following code and it doesn't work
$(window).on("load", GetAllProperties);
function GetAllProperties() {
$.ajax({
url: 'userdetailfetch.php', //the script to call to get data
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
$('#ph').html(data[0]);
$('#email').html(data[1]);
$('#name').html(data[2]);
$('#fname').html(data[3]);
$('#date').html(data[4]);
$('#course').html(data[5]);
$('#branch').html(data[6]);
$('#sem').html(data[7]);
$('#roll').html(data[8]);
}
});
}
fetchuserdetail.php
<?php
$cnx = mysqli_connect("localhost", "root", "", "loginerp");
$result = mysqli_query($cnx, "SELECT * FROM user_info WHERE id='" . $_SESSION['sessuser'] . "'");
$data = array();
while($row = mysqli_fetch_array($result)) {
$data[] =$row;
}
echo json_encode($data);
?>
I want to display all the details when the page loads .
Thanks for your help.
Start session in fetchuserdetail.php file
session_start();
Correct the page name
url: 'fetchuserdetail.php',
I am having a problem trying to get around a "parsererror" that is returned from my ajax request, despite a response in devtools which is an array of strings. I have a click event that makes an ajax request to pull in information from a database. The result in dev tools is:
1["1","admin","admin#admin.com","test","2017-01-11 00:00:00"]
I was expecting it to be a json object { }.
The code I wrote for the click event is:
$('#viewProfile').on('click', function() {
$.ajax({
type: 'GET',
url: 'api.php',
data: "",
cache: false,
dataType: 'json',
success: function(data) {
var id = data[0];
var name = data[1];
$('#userDetails').html("<p>ID: " + id + " Name: " + name + "</p>");
},
error: function(request, error) {
$('#userDetails').html("<p>There was a problem: " + error + "</p>");
}
});
});
The php I wrote for api.php
session_start();
echo $_SESSION['user_session'];
//DECLARE VARS FOR DB
$db_host = "localhost";
$db_name = "dbregistration";
$db_user = "root";
$db_pass = "";
$db_tablename = "tbl_users";
//CONNECT TO DB
include 'dbconfig.php';
$db_con = mysqli_connect($db_host,$db_user,$db_pass,$db_name);
$dbs = mysqli_select_db($db_con, $db_name);
//QUERY DB FOR DATA
$result = mysqli_query($db_con, "SELECT * FROM $db_tablename where user_id = '".$_SESSION['user_session']."' ");
$array = mysqli_fetch_row($result);
//RETURN RESULT
echo json_encode($array);
I have tried in api.php to use json_encode($array, JSON_FORCE_OBJECT) along with changing the datatype to HTML, which obviously did not work. In short, my goal was to be able to fire the click event, send an ajax request to retrieve information from the database, based on the user id then return that to the #userDetails id on the page. I am stuck trying to get around the array of strings that seems to be the roadblock for me.
Remove this line:
echo $_SESSION['user_session'];
and change this:
$array = mysqli_fetch_row($result);
to this:
$array = mysqli_fetch_assoc($result);
EDIT: you should also be checking for success/failure of your various db-related statements:
$db_con = mysqli_connect($db_host,$db_user,$db_pass,$db_name) or die("there was a problem connecting to the db");
$dbs = mysqli_select_db($db_con, $db_name) or die("Could not select db");
and also
$result = mysqli_query($db_con, "SELECT * FROM $db_tablename where user_id = '".$_SESSION['user_session']."' ");
if (!$result) {
die("query failed");
}
This needs to be removed echo $_SESSION['user_session'] it is getting returned to ajax call and because it is on json the return is incorrect.
I want to get searched data from mysql database using JSON and show in my php page. I was write this code but it not retrieve any data.please help me
Client page
$(function () {
var roll = document.getElementById("roll").value;
$.ajax({
type: "POST",
url: 'api.php',
data: "roll=" + roll,
dataType: 'json',
success: function (data) {
var id = data[0];
var vname = data[1];`$` ('#output').html("id: " + id + " name: " + vname);
}
});
});
api.php
$host = "localhost";
$user = "root";
$pass = "";
$databaseName = "ajax";
$tableName = "stud";
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
if(isset($_POST['roll'])){
$data = $_POST['roll'];
$result = mysql_query("SELECT * FROM $tableName WHERE roll = '".$data."'");
$array = mysql_fetch_row($result);
}
echo json_encode($array);
log this value before sending,
var roll = document.getElementById("roll").value;
console.log(roll);
Use object to send the params in ajax call like this data: {'roll':roll} for best practice
use firebug to check if the value 'roll' passed properly
In your php dump the post variable print_r($_POST) and check the firebug response console whether you got what you sent.
If you got it in $_POST then probably you have some issue with sql connection/query
i am calling a php page res.php using jquery and ajax. The code is:-
$('#submit_button').click(function () {
buildingVal = $("#building");
levelVal = $("#level");
data = 'building=' + buildingVal.val() + 'level=' + levelVal.val();
$.ajax( {
url: "res.php",
type: "POST",
data: data,
success: function (data) {
$('#npc').html(data);
}
});
});
the res.php page codes are:-
<?php
//connect to the database
$con = mysql_connect("localhost","root","12345") or die("error ".mysql_error());
//connect to the travian table
mysql_select_db("trav",$con) or die("error ".mysql_error());
$building = mysql_real_escape_string($_GET['building']);
$level = mysql_real_escape_string($_GET['level']);
$query = "select * from ";
$query = $query . $building;
$query = $query . "where lvl=" . $level;
$query = $query . ";";
$result = mysql_query($query) or die('Error in Child Table!');
$data = mysql_fetch_assoc($result);
echo '<table><tr><td>Lumber=$data["lumber"]</td><td>Clay=$data["clay"]</td><td>Iron=$data["iron"]</td><td>Crop=$data["crop"]</td>';
?>
I am receiving the error
Notice: Undefined index: building in C:\xampp\htdocs\debal\res.php on line 8
Notice: Undefined index: level in C:\xampp\htdocs\debal\res.php on line 9
Error in Child Table!
How am i to extract both the parameters that were sent to the page and use them in the sql query to retrieve the data from the table in the database.
Please could you help me..
The problem is you are sending $_POST values through AJAX and trying to assign variables from $_GET on your res.php page. Change either AJAX function to type: "GET", or
$building = mysql_real_escape_string($_POST['building']);
$level = mysql_real_escape_string($_POST['level']);
on res.php
also you're not sending the 'level' variable properly, you're missing an '&'
data = 'building=' + buildingVal.val() + '&level=' + levelVal.val();
I am trying to pass some values to my PHP page and return JSON but for some reason I am getting the error "Unknown error parsererror". Below is my code. Note that if I alert the params I get the correct value.
function displaybookmarks()
{
var bookmarks = new String();
for(var i=0;i<window.localStorage.length;i++)
{
var keyName = window.localStorage.key(i);
var value = window.localStorage.getItem(keyName);
bookmarks = bookmarks+" "+value;
}
getbookmarks(bookmarks);
}
function getbookmarks(bookmarks){
//var surl = "http://www.webapp-testing.com/includes/getbookmarks.php";
var surl = "http://localhost/Outlish Online/includes/getbookmarks.php";
var id = 1;
$.ajax({
type: "GET",
url: surl,
data: "&Bookmarks="+bookmarks,
dataType: "jsonp",
cache : false,
jsonp : "onJSONPLoad",
jsonpCallback: "getbookmarkscallback",
crossDomain: "true",
success: function(response) {
alert("Success");
},
error: function (xhr, status) {
alert('Unknown error ' + status);
}
});
}
function getbookmarkscallback(rtndata)
{
$('#pagetitle').html("Favourites");
var data = "<ul class='table-view table-action'>";
for(j=0;j<window.localStorage.length;j++)
{
data = data + "<li>" + rtndata[j].title + "</li>";
}
data = data + "</ul>";
$('#listarticles').html(data);
}
Below is my PHP page:
<?php
$id = $_REQUEST['Bookmarks'];
$articles = explode(" ", $id);
$link = mysql_connect("localhost","root","") or die('Could not connect to mysql server' . mysql_error());
mysql_select_db('joomla15',$link) or die('Cannot select the DB');
/* grab the posts from the db */
$query = "SELECT * FROM jos_content where id='$articles[$i]'";
$result = mysql_query($query,$link) or die('Errant query: '.$query);
/* create one master array of the records */
$posts = array();
for($i = 0; $i < count($articles); $i++)
{
if(mysql_num_rows($result)) {
while($post = mysql_fetch_assoc($result)) {
$posts[] = $post;
}
}
}
header('Content-type: application/json');
echo $_GET['onJSONPLoad']. '('. json_encode($posts) . ')';
#mysql_close($link);
?>
Any idea why I am getting this error?
This is not json
"&Bookmarks="+bookmarks,
You're not sending JSON to the server in your $.ajax(). You need to change your code to this:
$.ajax({
...
data: {
Bookmarks: bookmarks
},
...
});
Only then will $_REQUEST['Bookmarks'] have your id.
As a sidenote, you should not use alert() in your jQuery for debugging. Instead, use console.log(), which can take multiple, comma-separated values. Modern browsers like Chrome have a console that makes debugging far simpler.