How to send php variable into angularjs function (different files) - php

I have a variable in php file reg.php. I want to send that variable into .js file in different place (app.reg.js). I tried a lot of solutions but they didn't work. I have to admit that I'm a new programmist, and this is my first own project in angularjs.
How my app exactly works :
In index.html i use routing to get to register.html (this working well).
register.html has a form app.reg.js sending it into reg.php
App.reg.js :
http://www.chopapp.com/#kpwad4zs (i'm getting ALL THE TIME "your post is not properly formatted as code -.-).
reg.php (it works fine! Just need variable $loginExist from it :
http://www.chopapp.com/#yvqivk5m
I would like to send variable from reg.php to the app.reg.js file. How to do this? I think i tried all of the solutions from here but non of them worked...

php file
session_start();
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$login = $request->login;
$password = $request->password;
require_once "connect.php";
mysqli_report(MYSQLI_REPORT_STRICT);
try {
$connect = new mysqli($host,$db_user,$db_password,$db_name);
if($connect->connect_errno!=0)
{
throw new Exception(mysqli_connect_errno());
} else {
//Does login exist?
$result = $connect->query("SELECT id FROM `users` WHERE login = '" . mysql_real_escape_string($login) . "'");
$login_count = $result->num_rows;
if($login_count>0) {
$loginExist = true;
}
else {
$loginExist = false;
$password = $login . $password;
$password = password_hash($password, PASSWORD_DEFAULT);
//$sql = "INSERT INTO users (login, password) VALUES ('$login','$password')";
$sql = "INSERT INTO users (login, password)VALUES('" . mysql_real_escape_string($login) . "', '" . mysql_real_escape_string($password) . "')";
if($connect->query($sql) === TRUE) {
echo "ok!";
} else {
echo "Error: " . $sql . "<br>" . $connect->error;
}
}
$connect->close();
}
} catch(Exception $e) {
echo 'Server error!';
}
echo json_encode(['res' => $loginExist]);
?>
js file
app.controller('regCtrl', function ($scope, $window, $http) {
$scope.send = function () {
var form = {
password: scopeToPasswordImput,
login: scopteToLoginImput
};
$http({
url:'reg1.php',
method: "POST",
data: form
}).then(function (response) {
if (response) {
//I Want to use php variable in this section
//$window.alert("");
console.log(response.data.res);
} else {
console.log("Network response was not ok.");
window.location.href = '/';
}
})
};
});

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 get php session data from a google sign in

I am trying to create a website where users login with their google login (https://developers.google.com/identity/sign-in/web/sign-in). The site has multiple pages and gets data for the user from a mysql database. I would like to store the users' data (name, email) in a php session to have ready for the php when accessing the database. The login function works, but I can't figure out how to get the data to php, with it currently all in javascript.
There wasn't a conventional way to do this, but I was able to get the information from the google auth token
function get_var($var_index) {
$id = $_POST["id"];
$id_token = file("https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=" . $id);
$var = str_replace("\"", "", $id_token[$var_index]);
$var = str_replace(",", "", $var);
$var = substr($var, strpos($var, ":") + 2 );
return $var;
}
$name = get_var(12);
$email = get_var(5);
$img_url = get_var(13);
$exp = get_var(8);
$iss = get_var(9);
if ($_SERVER['REQUEST_TIME'] < $exp) {
session_start();
$_SESSION["name"] = $name;
//$_SESSION["imageurl"] = $img_url;
$_SESSION["email"] = $email;
$_SESSION["exp"] = $exp; // when to auto logout
header("LOCATION: page.php");
exit();
} else{
header("LOCATION: loginpage.html");
}
You can use ajax for this. It's a very efficient way. just make sure you have jquery uncmopressed or minified (not slim) in you page and you're good to go.
This my javascript code in my page where the button is:-
function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
$.ajax({
type: "POST",
url: "googlesignin.php?action=google",
data: "gmail=" + profile.getEmail() + "&name=" + profile.getName(),
success: function(result) {
if (result == 1) {
alert("Hello, " + profile.getName());
$("#googlesignin").hide();
} else {
alert("failed to login");
}
}
})
}
So now the new file called googlesignin.php from where you will execute the insert query to the mysql database
if ($_GET['action'] == "google") {
$email = $_POST['gmail'];
$name = $_POST['name'];
$query = "SELECT * FROM google WHERE email='".$email."' AND name='".$name."'";
$result = mysqli_query($link, $query);
if (mysqli_num_rows($result) > 0) {
echo 1;
} else {
$query = "INSERT INTO google (email, name) VALUES ('".$email."', '".$name."')";
$result = mysqli_query($link, $query);
echo 1;
}
}
so now we have stored our post variables as php variables and we can use them easily to execute our insert query. but we need to check whether the email has first registered or not.

Why isn't my pdo mysqli query working correctly from browser, but has correct behavior from Postman?

I'm currently working on a project where a user can subscribe on a class event. They have the event displayed in a calendar and when they click on it, there is a mysqli query executed:
INSERT INTO conduct_user
(user_id, conduct_id)
VALUES
(?, ?)
which subscribes the user for a class event. This works properly with no deviations.
However... When the user clicks a second time on the event, a second query is executed, which should unsubscribe the user from the event:
public function unsubscribe_from_class_event($userId, $eventId)
{
return "
DELETE FROM conduct_user
WHERE user_id = " . $userId . " AND conduct_id = " . $eventId . "
";
}
The above function returns and assigns a variable $sql:
$sql = unsubscribe_from_class_event($userId, $eventId);
It ($sql) in its turn is executed from the connection object $conn:
$result = $conn->query($sql);
if($result){
return true;
} else {
return false;
}
The strange thing is that whenever I execute this from Postman of Chrome, it works properly without any deviations.
However, when I execute it from the browser, it doesn't execute, even though in both cases "true" is returned.
Here is the repo of the project:
https://github.com/mirchev1977-practical-projects/unity-yoga
and below are the files with annotations to understand how the queries are executed. The steps are enumerated and described. Please follow the links and look for notes which will guide you into the flow of the request process. [UPDATE!!!] Here are the notes on github starting from 0.1, 0.2 ...
which will guide you through the code:
https://github.com/mirchev1977-practical-projects/unity-yoga/commit/153fa9c4d9907fd1e38f6a2d7d34649b14e3c457#diff-ca9644a4bcedb12a5bbbf1fbf744e496
Here is the relevant code:
file: src/angular/calendar/calendar.js
Here I call the function unsubscribeEvent(userId, eventId):
if (indexEvent == -1) {
eventsSubscribedOn.push(eventId);
event.attendees.length++;
} else {
unsubscribeEvent(userId, eventId);
event.attendees.length--;
var inx = eventsSubscribedOn.indexOf(eventId);
eventsSubscribedOn.splice(inx, 1);
}
In the same file is the function inself.
file: src/angular/calendar/calendar.js
function unsubscribeEvent(userId, eventId) {
var request = DbRequester.unsubscribeEvent(userId, eventId,
CONFIG.SERVER.CALENDAR_CONTROLLER_PATH,
Helpers.getSessionId(),
Helpers.getUserRole());
request
.done(function(data) {
console.log('success');
console.log(data);
if (data === 'exited') {
Helpers.logout();
return;
}
// Helpers.setLocalStorage(data);
})
.fail(function(data) {
console.log("error");
console.log(data);
// Helpers.logout();
});
}
It calls the method
$dbRequester.unsubscribeEvent = function(userId, eventId, serverPath, sessionId, userRole) {
return $.ajax({
url: serverPath,
type: 'POST',
dataType: 'json',
data: {submit_type: 'unsubscribe_event',
user_id: userId,
event_id: eventId,
session_id: sessionId,
user_role: userRole
}
});
}
from the file src/angular/db_requester.js .
This method $dbRequester.unsubscribeEvent
sends an ajax request to the php backend file:
src/server_files/controllers/calendar_controller.php
and its method:
if ( isset($_POST['submit_type'])
&& $_POST['submit_type'] == 'unsubscribe_event'
&& isset($_POST['user_role'])
&& ($_POST['user_role'] == 'admin'
|| $_POST['user_role'] == 'instructor'
|| $_POST['user_role'] == 'user') ) {
//set session
// $post_session = $_POST['session_id'];
// $sessionIsActive = sessionIsActive($post_session, 'not_as_array');
$sessionIsActive = true;
//set session
if ($sessionIsActive != false) {
$calendar = new CalendarObj(Db::getDb(), new Config());
$calendar->unsubscribeEvent($_POST['user_id'], $_POST['event_id']);
} else {
echo 'exited';
}
}
.
In it is created a CalendarObj
src/server_files/models/calendar/calendar_obj.php and its method
public function unsubscribeEvent($userId, $eventId)
{
$req = new RequesterCalendar();
//Into the class_conduction
$conn = $this->db;
$sql = $req->unsubscribe_from_class_event($userId, $eventId);
$result = $conn->query($sql);
if($result) {
echo 'true';
}
return null;
}
is called.
In it the object
$req = new RequesterCalendar();
is created and assigned to the $req variable.
Then
$req->unsubscribe_from_class_event($userId, $eventId)
is called:
its code is the following:
public function unsubscribe_from_class_event($userId, $eventId)
{
return "
DELETE FROM conduct_user
WHERE user_id = " . $userId . " AND conduct_id = " . $eventId . "
";
}
The $sql variable is assigned and the mysqli query executed on the next row:
$sql = $req->unsubscribe_from_class_event($userId, $eventId);
$result = $conn->query($sql);
Whenever I make this request from Postman
there is no problem.
If I make the request from the browser itself - it does not work.

Phonegap Ajax and wampserver/php

I am currently trying to simply get Ajax to 'activate' a php file on wampserver
Better to show the code that explain I think
The following is a function activated by a button, the HTML/JS all works fine
var jsonString = "";
function jsonconversion(){
jsonString = JSON.stringify(myArr);
return jsonString;
console.log(jsonString);
$.ajax({
type: "POST",
url: "http://xx.xx.xx.xx:80/xx/index2.php",
data: jsonString,
complete: function() {
console.log("Success");
},
error: function() {
console.log("Function: forward_to_server() error")
}
});
}
However, I can't seem to access the php file. For ease, I am not even using the jsonString in the php file, instead I am simply trying to post some integers into a database on wamp. The php file loaded by itself works fine
<?php
$servername = "localhost";
$username = "root";
$password = "xx";
$dbname = "xx";
//$myArray = $_REQUEST['jsonString'];
$myArray = array(100,1,19);
$con = mysqli_connect($servername,$username,$password ,$dbname) or die ("could not connect database");
echo $myArray;
$keys = array_keys($myArray); // get the value of keys
$rows = array(); // create a temporary storage for rows
foreach($keys as $key) { // loop through
$value = $myArray[$key]; // get corresponding value
$rows[] = "('" . $key . "', '" . $value . "')";
// add a row to the temporary storage
}
$values = implode(",", $rows); // 'glue' your rows into a query
$sql = "INSERT INTO php_test (temp, sound, light) VALUES (10,20,30)"; //. $values
$rs = mysqli_query($con,$sql) or die(mysqli_error($con));
if ($con->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $con->error;
}
$con->close();
?>
However when I call the function in phonegap, it doesn't seem to work, I have no errors either which is hurting the process :(
Wamp server is 'online' and I can access it from the internet.
Any guidance on this?
Thanks in advance

Database query not working with xeditable plugin

I have created a table with popup unabled editing with xeditable plugin and trying submit my data with ajax call to the database. The following is my table row code:
echo "<td>" . $row['loan_status'] . "</td>";
I have tried debugging and in the Network tab of firefox I could see the data being posted as follows :
Form Data:
name : "loan_amount"
value: "2000"
pk: "1"
but the response from the post.php is this field is required . Here is my post.php code
$pk = $_POST['pk'];
$name = $_POST['name'];
$value = $_POST['value'];
/*
Check submitted value
*/
if(!empty($value)) {
$result = mysql_query('update k_loans set '.mysql_escape_string($name).'="'.mysql_escape_string($value).'" where loan_id ="'.mysql_escape_string($pk).'"');
print_r($_POST);
} else {
echo "This field is required!";
}
My jquery code for th xeditable plugin is as follows:
$(document).ready(function() {
//toggle `popup` / `inline` mode
$.fn.editable.defaults.mode = 'popup';
$('#loan a').editable({
type: 'text',
name: 'loan_amount',
url: '../payments/post.php',
title: 'Enter amount',
ajaxOptions: {
type: 'put'
}
});
});
But i am unable to understand the issue as the query seems perfectly fine to me , still the database is not getting updated .
Anyone who can guide me in the right direction . Thanks
The first issue with the script provided by the xeditable on their github uses mysql which is not safe to use these days . So I have shifted all of them to use mysqli. Here is the working code for anyones reference :
<?php
$server = "localhost";
$username = "user";
$password = "pass";
$database = "db";
$con = new mysqli($server,$username,$password,$database);
if (!$con){
die('Could not connect: ' . mysqli_connect_error($con));
echo "Cudnt cnnect";}
else{
echo "connected";
}
var_dump($_POST);
$pk = $_POST['pk'];
$name = $_POST['name'];
$value = $_POST['value'];
/*
Check submitted value
*/
if(!empty($value)) {
if ($result = mysqli_query($con,'update k_loans set '.mysqli_real_escape_string($con,$name).'="'.mysqli_real_escape_string($con,$value).'" where loan_id ="'.mysqli_real_escape_string($con,$pk).'"'));
{
echo "Update successful";
}
mysqli_close($con);
print_r($_POST);
} else {
echo "This field is required!";
}
?>

Categories