Ionic Angular pass data to PHPfile and insert into MySQL database - javascript

Something strange happen, I pass insert data from angular controller to php file. Next, php file is inserting data into MySQL database. All the data is successfully inserted. However once I click on button two record is inserted into MySQL database. One will the empty data is inserted and second is the data I entered from UI. The following is my code:
Javascript controller Code:
.controller('registerController',['$scope', '$stateParams', '$state', '$http', function($scope, $stateParams, $state, $http){
var userInformation = [];
$scope.registration = {};
console.log($stateParams.all);
$scope.doRegister = function () {
if( $scope.registration.pasword !== $scope.registration.confirmpassword){
alert("Password not match");
}
$http({
url: "http://localhost/php/chat.php",
method: "POST",
data: {
'username': $scope.registration.username,
'email': $scope.registration.emailaddress,
'password': $scope.registration.pasword
}
}).success(function(response) {
console.log(response);
}).error(function(response) {
console.log(response);
});
$state.go('login', {userInformation : userInformation});
};
$scope.goBack = function() {
$state.go('login');
}
}])
PHP Code
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$user = $request->username;
$email = $request->email;
$pass = $request->password;
$servername = "localhost";
$username = "jack";
$password = "1234";
$dbname = "chat";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO use_directory VALUES ('', '$user', '$email', '$pass');" ;
$retval = $conn->multi_query($sql);
if( $retval === TRUE) {
echo "Add successfully\n";
}else {
die('Could not edit data');
}
?>
Here is my database outcome

$sql = "INSERT INTO use_directory (user,email,pass) VALUES ( '$user','$email', '$pass')" ;
if(mysqli_query($conn, $sql)){
echo "Add successfully\n";
}else{
die('Could not edit data');
}
Have you tried like this? Hope it helps :)

Related

Post method return Json data keeps on looping

So, I am building a website that tries to first post an id from the front end then on the php file. The post method return a questions that is base on the id that is send to the backend and query through the database. This is my code
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: access");
header("Access-Control-Allow-Methods: GET,POST");
header("Content-Type: application/json; charset=UT-8");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
$servername = "localhost";
$username = "root";
$password = "";
$database= "credentials";
// Create connection
$db = mysqli_connect($servername, $username, $password, $database);
// Check connection
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
$postdata = file_get_contents("php://input");
if(isset($postdata) && !empty($postdata)){
$request = json_decode($postdata);
$quizID = $request->QuizID;
$sql = "SELECT * FROM question WHERE QuizID='$quizID'";
$result = mysqli_query($db,$sql);
if(mysqli_num_rows($result)>0){
$json_array = array();
while($row = mysqli_fetch_assoc($result))
{
$json_array[] = $row;
}
$response = ["data"=>"valid","quiz"=>$json_array];
echo json_encode($response);
}else{
$response = ["data"=>"invalid"];
echo json_encode($response);
}
}
?>
The front end was successfully return the JSON data but it keeps looping non stop. Why is that happening, I tried running the query first then I store in variable but still it keeps looping.
This is my front end code
useEffect(()=>{
console.log("use effect");
const sendData = {
QuizID: localStorage.getItem("quizID")
}
console.log("adad")
axios.post("http://localhost/pepep/fetchLesson.php", sendData).then(res=>{
console.log("post success");
console.log(res.data.quiz[0]);
setQuestion([res])
})
})
Can anyone help me with this ?
You have setQuestion([res]) which will set the state to a new value.
Setting the state will trigger a re-render.
Your useEffect call doesn't have a dependency array, so it will run on every render.
Add a dependency array with a list of variables that should trigger the function when they change.
Since you don't appear to be using any external variables, it looks like that should be none.
useEffect( () => { /* ... */ }, [] );

PHP get mysql data and return to javascript with ajax

