In my AngularJS app, the data entered into the form are not stored in the MySQL database after hitting the submit button. An alert after successful form data submit however indicates that it is working.
Also, after hitting the submit button, I want the app to proceed to the next view (#/setup-step2) - however it remains at step1.
html partial (#/setup-step1):
<form ng-submit="submitForm1()">
Job title: <input type="text" name="jobtitle" ng-model="formData1.jobtitle">
Vacancy ID: <input type="text" name="vacancyid" ng-model="formData1.vacancyid">
<button type="submit" class="animatedbutton"> Proceed </button>
</form>
controller.js:
var ctr = angular.module('myApp.controller', []);
ctr.controller
('Step1Controller', ['$scope', '$routeParams', '$http', function($scope, $routeParams, $http){
$scope.formData1 = {};
$scope.submitForm1 = function() {
$http({
method: 'POST',
url: 'php/setup-step1.php',
data: $.param($scope.formData1),
headers: { 'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data){
console.log(data);
alert("It worked");
})
.error(function(data) {
console.log(data);
alert("It didn't work");
})
}
}]);
setup-step1.php in folder /php:
<?php
include_once('db.php');
// Check connection
if(mysqli_connect_errno())
{echo '<p>Connection to MySQL server failed: '.mysqli_connect_error().'</p>';}
else
{echo '<p>Connection to MySQL server successful.</p>';}
$_POST = json_decode(file_get_contents("php://input"), true);
if (empty($_POST['jobtitle']))
{$errors['jobtitle'] = 'Job title is required.';}
else {
// Escape user inputs for security
$jobtitle = $_POST['jobtitle'];
$vacancyid = $_POST['vacancyid'];
$data = "INSERT INTO campaign (Job_title, Job_id) VALUES ('$jobtitle','$vacancyid')";mysql_query("INSERT INTO campaign (Job_title, Job_id) VALUES ('$jobtitle', '$vacancyid')");}
if ($connect->query($data) === TRUE)
{$conn->close();}
else
{echo "Error: " . $sql . "<br>" . $conn->error;}
exit();
?>
First,
Be sure that you enable the cors before performing any request to the server.When you are working with angularjs this usually means that you are making cors requests to the server.If you didn't enable cors option you cannot call any method from the server since it is not allowed.
Second,
just keep php code inside your setup-step1.php.You don't need any html code there since it will return result of your requet only.
Third,
As I know you cannot change location of the webpage from erver because server domin and website domains are different.You need to redirect the user to another page in angularjs. You can find the ways of redirecting in angularjs by using $location or $state.
I found the answer myself. The problem was incorrect php and mysql syntax. Updated the code the way it works now.
Related
I am working with phonegap for the first time to build hybrid mobile app with back-end(php, mysql). So i am doing a test on how phonegap can connect to php on localhost to send and retrieve data. But no data was retrieved, I have reduced my codes to the this and i see no errors in both ajax call and php code. So i guess it should be the way phonegap connects to backend that i am getting wrong, please help.
html form and ajax call:
<form id="form1">
<input type="text" id="email" />
<input type="password" id="password" />
<input type="submit" name="login" id="login" value="Login">
</form>
<script type="text/javascript">
$("form").submit(function(){
var data= ("#form1").serialize();
$.post("http://localhost/securityapp/login.php",data,function(response){
alert(response);
});
});
</script>
php file:
<?php
include 'db.php';
session_start();
if ($_POST ) {
echo $_POST;
}
?>
Basically it is meant to alert to values sent to php script as the response but it is not doing so, network tab says 200 for status. what am i doing wrong? I feel phonegap isn't connecting to the url defined
This is how I solved this issue:
created a table on a database that holds the current URL/IP of the server
Created a check-url.php file, this file runs a query on the database to see IP/URL of
the server
I created a connection.js file, this file basically makes a request to a check-url.php
to get current IP of the server to use in Cordova app
check-url.php
header("Access-Control-Allow-Origin: *"); //to allow phonegap access it because of cross origin and domain restrictions
require 'db.php';
$query= "SELECT url FROM settings";
$query= mysqli_query($conn,$query);
$row = mysqli_fetch_assoc($query);
$row= $row['url'];
echo $row; //current IP exmaple:http://127.0.0.1:80/
connection.js
//check current server ip from database
export function check_url(callback) {
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === 4) { // request is done
if (httpRequest.status === 200) { // successfully
callback(httpRequest.responseText); // we're calling our method
}
}
};
httpRequest.open('GET', "http://127.0.0.1:80/projectname/check-url.php");
httpRequest.send();
}
So any time I want to connect to backend by Cordova I import the function check-url() from connection.js into my front-end ajax request url like this:
<script type="module">
import {check-url} from './connection.js';
check-url(function(result) {
var currentIP= result;
$.ajax({
type:"POST",
url: currentIP + "projectapp/login.php",
data:data,
success: function(data){
//do something
}
});
});
</script>
Note: The URL/IP in connection.js, database, and server IP should be the same, as this helps you not to repeat IP always and also to test when using PhoneGap mobile and also when you switch to live, change it to the current IP address of your project.
I have a form in a popup modal that should be used for user login there are two input fields one for ID card number and second for password .. The collected data are sent by ajax to a php page called login.php that should check the user user entered data and create a session for it if he is active user and transfers him to home page and if he is not active user transfers him to student-registration page and if the entered data are wrong a paragraph within the form should give a notification to the user .. now there is nothing happening when I submit the form where did missed up !!
html strcture:
<div id="std-login-modal" class="modal">
<header class="modal-header">
<h3>تسجيل الدخول كطالب</h3>
<i class="fa fa-times modal-close"></i>
</header>
<div class="modal-body">
<form id="std-login-frm" method="POST">
<div>
<input type="text" id="std-card" name="stdID" autocomplete required>
<label>رقم القيد</label>
<i class="fa fa-exclamation"></i>
<div class="input-desc">
<span>هذا الحقل خاص بادخال رقم قيد الطالب المكون من سبعة أرقام</span>
</div>
</div>
<div>
<input type="password" id="std-pass" name="stdPass" required>
<label>كلمة المرور</label>
<i class="fa fa-exclamation"></i>
<div class="input-desc">
<span>هذا الحقل خاص بكلمة المرور الخاصة بالطالب</span>
</div>
</div>
<div>
<input type="submit" value="تسجيل دخول" name="stdLoginBtn">
<p id="std-login-error"></p>
</div>
</form>
</div>
<footer class="modal-footer">
<p>لا يوجد لديك حساب في الموقع؟ قم بانشاء واحد</p>
<button id="create-std-account" class="modal-second-btn">انشاء حساب</button>
</footer>
</div>
My jquery code:
$(document).ready(function(){
// Student Login Operation
$("#std-login-frm").submit(function(e){
e.prvenetDefault();
// Get Student Entered Data From The Inputs
var stdID = $("#std-card").val().trim();
var stdPass = $("#std-pass").val().trim();
// Call AJAX Method And Specify Its Parameters
$.ajax({
url: "login.php?type=student",
type: "POST",
data: {ID:stdID,Password:stdPass},
dataType:"json",
error: function(data){
$("#std-login-error").html(data.fail);
}
});
});
});
login.php code:
<?php
include'connect.php';
if(isset($_POST['stdLoginBtn']))
{
$type = '';
if(isset($_GET['type']))
{
$type = $_GET['type'];
if($type == 'student')
{
// Get Data Sent By AJAX POST Request
$ID = $_POST['ID'];
$pass = $_POST['Password'];
// Check if the user exist in database
$stmt = $con->prepare("select ID,password,status,name,phone,
token from students where ID=?");
$stmt->execute(array($ID));
$info=$stmt->fetch();
if(password_verify($pass,$info["password"]))
{
if($info["status"] == 1)
{
$_SESSION['stdID'] = $info["ID"];
header('Location:home.php');
exit();
}
else
{
$_SESSION['mobile'] = $info["phone"];
$_SESSION['token'] = $info["token"];
$_SESSION['name'] = $info["name"];
header('Location:student-registration.php');
exit();
}
}
else
{
$fail = "خطأ في البيانات يرجى إعادة المحاولة";
$data = array('error' => $fail);
echo json_encode($data);
}
}
}
}
?>
I also will provide the connection code to mysql:
<?php
$dsn='mysql:host=localhost;dbname=vcm';
$user='root';
$pass='';
$option=array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
try{
$con= new PDO($dsn,$user,$pass,$option);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
echo 'Failed to connect' . $e->getMessage();
}
?>
You need to invoke session_start(); in your php program before you output anything to a page that uses or sets any session variables. That allows them to be saved in the session manager, and feeds a cookie to your user's browser identifying the session. In subsequent web requests the user's browser passes along the session cookie.
Additionally, if your ajax request goes to a different domain than the one served by your page, you should include this in your ajax options.
xhrFields: {
withCredentials: true
}
Finally, the browser doesn't look at any Location: header returned in a response to an AJAX request (only in a page response). You need to process that header yourself in your Javascript code.
Something like this may do the trick for you:
success: function(data, text, request){
document.location.href = request.getResponseHeader('Location');
}
Putting it all together, your ajax request might look like this (not debugged).
// Call AJAX Method And Specify Its Parameters
$.ajax({
url: "login.php?type=student",
type: "POST",
data: {ID:stdID,Password:stdPass},
dataType:"json",
xhrFields: {
withCredentials: true
},
success: function(data, text, request){
var target = request.getResponseHeader('Location');
alert('About to redirect to ' + target);
document.location.href = target;
},
error: function(data){
$("#std-login-error").html(data.fail);
}
});
Edit You are trying to do something very hard, involving a lot of moving parts: html, Javascript, php, ajax, sql, and redirection. It's admirable that you want to figure out how to do this; you'll learn a lot. If you need to just finish this task, forget about the ajax and just post the login form to php.
If you want to get this working, you should open up the developer tools on your browser ( on PCs, right-click/inspect on any platform).
The Console tab shows you diagnostic information about your pages. You can put console.log(whatever); lines in your Javascript and they'll show up on the console.
In the Network tab you can see the requests to and responses from your php AJAX endpoints including the Location header values and cookie values.
The Source tab is a debugger. You can set breakpoints on lines of Javascript so you can see what's happening. Suggestion: set breakpoints on the first lines of the success: and error: functions.
You can get yourself a browser web extension like Edit This Cookie, to help you inspect the cookies fed to your browser by your ajax and GET/POST responses.
If you have a debugger server-side for your php, that will help too. There's far more to learn about this than can appear in a Stack Overflow answer.
I assume i am doing something really simply wrong here (to all you seasoned programmers), but forgive me i have spent hours and hours reading trying to understand how AJAX calls work...
My variables aren't making it to recordsale.php to be inserted into SQL table.
The javascript variables are displayed on the HTML page, so i know they contain data.
Can anyone offer some advice?
(any response knocking my ability will not be appreciated - I AM TRYING :) )
My form submit button in html looks like this
<form action="recordsale.php" method="post">
<input type="image" src="assets/CompleteSale.png" alt="Submit"> </form>
My AJAX Post Function:
$( "#submit" ).submit(function( event ) {
alert("hello");
// Jquery code for making AJAX call to server side script
$.ajax({
method: "POST",
url: "recordsale.php",
data: { adultqty: adultticketqty, concessionqty: concessionticketqty, studentqty: studentticketqty, childqty: childticketqty, programqty: programqty, totalsell: totalsaleprice }
})
//alert(adultqty + childqty)
});
Recordsale.php
<?php
$adultticketqty = $_POST['adultqty'];
$concessionticketqty = $_POST['concessionqty'];
$studentticketqty = $_POST['studentqty'];
$childticketqty = $_POST['childqty'];
$programqty = $_POST['programqty'];
$totalsaleprice = $_POST['totalsell'];
//include('phpsqlget.php');
/* Attempt MySQL server connection. Assuming you are running MySQL server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "speedway", "speedwayticketsales");
// Check connection
if($link === false){ die("ERROR: Could not connect. " . mysqli_connect_error()); } // Attempt insert query execution
$sql = "INSERT INTO stdsalesrecords (qtyadulttickets, qtyconcessiontickets, qtystudenttickets, qtychildtickets, qtyprograms, totalsell) VALUES ($adultticketqty,$concessionticketqty,$studentticketqty,$childticketqty,$programqty,$totalsaleprice)";
if(mysqli_query($link, $sql)){
echo "Records inserted successfully."; }
else{ echo "ERROR: Could not able to execute $sql. "
. mysqli_error($link); } // Close connection mysqli_close($link);
?>
This is how i usually do my ajax submissions. there are other ways of handling form submission.
Check out $(form).serialize() amongst others.
$( "#submit" ).submit(function( event ) {
var adultticketcty = $('selector').val();
//continue filling out the fields and mirror them in the below dataString.
var dataString = 'adultqty='+adultticketcty+'&concessionqty='+concessionticketqty;
//Check if you set the correct values in the datastring.
console.log(dataString);
$.ajax({
type: "POST",
url: "recordsale.php",
data: dataString,
success: function(data){
//check whatever is returned from recordsale.php
console.log(data);
}
});
});
then in your recordsale.php do this to see if anything is returned in your ajax success call:
$adultticketqty = $_POST['adultqty'];
$concessionticketqty = $_POST['concessionqty'];
echo $adultticketqty;
Not related to the question, but i wanna recommend checking out pdo queries to prevent sql injections etc.
solved my issue
had to write a function to write my JS Variables into hidden elements in the form
function save()
document.getElementById("qty").value = Aqty;
then add the hidden elements to my form
<form method="post" name="submit" id="submit" action="record.php" >
<input type="hidden" id="qty" name="qty" value="" >
<input type="submit" value="Submit" onclick="save();">
works a treat!
I've literally checked out every single ng-repeat question out there but a lot of them don't deal with databases and people just use arrays in JS and a simple $scope.array.push("stuff") works for them.
I've tried $scope.apply, $rootScope and even calling the GET request right after a successful POST request.
I have a form with 2 text inputs, date and content.
When the submit button is pressed, date and content are added into a MySQL database using PHP.
The data is added just fine to the MySQL database and retrieving also works properly.
Even the GET request inside the successful POST request is executed.
So I don't understand why it forces me to refresh the page to see the updated ng-repeat results.
Am I missing something?
Any help or suggestions is greatly appreciated, thanks!
Relevant HTML code
<div ng-controller="insertController">
<h2> What I learned today </h2>
<form>
Date <br>
<input type="text" ng-model="date"><br><br>
Content <br>
<textarea rows="10" cols="50" ng-model="content"></textarea><br><br>
<input type="button" value="Submit" ng-click="insertdata()">
</form>
</div>
<div ng-controller="fetchController">
<span ng-repeat="item in results">
{{item.date}}<br>
{{item.content}}<br><br>
</span>
</div>
insertController.js
var app = angular.module('myApp', []);
app.controller('insertController', function($scope, $http) {
$scope.insertdata = function() {
$http({
method: 'POST',
url: 'http://localhost/storestuff/insert.php',
data: {'date':$scope.date, 'content':$scope.content, 'in':'json-format'},
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.then(function(res) {
console.log("Successful response", res)
$scope.date = "";
$scope.content = "";
$http.get('http://localhost/storestuff/fetch.php')
.then(function successCallback(response) {
alert("GOT NEW DATA");
$scope.results = response.data; // Allow angular to access the PHP output data
});
$scope.apply;
})
.catch(function(err) {
console.error("Error with POST", err);
});
}
});
insert.php
<?php
header('Access-Control-Allow-Origin: *');
$theConnection = mysqli_connect("localhost", "root", "", "storestuff");
if(mysqli_connect_errno()) {
echo "Failed to connect to MySQL.";
}
$theData = json_decode(file_get_contents('php://input'));
$date = mysqli_real_escape_string($theConnection, $theData->date);
$content = mysqli_real_escape_string($theConnection, $theData->content);
mysqli_query($theConnection, "INSERT INTO thestuff(date, content) VALUES('$date', '$content')");
mysqli_close($theConnection);
?>
fetchController.js
app.controller('fetchController', function ($scope, $http) {
$http.get('http://localhost/storestuff/fetch.php')
.then(function successCallback(response) {
$scope.results = response.data; // Allow angular to access the PHP output data
});
});
fetch.php
<?php
header('Access-Control-Allow-Origin: *'); // clientside(Node) <-> serverside(PHP)
$mysqli = new mysqli("localhost", "root", "", "storestuff");
if($mysqli->connect_error) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$query = "SELECT * FROM thestuff";
$theData = array();
if($result = $mysqli->query($query)) {
while($row = mysqli_fetch_array($result)) {
$theData[] = array(
'date'=>$row['date'],
'content'=>$row['content']);
}
echo json_encode($theData); // Echo the output for the controller to access
$result->free(); // Free the result set
}
else {
echo "0 results.";
}
$mysqli->close(); // Close the connection
?>
The problem with this code is that you have two different controllers, both with separate scopes. Inserting/updating the $scope.results object/array in one controller, will not update the other $scope; they are separate distinct scopes, both with a copy of the data.
Using two controllers looks correct in your use case. However you should be using a service to access your remote data. Check out this answer for some advice on this https://stackoverflow.com/a/20181543/2603735.
Using a service like in that answer, will allow you to store the array/object of remote data in one place, and reference the SAME object from both controllers. Therefore updating from one controller, will also update the other.
For anyone who will ever stumble on my question, I don't want to just leave my broken code there with no answer but neither can I edit the question and put in my answer cause that would defy the purpose of StackOverflow.
So here is my answer to my own question.
I had to make quite a few changes to what I had before. The biggest change by far, is how I handled the data that was returned by fetch.php.
Instead of just taking the output into $scope.results = response.data;, which would work fine if I wasn't dynamically adding to the database, but for this case, I ended up using a service. (Thanks #jayden-meyer for suggesting Angular services.)
The service allowed me to access the same array from my insertController and from my fetchController instead of having a copy of the same array in both controllers which was my problem.
No changes in the HTML code.
No changes to insert.php.
No changes to fetch.php.
insertController.js
I removed the extraneous GET request I had inside the .then method which was completely unneeded since I can just push to the existing array.
(Thanks #charlietfl for the tip)
Instead I added resultsService.addItem($scope.date, $scope.content); inside of the .then method.
I also added my service as an argument.
app.controller('insertController', function($scope, $http, resultsService) {
result.js
app.service('resultsService', function() {
var results = new Array();
var addItem = function(date, content) {
var obj = new Object();
obj["date"] = date;
obj["content"] = content;
results.push(obj);
}
var getItems = function() {
return results;
}
return {
addItem: addItem,
getItems: getItems
};
});
fetchController.js
var size = 0;
var count = 0;
app.controller('fetchController', function ($scope, $http, resultsService) {
$http.get('http://localhost/storestuff/fetch.php')
.then(function successCallback(response) {
size = (response.data).length;
while(count < size) {
var date = response.data[count].date;
var content = response.data[count].content;
resultsService.addItem(date, content);
count++;
}
size = 0;
count = 0;
$scope.results = resultsService.getItems();
});
});
Hi All and thanks for your time!
I am new to AngularJS and currently working on my first form with server side part.
I am running on VirtualBox, used Yeoman to set up.
my HTML has 2 fields: username and password, that are in turn passed to the js file:
function authUsers($scope, $http) {
$scope.url = '../api/authUsersService.php'; // The url of our search
// The function that will be executed on button click (ng-click="search()")
$scope.loginAttempt = function() {
// Create the http post request
// the data holds the keywords
// The request is a JSON request.
alert($scope.session.username);alert($scope.session.password);
$http.post($scope.url, { "username" : $scope.session.username, "password" : $scope.session.password}).
success(function(data, status) {
$scope.status = status;
$scope.data = data;
$scope.result = data; // Show result from server in our <pre></pre> element
alert(data);
})
.
error(function(data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
alert(data);
alert(status);
});
};
}
I am getting the 2 alerts (username, password).
This file and the HTML itself is under Angular's APP folder. outside the folder, in the same containing folder: I created 'API' folder. this is the file api/authUsersService.php:
<?php
$data = file_get_contents("php://input");
$objData = json_decode($data);
// Create connection
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno($con)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con, "select userID from authUsers where username = " . $objData->username . " and password = " . $objData->password);
if ($result->num_rows > 0) {
$row = $result->fetch_array(MYSQLI_ASSOC);
echo $row["userID"];
} else {
echo "";
}
?>
when the HTML form is submitted, i am getting all the alerts from the controller (js file), including the ".error" ones. the data i am getting inside the error: "cannot post to /api/authUsersService.php" and the status is "404".
i couldn't find any solution. tried an .htaccess in the var\www\http folder, didnt help.
please help me successfully get to the PHP server code!
thanks!
Using "../" in a URL is a good indicator you're doing something wrong.
You can't go "outside" the root directory of your webserver, so you need to put it inside the "app" directory, so that it's web accessible.