I have a question re. receiving data from php-function to ajax.
Ajax (in html-file):
function showUser(name) {
$.ajax({
type: 'POST',
url: '/api.php',
data: {
name : "\""+name+"\"",
func_id : "1"
},
dataType: 'json',
success: function(data)
{
if (data == null) {
console.log("Something went wrong..");
} else {
console.log(data);
Php (separate php-file):
<?php
error_reporting(E_ALL);
//MySQL Database connect start
$host = "localhost";
$user = "root";
$pass = "root";
$databaseName = "TFD";
$con = mysqli_connect($host, $user, $pass);
if (mysqli_connect_errno()) {
echo "Failed to connect to database: " . mysqli_connect_error();
}
$dbs = mysqli_select_db($con, $databaseName);
//MySQL Database connect end
$func_id = $_POST['func_id'];
function showUser() {
global $con;
$name = $_POST['name'];
$sql = "SELECT * FROM users WHERE first_name=$name";
$result = mysqli_query($con, $sql);
$array = mysqli_fetch_row($result);
mysqli_close($con);
echo json_encode($array);
}
if ($func_id == "1") {
showUser();
}
?>
The question: Everything works if I don't have the showUser-function in the php, i.e. I receive correct output to ajax if I have all php code in the "root" directly, but when I put that part in a function I don't get anything sent to ajax. The Network-panel in Chrome shows correct query from the sql so $array contains correct data, but I don't receive it in ajax.
Is there a fix for this?
Thanks!
The reason may be that the variables inside a function're visible only for function itself. Try this way:
$name = $_POST['name'];
function showUser($name) {
global $con;
$sql = "SELECT * FROM users WHERE first_name=$name";
$result = mysqli_query($con, $sql);
$array = mysqli_fetch_row($result);
mysqli_close($con);
echo json_encode($array);
}
Note: If you'll use 'mysql_escape_string' to prevent sql injections, don't forget to connect to db first, otherwise 'mysql_escape_string' will return empty string.
Related
How can I iterate through the object sent back from the php script below in my jquery/ajax call?
I tried result[0] whiche gave me back c. That means that I'm being returned a string.What code should I write to be returned company1 etc. ?
DROP DATABASE IF EXISTS test;
CREATE DATABASE test;
USE test;
CREATE TABLE company(
name VARCHAR(255),
id INT PRIMARY KEY AUTO_INCREMENT
);
INSERT INTO company(name) VALUES( 'company1');
INSERT INTO company(name) VALUES( 'company2');
INSERT INTO company(name) VALUES( 'company2');
$.ajax({
type: "GET",
url: "manager-get-company.php",
success: function (response) {
//iterate through response here
//console.log(response[0]; -> log Company1
//console.log(response[1]; -> log Company2
}
});
<?php
//manager-get-company.php
$hostname = 'localhost';
$username = 'root';
$password = '';
$database_name = 'test';
$con = mysqli_connect($hostname,$username,$password,$database_name);
//Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
$sql= mysqli_query($con, 'SELECT name FROM company');
while($row = mysqli_fetch_array($sql)){
echo $row['name'];
}
In ajax add dataType : "json",
$.ajax({
type: "GET",
dataType : "json",
url: "manager-get-company.php",
success: function (response) {
//iterate through response here
if(!response.error){
console.log(response[0]);
}
}
});
In php
$result = [];
//Check connection
if (mysqli_connect_errno()) {
$result['error'] = "Failed to connect to MySQL: " . mysqli_connect_error();
}else{
$sql= mysqli_query($con, 'SELECT name FROM company');
while($row = mysqli_fetch_array($sql)){
$result[] = $row['name'];
}
}
echo json_encode($result);
Edited : use $result['error'] not result['error']
I have my php file on a server that retrieves data from my database.
<?php
$servername = "myHosting";
$username = "myUserName";
$password = "MyPassword";
$dbname = "myDbName";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name, description FROM tableName;";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$row_number = 0;
while($row = $result->fetch_assoc()) {
$row_number++;
echo $_GET[$row_number. ";". $row["id"]. ";". $row["name"]. ";". $row["description"]. "<br>"];
}
} else {
echo "0 results";
}
$conn->close();
?>
Unfortunately, I do not know how to receive data from a php file using javascript.
I would like the script in javascript to display the received data in the console in browser.
The script written in javascript is Userscript in my browser extension(tampermonkey) and php file is on my server.
I've tried to use ajax, unfortunately without positive results.
(the php script works as expected).
JS(not working):
$.ajax({
url: 'https://myserver.com/file.php',
type: 'POST',
success: function(response) {
console.log(response);
}
});
The code within the loop is a little screwy
$_GET[$row_number. ";". $row["id"]. ";". $row["name"]. ";". $row["description"]. "<br>"]
that suggests a very oddly named querystring parameter which is not, I think, what was intended.
Instead, perhaps try like this:
<?php
$servername = 'myHosting';
$username = 'myUserName';
$password = 'MyPassword';
$dbname = 'myDbName';
$conn = new mysqli($servername, $username, $password, $dbname);
if( $conn->connect_error ) {
die( 'Connection failed: ' . $conn->connect_error );
}
$sql = 'select `id`, `name`, `description` from `tablename`;';
$result = $conn->query($sql);
if( $result->num_rows > 0 ) {
$row_number = 0;
while( $row = $result->fetch_assoc() ) {
$row_number++;
/* print out row number and recordset details using a pre-defined format */
printf(
'%d;%d;%s;%s<br />',
$row_number,
$row['id'],
$row['name'],
$row['description']
);
}
} else {
echo '0 results';
}
$conn->close();
?>
A full example to illustrate how your ajax code can interact with the db. The php code at the top of the example is to emulate your remote script - the query is more or less the same as your own and the javascript is only slightly modified... if you were to change the sql query for your own it ought to work...
<?php
error_reporting( E_ALL );
ini_set( 'display_errors', 1 );
if( $_SERVER['REQUEST_METHOD']=='POST' ){
ob_clean();
/* emulate the remote script */
$dbport = 3306;
$dbhost = 'localhost';
$dbuser = 'root';
$dbpwd = 'xxx';
$dbname = 'xxx';
$db = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
$sql= 'select `id`, `address` as `name`, `suburb` as `description` from `wishlist`';
$res=$db->query( $sql );
$row_number=0;
while( $row=$res->fetch_assoc() ){
$row_number++;
/* print out row number and recordset details using a pre-defined format */
printf(
'%d;%d;%s;%s<br />',
$row_number,
$row['id'],
$row['name'],
$row['description']
);
}
exit();
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<script src='//code.jquery.com/jquery-latest.js'></script>
<title>Basic Ajax & db interaction</title>
<script>
$( document ).ready( function(){
$.ajax({
url: location.href,
type: 'POST',
success: function( response ) {
console.log( response );
document.getElementById('out').innerHTML=response;
}
});
} );
</script>
</head>
<body>
<div id='out'></div>
</body>
</html>
Hi you can do it this way:
your php script:
if (isset($_POST["action"])) {
$action = $_POST["action"];
switch ($action) {
case 'SLC':
if (isset($_POST["id"])) {
$id = $_POST["id"];
if (is_int($id)) {
$query = "select * from alumni_users where userId = '$id' ";
$update = mysqli_query($mysqli, $query);
$response = array();
while($row = mysqli_fetch_array($update)){
.......
fill your response here
}
echo json_encode($response);
}
}
break;
}
}
Where action is a command you want to do SLC, UPD, DEL etc and id is a parameter
then in your ajax:
function getdetails() {
var value = $('#userId').val();
return $.ajax({
type: "POST",
url: "getInfo.php",
data: {id: value}
})
}
call it like this:
getdetails().done(function(response){
var data=JSON.parse(response);
if (data != null) {
//fill your forms using your data
}
})
Hope it helps
I'm new to PHP programming and I'm trying to test out a login page alongside JSON and MySQL. I managed to make most of it functional but I can't seem to find a way to make the query in which I verify the username and password to work.
Please help.
Here's the code:
login.js:
$(document).ready(function(){
$('#errorLogin').hide();
$('#formLogin').submit(function(e){
var username=$('#inputUser').val();
var password=$('#inputPassword').val();
$.ajax({
type:'get',
dataType: 'json',
url: 'dist/php/connection-login.php',
data: {
user: username,
pass: password
},
success: function(e){
console.log(e);
}
});
});
});
connection-login.php:
<?php
$con = new mysqli("localhost", "root", "root", "solucionar_manutencoes_db");
$lg_user=$_GET['user'];
$lg_password=$_GET['pass'];
if (mysqli_connect_errno()) trigger_error(mysqli_connect_error());
$qry = mysqli_query($con, "SELECT * FROM tb_login WHERE lg_user = '$lg_user' AND lg_password = '$lg_password';");
$result = mysqli_fetch_assoc($qry);
$row = mysqli_fetch_assoc($result);
if ($row != 0) {
$response["success"] = 1;
echo json_encode($response);
}
else {
$response["failed"] = 0;
echo json_encode($response);
}
?>
Your PHP should be more like:
connect.php - make sure this is a separate secure page
<?php
function db(){
return new mysqli('localhost', 'root', 'root', 'solucionar_manutencoes_db');
}
?>
I would change your JavaScript AJAX to a POST request, unless you have a reason for it.
connection-login.php
<?php
sesson_start(); include 'connect.php';
if(isset($_POST['user'], $_POST['pass'])){
$db = db(); $r = array();
$prep = $db->prepare('SELECT `lg_user` FROM login WHERE `lg_user`=? && lg_user=?');
$prep->bind_param('ss', $_POST['user'], $_POST['pass']); $prep->execute();
if($prep->num_rows){
$prep->bind_result($lg_user); $r['user'] = $lg_user;
$_SESSION['logged_in'] = $lg_user;
}
echo json_encode($r);
}
?
Now if your JavaScript AJAX result does not contain the a e.user then they are not logged in. Of course, you would probably want to store the original password as a SHA1 or stronger and use AES_ENCRYPTION or better for Personal Information, along with SSL.
I see several errors in your code. The first is that you are executing mysqli_fetch_assoc twice: once on the result, and then again on the array the first call returned. The next is that the $response variable was never declared. Here is the fixed PHP script:
<?php
$con = mysqli_connect("localhost", "root", "root", "solucionar_manutencoes_db");
$lg_user=$_GET['user'];
$lg_password=$_GET['pass'];
if (mysqli_connect_errno()) trigger_error(mysqli_connect_error());
$qry = mysqli_query($con, "SELECT * FROM tb_login WHERE lg_user = '$lg_user' AND lg_password = '$lg_password';");
$results = mysqli_fetch_assoc($qry);
$response = [];
if (count($results) != 0) {
$response["success"] = 1;
echo json_encode($response);
}
else {
$response["failed"] = 0;
echo json_encode($response);
}
?>
In your JavaScript make sure to use e.preventDefault() inside #formLogin's submit handler to prevent page reload when that form is submitted.
login.js
$http({
url: 'http://ipadress/login.php',
method: 'POST',
data: {
'var_id': $scope.form.txt_id,
'var_pass': $scope.form.txt_pass
}
}//http
login.php
<?php
session_start();
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
mysql_connect("localhost","root","password");
mysql_select_db("db");
$data = file_get_contents("php://input");
$dataJsonDecode = json_decode($data);
$var_id = $dataJsonDecode->var_id;
$var_pass = $dataJsonDecode->var_pass;
$sql = "SELECT * FROM user WHERE user_login = '".($id)."' and user_pass = '".md5($pass)."'";
$query = mysql_query($sql);
$result = mysql_fetch_array($query);
$resource = mysql_query($sql);
$count_row = mysql_num_rows($resource);
if (!$result) {
$results = '{"results":"not match"}';
} else {
$_SESSION["users_login"] = $result["users_login"];
session_write_close();
if($count_row > 0){
$results = '{"results":"match"}';
} else {
$results = '{"results":"Error"}';
}
}
echo $results;
?>
$http.get('http://ipaddress/data_user.php')
.then(function (response) {
console.log(response.data.results);
$scope.myData = response.data.results;
}, function (error) {
console.log(error);
});
user_data.php
<?php
session_start();
if($_SESSION['users_login'] == ""){
$results = '{"results":"Please Login"}';
echo $results;
}
else{
mysql_connect("localhost","root","password");
mysql_select_db("db");
mysql_query( "SET NAMES UTF8" );
$sql = "SELECT * FROM users WHERE users_login = '".$_SESSION["users_login"]."' ";
$query = mysql_query($sql);
$count_row = mysql_num_rows($query);
if($count_row > 0){
while($result = mysql_fetch_array($query)){
$rows[] = $result;
}
$data = json_encode($rows);
$totaldata = sizeof($rows);
$results = '{"results": '.$data.'}';
}
echo $results;
}
?>
I have problem with login. My $results = please login.
First check what $result["users_login"] contains..
You are getting the please login because you don't have the session data.
I am not sure about your approach, but don't mix php session and Ionic, You can create a kind of API to check user credentials from your ionic App, or else handle it in the ionic app.
Session normally used in websites to pass data through out the page, not for API calls. Think of scenario 10 users access your app simultaneously, How you going to use the Session to verify them?
My advise is, instead of using PHP sessions, you can handle your sessions inside your app using the session storage
Read this. There are plenty of plugin available. OR you can create your as shown here
Good Luck!!
So I'm building a mobile (cordova) app using a mySQL server, PHP, javascript (jQuery) but I have encountered a rather annoying problem.
When sending a test string with AJAX the recieving end, a PHP script does not receive all the data:
function testJson() {
$.ajax({
type: 'POST',
data: {
text: "hello, this is a test to see if the string is send."
},
url: 'http://a.working.url/save.php',
success: function(data) {
alert('succes');
},
error: function(data) {
alert('There was an error adding your comment');
}
});
return false;
}
then at the serverside I have a small PHP script:
<?php
$server = "localhost:3307";
//changed port to 3307
$username = "user";
$password = "pass";
$database = "test";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$comment = $_POST['text'];
echo $comment;
$sql = "INSERT INTO data (comment) ";
$sql .= "VALUES ('$comment')";
if (!mysql_query($sql, $con)) {
die('Error: ' . mysql_error());
} else {
echo "Comment added";
}
mysql_close($con);
?>
but this PHP script did not recieve the full string, when I check using:
echo $_POST['text']
It only got: "hello, this is a test to see if the" (without quotes).
If anybody can help me it would be great cause I cannot continue working on the app unless the data transfer works.
Thanks in advance.