I am having an issue while using JSON server for login form. I have login credentials like Username and password and trying to execute it. I have used POST on the server, specifying username and password inserted by the user. The server should execute a query on the specified condition, to check if there are any rows with that name and password. If yes return true, if false return false. then the client should parse this response.
This is my HTML code :
<form ng-submit="loginform(logcred)" name="logform"><br/><br>
<tr ng-repeat="logcred in loginfo"></tr>
<div>
<label form="emailinput"><b>Email</b></label>
<input type="email" class="form-control" name="uname" id="emailinput" placeholder="you#example.com" ng-model="logcred.username" >
</div>
<div>
<label form="pwdinput"><b>Password</b></label>
<input type="password" class="form-control" name="pwd" id="pwdinput" placeholder="*******" ng-model="logcred.password">
</div>
<div>
<button type="cancel" class="btn" ng-click="toggle_cancel()">Cancel</button>
<button class="btn btn-primary" ng-click="submit()">Login</button>
</div>
</form>
This is the Javascript code using AngularJS:
var myApp = angular.module('myApp', []);
myApp.controller('credientials', function($scope, $http) {
$http.get('http://localhost:3000/loginfo')
.then(
function successCallback(response){
$scope.loginfo == response.data;
$scope.loginform = function(loginfo,username,password){
console.log(loginfo);
$http({
url :'http://localhost:3000/loginfo',
method : 'POST',
data : loginfo
})
.then(
function successCallback(response){
$scope.loginfo = response.data;
if (username === username && password === password) {
console.log(response);
}
else
{
console.log("Error: " + response)
}
});
}
});
I am getting the response properly from my server. But when I match the data using POST request using if condition, there I am not understanding what mistake I am doing ?
Any help / advice would be greatly appreciated.
i didnt understand if your problem is server side or client ? is your problem at
if (username === username && password === password) {
console.log(response);
}
you may use == insted of ====
You are comparing the data with itself.
username === username && password === password
Should be
username === $scope.loginfo.username && password === $scope.loginfo.password
Still, any kind of security validation should be done on the server rather than on the client.
Also, you seem to be new to Angular. Let me recommend to you the John Papa's Styleguide.
Here is my HTML code:
<form class="addtowatchlistform" action="logo/insertwatchlist.php" method="POST">
<input type="hidden" name="tmdb_id" value="'.$result[$x]["tmdb_id"].'"/>
<button id="addtowatchlistbutton" type="submit" name="tmdb_id" value="'.$result[$x]["tmdb_id"].'" data-tooltip="'.$addremove.' TO YOUR WATCHLIST" class="material-icons" style="color:'.$watchlisticoncolor.'">add_box</button>
</form>
// Same form as above
<form class="addtowatchlistform" action="logo/insertwatchlist.php" method="POST">
<input type="hidden" name="tmdb_id" value="'.$result[$x]["tmdb_id"].'"/>
<button id="addtowatchlistbutton" type="submit" name="tmdb_id" value="'.$result[$x]["tmdb_id"].'" data-tooltip="'.$addremove.' TO YOUR WATCHLIST" class="material-icons" style="color:'.$watchlisticoncolor.'">add_box</button>
</form>
Jquery Code:
<script>
$(".addtowatchlistform").submit(function(e) {
var data = $(this).serialize();
var url = $(this).attr("action");
$.post(url, data, function() {
});
return false;
});
</script>
What it currently do?
When someone click on add_box (submits the form) button, it runs insert.php in the background.
The insert.php file sets 2 variables inside it, i.e:
$addremove and $watchlisticoncolor. I want to run this variables in my main file also. (You can find those variables inside <form> tag, I want to replace them), in the real time without reloading the page.
How can I do it with Jquery or PHP ajax code?
As the comments suggested you can use JSON data to exchange the data you want between the server and the client
the server code (insertwatchlist.php) file
<?php
$response = new \stdClass();
$response->addremove = "item1";//you can get the data anyway you want(e.g database)
$response->watchlisticoncolor = "red";
die(json_encode($response));
And your client side ajax function could be something like this
$.post(url, data, function() {
try {
data = JSON.parse(data);
$("button#addtowatchlistbutton").data('tooltip', data.addremove + " TO YOUR WATCHLIST");
$("button#addtowatchlistbutton").css('color',data.watchlisticoncolor);
} catch (e) {
console.log("json encoding failed");
return false;
}
});
I have a form to create some folders (albums) to upload images. When I create an album with accented characters the accented characters are not displayed. For example: "Álbum" is displayed "lbum".
I am loading the albums on a list to further open the images according to each list item click. I don´t use database in this part of the app.
Is there a way to fix this in the app script? I tried to solve it using some examples like this one ($sce) but it did work.
I get this error when I try to usu it on response.data.
Error: [$sce:itype] Attempted to trust a non-string value in a content requiring a string: Context: html
list html
<ion-list id="fotos-list4" ng-show="albums_list">
<ion-item class="item-icon-left item-icon-right calm no-border" id="fotos-list-item4" ng-model="album_name" ng-repeat="item in albums" item="item" href="#/item/{{item.FOLDER}}" ng-click="open_album(item)" ng-bind-html="trust">
<i class="icon ion-images"></i>
{{item.FOLDER}}
<i class="icon ion-ios-arrow-forward"></i>
</ion-item>
</ion-list>
controller
.controller('albumsCtrl', ['$scope', '$http', '$state', '$sce', function ($scope, $http, $state, $sce) {
$http.get("http://website.com/dashboard/select-albuns.php").then(function(response){
console.log(response);
console.log(JSON.stringify(response));
$scope.albums = response.data;
$scope.trust = $sce.trustAsHtml($scope.albums);
}, function(response){
$scope.albums_list = false;
$scope.display_error = true;
}).finally(function(){
$scope.loading = false;
});
...
php script
$path = "images";
$dirs = glob($path."/*", GLOB_ONLYDIR);
foreach($dirs as $dir){
$reg = array(
"FOLDER" => basename($dir).PHP_EOL
);
$return[] = $reg;
}
$return = json_encode($return);
echo $return;
I have an extremely similar service like the one in this thread:
Php: Form auto-fill using $_SESSION variables with multiple php files
I would have asked there but since I don't have 50 reputation, I'll have to ask a new question.
To understand Ajax better I wanted to re-create rkmax's files and see if they would work. So I saved them as 5 separate files.
The SESSION does not seem to store any posted information. Added a print_r($_SESSION); to keep track of what's currently in there. Furthermore the .blur event to retrieve account information via the phone number doesn't work either.
Been banging my head against the wall for days with this one. It won't work when working either hosted locally via Apache/XAMPP or on an actual web server. All 5 files are in the same folder and titled exactly the same as rkmax's file titles.
I understand the logic behind each of the functions and can't seem to find a problem anywhere. I'm pretty new to coding so it could easily be something obvious like file structure or my own computer's settings?
Read a bunch of other StackOverflow threads with similar problems, but none of them seemed whatsoever applicable.
Thanks for your time.
Here's everything copied from rkmax's code:
index.php
<?php
session_start();
if (!isset($_SESSION['customers'])) {
$_SESSION['customers'] = array(
'1234567' => '{"lname": "Berg", "mi": "M", "fname": "Thomas", "account": "1234"}',
'1122334' => '{"lname": "Jordan", "mi": "C", "fname": "Jacky", "account": "4321"}',
);
}
require __DIR__ . '/index_template.php';
index_template.php
<!doctype html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="jquery.js"></script>
<script src="scripts.js"></script>
</head>
<body>
<div style="margin-left: 300px">
<form id="dataForm" method="post">
<fieldset>
<legend>User info</legend>
<label for="fname">First name</label>
<input id="fname" type="text" name="fname" placeholder="First name"/>
<label for="mi">Middle inicial</label>
<input id="mi" type="text" name="mi" placeholder="Middle Initial"/>
<label for="lname">Last name</label>
<input id="lname" type="text" name="lname" placeholder="Middle Initial"/>
<label for="phone">Phone number</label>
<input id="phone" type="text" name="phone" placeholder="000000"/>
</fieldset>
<fieldset>
<legend>Account info</legend>
<label for="account">Account</label>
<input id="account" type="text" name="account"/>
</fieldset>
<input type="submit" name="submit"/>
<input type="reset" name="clear"/>
</form>
</div>
</body>
</html>
postCustomerInformation.php
session_start();
// example: converts $_POST['phone'] into $post_phone if exists
extract($_POST, EXTR_PREFIX_ALL, 'post');
// Validates that all required information was sent
if (isset($post_lname) && isset($post_fname) && isset($post_phone) && isset($post_account)) {
$customer = array(
'fname' => $post_fname,
'lname' => $post_lname,
'account' => $post_account,
'mi' => isset($post_mi) ? $post_mi : '' // optional
);
$_SESSION['customers'][$post_phone] = json_encode($customer);
// returns a valid json format header
header('Content-Type: application/json');
header("HTTP/1.0 204 No Response");
} else {
// returns error
header('Content-Type: application/json');
header("HTTP/1.0 400 Bad Request");
}
getCustomerInformation.php
session_start();
// example: converts $_GET['phone'] into $get_phone if exists
extract($_GET, EXTR_PREFIX_ALL, 'get');
if (isset($get_phone) && isset($_SESSION['customers'][$get_phone])) {
header('Content-Type: application/json');
echo $_SESSION['customers'][$get_phone];
} else {
header('Content-Type: application/json');
echo '{}';
}
scripts.js
;(function () {
"use strict";
function getCustomerInformation() {
var phone = jQuery(this).val();
if (!phone) {
return;
}
jQuery.ajax({
type: 'get',
url: 'getCustomerInformation.php',
data: {
phone: phone
},
success: function getCustomerInformation_success(data) {
// for each returned value is assigned to the field
for (var i in data) {
if (data.hasOwnProperty(i)) {
$('#' + i).val(data[i]);
}
}
}
});
}
function postCustomerInformation(event) {
event.preventDefault();
var form = jQuery(this);
jQuery.ajax({
type: 'post',
url: 'postCustomerInformation.php',
data: form.serializeArray(),
success: function postCustomerInformation_success() {
alert("OK");
},
error: function postCustomerInformation_error() {
alert("Error");
}
})
}
// set behaviors when document is ready
jQuery(document).ready(function document_ready() {
jQuery('#phone').blur(getCustomerInformation);
jQuery('#dataForm').submit(postCustomerInformation);
});
})();
I would try and do something a bit scaled down, see if this is what you are trying to do. You only need 3 pages, the original form page, the php page, and the js file:
/ajax/dispatch.php
/*
** #param $phone [string] Gets key from session
*/
function getCustomerByPhone($phone)
{
if(!empty($_SESSION['customers'][$phone])) {
// I am decoding, but if you have the ability to set,
// create an array like below with success and data
$values = json_decode($_SESSION['customers'][$phone]);
die(json_encode(array("success"=>true,"data"=>$values)));
}
}
function makeError()
{
// Send back error
die(json_encode(array("success"=>false,"data"=>false)));
}
/*
** #param $array [string] This will be a query string generated from the
** jQuery serialize, so it's to be turned to array
*/
function updateSession($array)
{
// This should come back as a string, so you will need to parse it
$data = false;
parse_str(htmlspecialchars_decode($array),$data);
// Update the session
$_SESSION['customers'][$data['phone']] = json_encode($data);
die(json_encode(array("success"=>true,"data"=>$data)));
}
if(isset($_POST['phone'])) {
// If already exists, return to ajax the data
getCustomerByPhone($_POST['phone']);
}
elseif(isset($_POST['data'])) {
updateSession($_POST['data']);
}
// If not exists, return false
makeError();
/scripts.js
// I try not to duplicate things as much as possible
// so I would consider making an object to reuse
var AjaxEngine = function($)
{
this.ajax = function(url,data,func,method)
{
method = (typeof method === "undefined")? 'post' : 'get';
$.ajax({
url: url,
data: data,
type: method,
success: function(response) {
func(response);
}
});
};
};
$(document).ready(function(){
// Create instance
var Ajax = new AjaxEngine($);
var dispatcher = '/ajax/dispatch.php';
// On submit of form
$(this).on('submit','#dataForm',function(e) {
// Get the form
var thisForm = $(this);
// Stop form from firing
e.preventDefault();
// Run ajax to dispatch
Ajax.ajax(dispatcher,
// Serialize form
$('#dataForm').serialize(),
// Create an anonymous function to handle return
function(response) {
// Parse
var resp = JSON.parse(response);
// See if data exists
if(typeof resp.data === "undefined") {
console.log(resp.data);
return false;
}
// If there is a hit in session
else if(resp.success == true) {
// Loop through it and fill empty inputs in form
$.each(resp.data, function(k,v){
var input = $("input[name="+k+"]");
if(input.length > 0) {
if(input.val() == '') {
input.val(v);
}
}
});
}
// Run the session update
Ajax.ajax(dispatcher,
// This time send an action
// (just to differentiate from check function)
{
"action":"update",
"data":thisForm.serialize()
},
function(response) {
// Check your console.
console.log(response);
});
});
});
});
Started from scratch working on my answer pretty much nonstop, but gotta go to work soon, here's what I've got so far; I'm currently stuck on successfully sending the SESSION data back to the javascript and decoding it and displaying it successfully. Once I have that working I think sending those to the appropriate forms as well as the POST will be trivial. If anyone has any suggestions to speed me through this last part I would appreciate it.
Edit: Edited with the final solution.
index2.php
<?php
session_start();
if (!isset($_SESSION['customers'])) {
$_SESSION['customers'] = array(
'1111111' => '{"phone": "1111111", "fname": "Za", "lname": "Zo", "mi": "Z", "account": "1234"}',
'2222222' => '{"phone": "2222222", "fname": "La", "lname": "Li", "mi": "L", "account": "4321"}',
);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title> Assignment5 </title>
<meta charset = "utf-8" />
<script type = "text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type = "text/javascript" src = "scripts.js"></script>
</head>
<body>
<form id="myform">
<input placeholder="Phone Number" name="phone" type="text" id="phone" maxlength="7" autofocus>
<input placeholder="First Name" name="fname" type="text" id="fname">
<input placeholder="Last Name" name="lname" type="text" id="lname">
<input placeholder="Middle Initial" name="mi" type="text" id="mi">
<input placeholder="Account Number" name="account" type="text" id="account" maxlength="4">
<input type="submit" value="Submit">
</form>
</body>
</html>
scripts.js
$(document).ready(function(){
$("#phone").blur(function(){
var session;
var currentPhone = $("#phone").val();
$.get("getPhone.php", {phone: currentPhone}, function(data) {
for (var i in data) {
if (data.hasOwnProperty(i)) {
$('#' + i).val(data[i]);
}
}
});
});
$("form").submit(function(){
var form = jQuery(this);
$.post("postPhone.php", form.serializeArray(), function(data) {
alert(data);
});
});
});
getPhone.php
<?php
session_start();
$nowPhone = $_GET["phone"];
if (array_key_exists($nowPhone, $_SESSION['customers'])) {
header('Content-Type: application/json');
echo $_SESSION['customers'][$nowPhone];
} else {
header('Content-Type: application/json');
echo '{}';
}
?>
postPhone.php
<?php
session_start();
if (isset($_POST["phone"]) && isset($_POST["fname"]) && isset($_POST["lname"]) && isset($_POST["mi"]) && isset($_POST["account"])) {
echo ("Submitted");
$customer = array(
'phone' => $_POST["phone"],
'fname' => $_POST["fname"],
'lname' => $_POST["lname"],
'mi' => $_POST["mi"],
'account' => $_POST["account"],
);
$_SESSION['customers'][$_POST["phone"]] = json_encode($customer);
}
else
echo ("All Information is Required");
?>
I am using HTML and using amazon EC2 (Linux free tier). I would like to use CloudFront, but my newsletter won't work. I am not an AWS expert, and I don't have a clue as to why it won't work on CloudFront.
My newsletter form looks like this:
<form id="subscribe" class="form" action="<?=$_SERVER['PHP_SELF']; ?>" method="post">
<div class="form-group form-inline">
<input size="15" type="text" class="form-control required" id="NewsletterName" name="NewsletterName" placeholder="Your name" />
<input size="25" type="email" class="form-control required" id="NewsletterEmail" name="NewsletterEmail" placeholder="your#email.com" />
<input type="submit" class="btn btn-default" value="SUBSCRIBE" />
<span id="response">
<? require_once('assets/mailchimp/inc/store-address.php'); if($_GET['submit']){ echo storeAddress(); } ?>
</span>
</div>
</form>
and my js file looks like this:
jQuery(document).ready(function() {
jQuery('#subscribe').submit(function() {
// update user interface
jQuery('#response').html('<span class="notice_message">Adding email address...</span>');
var name = jQuery('#NewsletterName').val().split(' ');
var fname = name[0];
var lname = name[1];
if ( fname == '' ) { fname=""; }
if ( lname == '' || lname === undefined) { lname=""; }
// Prepare query string and send AJAX request
jQuery.ajax({
url: 'assets/mailchimp/inc/store-address.php',
data: 'ajax=true&email=' + escape(jQuery('#NewsletterEmail').val()),
success: function(msg) {
if (msg.indexOf("Success") !=-1) {
jQuery('#response').html('<span class="success_message">Success! You are now
subscribed to our newsletter!</span>');
} else {
jQuery('#response').html('<span class="error_message">' + msg + '</span>');
}
}
});
return false;
});
});
and my php file looks like this:
<?php
function storeAddress(){
require_once('MCAPI.class.php'); // same directory as store-address.php
// grab an API Key from http://admin.mailchimp.com/account/api/
$api = new MCAPI('mymailchimpapi');
$merge_vars = Array(
'EMAIL' => $_GET['email'],
'FNAME' => $_GET['fname'],
'LNAME' => $_GET['lname']
);
// grab your List's Unique Id by going to http://admin.mailchimp.com/lists/
// Click the "settings" link for the list - the Unique Id is at the bottom of that page.
$list_id = "myuniqueid";
if($api->listSubscribe($list_id, $_GET['email'], $merge_vars , $_GET['emailtype']) === true) {
// It worked!
return 'Success! Check your inbox or spam folder for a message containing a
confirmation link.';
}else{
// An error ocurred, return error message
return '<b>Error:</b> ' . $api->errorMessage;
}
}
// If being called via ajax, autorun the function
if($_GET['ajax']){ echo storeAddress(); }
?>
The form works when I access it without using CloudFront, but I am worried of the server bandwidth that's why I want to use CloudFront. What happens is that when you click the submit button, the "adding email address" message will just appear for 1 second, and the email address entered is ignored.
Please make sure your CloudFront distribution is actually configured to handle POST/PUT requests. Take a look here for details: http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#DownloadDistValuesAllowedHTTPMethods