I'm reading the values of my MySql-Databasetable with php like this:
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: PUT, GET, POST");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
$servername = "localhost";
$username = "wsl_home";
$password = "wsl";
$dbname = "wsl_home";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['functionname']) == 'getDrinks') {
$sql = "SELECT ID, Drinkname FROM drinks";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["ID"]. " - Name: " . $row["Drinkname"]. "<br>";
return $row;
}
} else {
echo "0 results";
}
}
?>
This works and i get the values as expected. Now I want to return them to my javascript using ajax to call the php function:
jQuery.ajax({
type: "POST",
url: 'drinks.php',
dataType: 'json',
data: {functionname: 'getDrinks', arguments: [1, 2]},
success: function (obj, textstatus) {
if( !('error' in obj) ) {
console.log("hi " + obj);
yourVariable = obj.result;
}
else {
console.log(obj.error);
}
}
});
But I get no output in the success function. Does somebody know how to accomplish this task?

Session Variable showing undefined

I have made the login page using ionic and it seems to work well. The $_SESSION variable also gets displayed after successfull login. Then in another php file, when I try to print the same session variable, it shows undefined or not set. Also, the session expires after refresh and it shows an alert to login again
Here is my login php code
<?php
ob_start();
session_start();
$errmsg_arr = array();
$errflag = false;
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers:{$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}
$errors = array();
$data = array();
// Getting posted data and decodeing json
$_POST = json_decode(file_get_contents('php://input'), true);
require_once 'db_functions.php';
$db = new db_functions();
if(empty($_POST['doc_key']))
{
$data['errors'] = 'Please enter all the credentials';
echo json_encode($data);
}
else if(empty($_POST['password']))
{
$data['errors'] = 'Please enter all the credentials';
echo json_encode($data);
}
else
{
$doc_key = $_POST['doc_key'];
$password = $_POST['password'];
$user = $db->getDoctorByEmailAndPassword($doc_key, $password);
if( $user == true)
{
//session_regenerate_id();
$_SESSION['name'] = $user["name"];
$_SESSION['contact'] = $user["contact"];
$_SESSION['email'] = $user["email"];
$_SESSION['license_no'] = $user["license_no"];
$_SESSION['type'] = $user["type"];
$_SESSION['gender'] = $user["gender"];
$_SESSION['location'] = $user["location"];
$_SESSION['fees'] = $user["fees"];
$_SESSION['experience'] = $user["experience"];
$_SESSION['doc_key'] = $user["doc_key"];
//session_write_close();
$data['message'] = $_SESSION['name'];// "User logged in successfully";
echo json_encode($data);
}
else
{
$data['errors'] = 'Login Credentials are invalid';
echo json_encode($data);
}
}
?>
This is the code of other page where I want to display the session variable
<?php
ob_start();
session_start();
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers:{$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}
$data = array();
$type_user = "";
if(isset($_SESSION['user_name']) || isset($_SESSION['license_no']))
{
if($type_user == "doctor")
{
$data["name"] = $_SESSION["name"];
$data["email"] = $_SESSION["email"];
$data["contact"] = $_SESSION["contact"];
$data["license_no"] = $_SESSION["license_no"];
$data["doc_key"] = $_SESSION["doc_key"];
$data["gender"] = $_SESSION["gender"];
$data["type"] = $_SESSION["type"];
$data["location"] = $_SESSION["location"];
$data["fees"] = $_SESSION["fees"];
$data["experience"] = $_SESSION["experience"];
echo json_encode($data);
}
else
{
$data["name"] = $_SESSION["name"];
$data["email"] = $_SESSION["email"];
$data["contact"] = $_SESSION["contact"];
$data["gender"] = $_SESSION["gender"];
$data["user_name"] = $_SESSION["user_name"];
echo json_encode($data);
}
}
else
{
$data["errors"] = "Please login first to see this";
echo json_encode($data);
}
?>
This page does not return the session data to controller. It shows blank
Here are the codes of controllers and ionic code
Controller for login page
.controller('doctorloginCtrl', function($scope,$http,$window) {
$scope.doctor = {};
$scope.loginDoc = function(){
$http({
method: 'POST',
url: 'http://localhost/drmedic/login_doctor.php',
data: $scope.doctor,
headers: {'ContentType': 'application/x-www-form-urlencoded'}
})
.success(function(data){
if(data.errors)
{
alert(JSON.stringify(data.errors));
}
else
{
alert(JSON.stringify(data.message));
$window.location.href = "#/home";
}
});
}
})
Controller for the other page where I want to show the details
.controller('profileCtrl', function($scope,$http,$ionicSideMenuDelegate,$window) {
$ionicSideMenuDelegate.toggleLeft();
$http({method: 'GET', url: 'http://localhost/drmedic/retrieve_login_details.php'}).success(function(data) {
if(data.errors)
{
alert(data.errors);
$window.location.href = "#/select-role";
}
else
{
$scope.contents = data;
console.log($scope.contents);
}
});
})
After login, when I go to the profile page by typing localhost:8100/#profile, it shows blank.. It does not display the {{contents.name}} field
IONIC CODE for Profile page
<ion-view title="Profile">
<ion-content overflow-scroll="true" padding="true" scroll="false" class="has-header">
Hi {{contents.name}}
</ion-content>
</ion-view>
The sessions used to work properly for my other project. Can't figure it out why it isn't working for this one. Is it because of the Authentication-Allow-Cross headers??
Please help.
Use Javascript localStorage Property. It will store data in your device until you remove it. So this is very easy to keep some data in the device. You can acccess it from anywhere in your code if it is exists.
// Store
localStorage.setItem("lastname", "Smith");
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("lastname");
for more information visit https://www.w3schools.com/jsref/prop_win_localstorage.asp

