i have question related to PHP - AngularJs, so i have simple PHP script
<?php
require_once '../../dbConnect.php';
$driverId = $_POST['driverId'];
if (isset($_POST['driverId'])) {
$sql = "delete from drivers where driver_id='$driverId'";
if ($mysqli->query($sql) === TRUE) {
echo mysqli_insert_id($mysqli);
} else {
echo "Error updating record: " . $mysqli->error;
}
$mysqli->close();
}
?>
At the moment i pass data to script like this
return $http({
method: 'POST',
url: '/api/drivers/deleteDriver.php',
data: $.param(driverObject),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
And i don't like that code, on other Java project i send params to end points with angularjs $resource service like this
var deleteDriverResouce = $resource('/api/drivers/deleteDriver.php');
function deleteDriver() {
deleteDriverResouce.save(driverObject);
}
And as you can see that is cleaner code and easier to use, i'm wondering can i use $resource service to pass object to php script ?
So i have found solution and i will share it here so maybe someone will need it. In order to use AngularJs $resource service you just need to make small change in PHP script, just add $object = json_decode(file_get_contents("php://input"), true); on that way you can access to object that you sent via $resource. And here is example of one working PHP script.
<?php
require_once '../dbConnect.php';
session_start();
$object = json_decode(file_get_contents("php://input"), true);
if (isset($object['email']) && isset($object['password'])) {
$email = $object['email'];
$password = $object['password'];
$query="select * from members where email='$email'";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
$row = mysqli_fetch_assoc($result);
if($row) {
if (password_verify($object['password'], $row['password'])) {
$_SESSION["id"] = $row['id'];
echo 'Login Success!';
} else {
session_destroy();
var_dump(http_response_code(400));
}
} else {
session_destroy();
var_dump(http_response_code(406));
}
$mysqli->close();
} else {
session_destroy();
var_dump(http_response_code(400));
}
?>
And on UI i have this simple and minimal code:
var userLoginObject = {
email: 'login#email.com',
password: 'password123'
};
var authenticationResource = $resource('/api/authentication/authenticate.php');
function logIn() {
authenticationResource.save(userLoginObject );
}
That's much better and cleaner than using ugly
return $http({
method: 'POST',
url: '/api/drivers/authenticate.php',
data: $.param(userLoginObject),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
Related
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.
Apologies if this is a repeat question, but any answer I have found on here hasn't worked me. I am trying to create a simple login feature for a website which uses an AJAX call to PHP which should return JSON. I have the following PHP:
<?php
include("dbconnect.php");
header('Content-type: application/json');
$numrows=0;
$password=$_POST['password'];
$username=$_POST['username'];
$query="select fname, lname, memcat from members where (password='$password' && username='$username')";
$link = mysql_query($query);
if (!$link) {
echo 3;
die();
}
$numrows=mysql_num_rows($link);
if ($numrows>0){ // authentication is successfull
$rows = array();
while($r = mysql_fetch_assoc($link)) {
$json[] = $r;
}
echo json_encode($json);
} else {
echo 3; // authentication was unsuccessfull
}
?>
AJAX call:
$( ".LogIn" ).live("click", function(){
console.log("LogIn button clicked.")
var username=$("#username").val();
var password=$("#password").val();
var dataString = 'username='+username+'&password='+password;
$.ajax({
type: "POST",
url: "scripts/sendLogDetails.php",
data: dataString,
dataType: "JSON",
success: function(data){
if (data == '3') {
alert("Invalid log in details - please try again.");
}
else {
sessionStorage['username']=$('#username').val();
sessionStorage['user'] = data.fname + " " + data.lname;
sessionStorage['memcat'] = data.memcat;
storage=sessionStorage.user;
alert(data.fname);
window.location="/awt-cw1/index.html";
}
}
});
}
As I say, whenever I run this the values from "data" are undefined. Any idea where I have gone wrong?
Many thanks.
This is my ajax call.
$(document).on('click','#Quote_create_value',function(){
$.ajax({
type : 'GET',
url : '../../../protected/config/ajax.php',
success : function(response){
$("#Quote_template_value").html(response);
}
});
});
I have many methods in ajax.php. Each and every method throws some response.
<?php
function respose()
{
$query = "select * from quote where template IS NOT NULL";
$result = mysql_query($query, $con);
while ($row = mysql_fetch_assoc($result)) {
echo '<option value="'.$row['template'].'">' . $row['template'] . '</option>';
}
$query1 = "select * from template";
$data = mysql_query($query1,$con);
while ($row = mysql_fetch_assoc($data)) {
echo json_encode($row);
}
}
function result()
{
}
?>
But i want to get response from one method [ie. from response()].
How can this be done?
You could include a selector in the ajax request data. Like this for example:
$(document).on('click','#Quote_create_value',function(){
$.ajax({
type : 'GET',
url : '../../../protected/config/ajax.php',
data: "function=result",
success : function(response){
$("#Quote_template_value").html(response);
}
});
});
Then in your PHP code, a simple if-statement will check which one to output.
if(isset($_GET['function'])) {
if($_GET['result'] == 'result') {
// do result stuff
} elseif($_GET['function'] == 'response') {
// do response stuff
}
}
I have read through dozens of similar questions on this website, and am having a lot of trouble trying to understand what is wrong with my code. I am trying to dynamically update select boxes based on the value of another one, but for some reason cannot seem to get any type of response data back once I post to PHP with Ajax.
JAVASCRIPT:
function toggleHiddenDIV()
{
var dc = document.getElementById("datacenter");
var dcVal = dc.options[dc.selectedIndex].value;
// Check if Datacenter selection has no Value selected
if(dcVal != '')
{
document.getElementById("hidden-options").style.display="block";
$.ajax({
type: "POST",
url: "handler.php",
data: { 'action_type': 'update_inventory_fields', id: dcVal },
success: function(response)
{
alert(response);
}
});
}
else
{
document.getElementById("hidden-options").style.display="none";
}
};
</script>
PHP:
if ($_POST['action_type'] == "update_inventory_fields")
{
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["id"])) { return; }
}
$result = mysql_query("SELECT id, ip, block FROM ipv4 WHERE datacenter = " . $_POST["id"]);
$data = array();
while($row = mysql_fetch_array($result, true))
{
$data[] = $row;
};
return json_encode($data);
}
Don't call return (since you're not returning a function); just echo then content onto the page:
echo json_encode($data);
Change to this...no need to return, just echo, since youre outside of a function call
if ($_POST['action_type'] == "update_inventory_fields")
{
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["id"])) { return; }
}
$result = mysql_query("SELECT id, ip, block FROM ipv4 WHERE datacenter = " . $_POST["id"]);
$data = array();
while($row = mysql_fetch_array($result, true))
{
$data[] = $row;
};
echo json_encode($data);
}
If the php code you posted is inside a function than you need to use echo functionname();
If the php code is not in a function, then just use echo json_encode($data);
I have some ajax code that executes on mouseclick. It calls a file called update.php that does a bunch of stuff, including checking for user permissions, numerous database calls, etc. In the end, I also want to be able to return a few variables from PHP for the callback to use, but not sure how to reference them - or if there's a better way to return this info.
$.ajax({
type: "POST",
url: "update.php",
data: dataString,
success: callback
});
function callback(data, status)
{
// $("div").text(data);
$("div.numbert").text("[first variable here]");
$("div.numbert2").text("[second variable here]");
}
From my update.php file (some snippets):
if ($check_access > 0)
{
// Update database
$sql = "UPDATE db SET access = '1' WHERE user = '$user'";
$result = mysql_query($sql) or die(mysql_error());
// Give access - function returns data to variable
$value = GiveAccess($user);
// Email - function returns data to variable
$emaillist = emailAdmins($user);
} else {
$message = "Sorry you do not have access";
}
So I'd like to figure out how to use the variables $message, $value and $emaillist in my callback if possible.
I'm wondering if I just need to make multiple $.ajax POST calls, with each .php function that returns a variable having it's own call?
Thanks!
----UPDATE-------
Updated code trying to use the json methods - thanks for all the help - but seems I'm missing one last thing.
$.ajax({
type: "POST",
url: "update.php",
data: dataString,
dataType: 'json',
success: callback
});
function callback(data, status)
{
// $("div").text(data);
$("div.numbert").text(data.value);
$("div.numbert2").text(data.emaillist);
and update.php:
$storage = array();
// Update database
$sql = "UPDATE db SET access = '1' WHERE user = '$user'";
$result = mysql_query($sql) or die(mysql_error());
// Give access - function returns data to variable
$storage['value'] = "some user";
// Email - function returns data to variable
$storage['emaillist'] = "some stuff";
header('Content-type: application/json');
echo json_encode($storage);
exit(0);
Thanks again.
You can use a JSON wrapper:
$messages = array();
$messages['value'] = GiveAccess($user);
$messages['emaillist'] = emailAdmins($user);
$messages['message'] = "Sorry you do not have access";
echo json_encode($messages);
And then simply use:
data.value data.emaillist data.message
in your Javascript.
Easiest way would be to use JSON...
$.ajax({
type: "POST",
url: "update.php",
data: dataString,
dataType: 'json',
success: callback
});
function callback(data, status)
{
// $("div").text(data);
if(data.error){
alert(error.message||'Unknown Error');
} else {
$("div.numbert").text(data.access||'No value');
$("div.numbert2").text(data.emailList||'No value');
}
}
PHP:
if ($check_access > 0)
{
// Update database
$sql = "UPDATE db SET access = '1' WHERE user = '$user'";
$result = mysql_query($sql) or die(mysql_error());
$responseData = array();
// Give access - function returns data to variable
$responseData['access'] = GiveAccess($user);
// Email - function returns data to variable
$responseData['emailList'] = emailAdmins($user);
} else {
$responseData['error'] = array('code' => 403, 'message' => "Sorry you do not have access");
}
header('Content-type: application/json');
print json_encode($responseData);
exit(0);
No, just return a JSON object or a dataset that's delimited that you can parse.
You can return your values using json:
$storage = array();
if ($check_access > 0)
{
// Update database
$sql = "UPDATE db SET access = '1' WHERE user = '$user'";
$result = mysql_query($sql) or die(mysql_error());
// Give access - function returns data to variable
$value = GiveAccess($user);
$storage['value'] = $value;
// Email - function returns data to variable
$emaillist = emailAdmins($user);
$storage['emaillist'] = $emaillist;
} else {
$message = "Sorry you do not have access";
$storage['message'] = $message;
}
header("Content-Type: application/json; charset=utf8");
$return = json_encode($storage);
echo $return;
exit;
You can then iterate over the object and go
function callback(data, status)
{
// $("div").text(data);
$("div.numbert").text(data.value);
$("div.numbert2").text(data.emaillist);
}