How to create a signup form with ajax, php and parsing json

first of all I'm new with jQuery and PHP. My aim is to create a signup form, passing data to my server on wamp. My query is working, a new record is created in the database, but I can't figure out why it is showing the error log of the ajax call instead of the success one.
Ajax call
$('#reg-button').click(function(event){
$.ajax({
url: 'http://localhost:80/project/signup.php',
type: 'POST',
dataType: 'json',
data: {
email:$("#email").val(),
username:$("#username").val(),
password:$("#password").val()
},
error: function() {
console.log("error");
},
success:function(data){
console.log("success");
var responseData = jQuery.parseJSON(data);
}
});
event.preventDefault();
});
PHP
$response = array();
if (isset($_POST['email']) && isset($_POST['username']) && isset($_POST['password'])){
$email = $_POST['email'];
$username = $_POST['username'];
$password = $_POST['password'];
$query = "INSERT INTO user (email, username, password) VALUES ('$email', '$username', '$password')";
$result = mysqli_query($conn, $query);
if($result){
$row_cnt = mysqli_num_rows($result);
printf("Result set has %d rows.\n", $row_cnt);
mysqli_free_result($result);
$response['success'] = 1;
$response['message'] = "User registered";
echo json_encode($response);
} else {
$response['success'] = 0;
$response['message'] = 'Ops, user not registered';
echo json_encode($response);
}
} else {
$response['success'] = 0;
$response['message'] = 'Required fields are missing';
echo json_encode($response);
}
Could you help me with fixing these problems, giving me some tips or tutorials?

Why does my website think the $http request is cross domain?

In my website I'm calling to a php page at http://domain.com/angulartest/js/services/index.php
from a service in the same folder.
app.factory('vakmannen', ['$http', function($http) {
return $http.get('http://www.domain.com/angulartest/js/services/index.php')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}]);
and this is my php
<?php
header("Access-Control-Allow-Origin: http://www.domain.com/angulartest/");
$servername = "localhost";
$username = "XXXXX";
$password = "XXXXX";
$dbname = "XXXXX";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM XXXX";
$result = $conn->query($sql);
while($row = $result->fetch_array(MYSQL_ASSOC)) {
$myArray[] = $row;
}
echo json_encode($myArray);
?>
But every time the $http.get runs Firefox tells me the CORS header isn't right, I've tried it on Chrome too but to no avail.
Any help will be greatly appreciated!
If the angular app is in the same folder, you can use relative URLs. You can even remove the Access-Control-Allow-Origin header.
app.factory('vakmannen', ['$http', function($http) {
return $http.get('/angulartest/js/services/index.php')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}]);

Categories