I want to call one addPost.php file through ajax function, and return the result as post submitted or not.
For that I am calling userAction function onClick of a button but now I am not getting the data through post, when I tried to access the post array data in addPost.php file its sending the error as undefined index category.
Can anyone please help what is going wrong?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Post</title>
</head>
<body>
<form class="postForm" id="postForm" method="post" action="addPost.html">
<fieldset>
<legend>Please add the details below </legend>
<p>
<label for="title">Title (required, at least 2 characters)</label>
<input id="title" name="title" minlength="2" type="text" required>
</p>
<p>
<label for="url">URL (required)</label>
<input id="url" type="url" name="url">
</p>
<p>
<label for="desc">Description (required, at least 2 characters)</label>
<input id="desc" name="desc" minlength="2" type="text" required>
</p>
<p>
<label for="keywords">Keywords (eg:#facebook)(required, at least 2 characters)</label>
<input id="keywords" name="keywords" minlength="2" type="text" required>
</p>
<p>
Select Url Type :
<select name="urlType" id="urlType">
<option value="">Select Url Type...</option>
<option value="0">Server Image</option>
<option value="1">Server Video</option>
<option value="2">YouTube Video</option>
<option value="3">Vimeo Video</option>
<option value="4">Facebook Image</option>
<option value="5">Facebook Video</option>
<option value="6">Instagram Image</option>
<option value="7">Instagram Video</option>
<option value="-1">Other</option>
</select>
</p>
<p>
Select Category :
<select name="category" id="category">
</select>
</p>
<p>
<input type="button" name="Submit" id="Submit" value="Submit" onclick="userAction('add')">
</p>
</fieldset>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
getCategories();
function getCategories() {
$.ajax({
type: "POST",
url: 'getCategories.php',
dataType: 'text',
async: false,
cache: false,
success: function (result) {
$('#category').html(result);
}
});
}
function userAction(type,id){
id = (typeof id == "undefined")?'':id;
var statusArr = {add:"added",edit:"updated",delete:"deleted"};
var userData = '';
if (type == 'add') {
userData = $("#postForm").find('.form').serialize() + '&action_type=' + type + '&id=' + id;
}
$.ajax({
type: 'POST',
url: 'addPost.php',
data: userData,
success:function(report){
alert(report)
}
});
}
</script>
</form>
</body>
</html>
addPost.php
include 'Database.php';
ini_set('display_errors', 1);
error_reporting(1);
ini_set('error_reporting', E_ALL);
if(isset($_POST['action_type']) && !empty($_POST['action_type'])) {
if($_POST['action_type'] == 'add') {
/* $database = new Database(Constants::DBHOST, Constants::DBUSER, Constants::DBPASS, Constants::DBNAME);
$dbConnection = $database->getDB();
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbConnection->prepare("insert into keywords(keyword)
values(?)");
$stmt->execute(array($_POST['keywords']));
//insert data into posts table
$stmt = $dbConnection->prepare("insert into posts(category_id,title,url,url_type,description,keywords)
values(?,?,?,?,?,?)");
$stmt->execute(array($_POST['category'], $_POST['title'], $_POST['url'], $_POST['urlType'], $_POST['desc'], $_POST['keywords']));
$count = $stmt->rowCount();
if ($count > 0) {
//if inserted
$response = array("status" => -1, "message" => "Post Submitted");
return $response;
} else {
//if not inserted
$response = array("status" => -1, "message" => "Could not submit post.");
return $response;
}*/
echo $_POST['category'], $_POST['title'], $_POST['url'], $_POST['urlType'], $_POST['desc'], $_POST['keywords'];
}
}
EDIT :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Post</title>
</head>
<body>
<form class="postForm" id="postForm" method="post" action="addPost.php">
<fieldset>
<legend>Please add the details below </legend>
<p>
<label for="title">Title (required, at least 2 characters)</label>
<input id="title" name="title" minlength="2" type="text" required>
</p>
<p>
<label for="url">URL (required)</label>
<input id="url" type="url" name="url" required>
</p>
<p>
<label for="desc">Description (required, at least 2 characters)</label>
<input id="desc" name="desc" minlength="2" type="text" required>
</p>
<p>
<label for="keywords">Keywords (eg:#facebook)(required, at least 2 characters)</label>
<input id="keywords" name="keywords" minlength="2" type="text" required>
</p>
<p>
Select Url Type :
<select name="urlType" id="urlType">
<option value="">Select Url Type...</option>
<option value="0">Server Image</option>
<option value="1">Server Video</option>
<option value="2">YouTube Video</option>
<option value="3">Vimeo Video</option>
<option value="4">Facebook Image</option>
<option value="5">Facebook Video</option>
<option value="6">Instagram Image</option>
<option value="7">Instagram Video</option>
<option value="-1">Other</option>
</select>
</p>
<p>
Select Category :
<select name="category" id="category">
</select>
</p>
<p>
<input type="hidden" name="action_type" id="action_type_id"/>
<input type="hidden" name="id" id="p_id"/>
<input type="button" name="Submit" id="Submit" value="Submit" onclick="userAction('add')">
</p>
<p id="report"></p>
</fieldset>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
getCategories();
$("#postForm").validate();
function getCategories() {
$.ajax({
type: "POST",
url: 'getCategories.php',
dataType: 'text',
async: false,
cache: false,
success: function (result) {
$('#category').html(result);
}
});
}
function userAction(type,id){
var statusArr = {add:"added",edit:"updated",delete:"deleted"};
if (type == 'add') {
$('#action_type_id').val(type);
$('#p_id').val(id);
}
$.ajax({
type: 'POST',
url: 'addPost.php',
data: $('#postForm').serialize(),
success:function(report){
$('#report').html(result);
}
});
}
</script>
</form>
</body>
</html>
Now By this edit code the data is getting insert in the database but I want to show the result in para in add.html so I have given the id of para in success method but this is not working, also form validation is not working.
Please help. Thank you.
You can use hidden value to send data in server.In your form place this two fields.
<input type="hidden" name="action_type" id="action_type_id"/>
<input type="hidden" name="id" id="p_id"/>
And your ajax method will be like:
function userAction(type,id){
var statusArr = {add:"added",edit:"updated",delete:"deleted"};
if (type == 'add') {
$('#action_type_id').val(type);
$('#p_id').val(id);
}
$.ajax({
type: 'POST',
url: 'addPost.php',
data: $('#postForm').serialize(),
success:function(report){
alert(report);
}
});
}
Explanation: Before submitting the form, you set type and id value to hidden field and send the entire form to server.now you can able to get all post data by $_POST['action_type'] and $_POST['id'].
echo $_POST['category'], $_POST['title'], $_POST['url'], $_POST['urlType'], $_POST['desc'], $_POST['keywords']
in this statement, you are trying to access "category", "title" etc. But you have not passed that fields in ajax(userdata), so you got "undefined index category" - this error
Related
I'm just starting with JS and like to implement a form that verifies for robots/humans by using captcha v3 on the client side and if verification succeeds the data should be submitted to another file.
This is what I got so far. I know it's wrong, but unsure what the correct logic is. Hope someone can shed a light. Thx!
<script src="https://www.google.com/recaptcha/api.js?render=6Lc3UZkeAAAAAMt6wcA-bYjLenFZPGv3K5AqfvuQ"></script>
<script type="text/javascript" src="/js/libs/jquery-1.11.3.min.js"></script>
<section class="cc-column-component regular-grid">
<form id="bank-form" class="form clear one-full cf-contact-form" action="?" method="POST" data-tracking="contact_sales">
<div>
<label class="label mandatory bank-color bank-label" for="firstName">First Name</label>
<input id="firstName" value="Pepe" type="text" class="one-full bank-color-grey bank-input" name="firstName" placeholder="First Name" autocomplete="off" data-validate="true" data-type="text" data-min="3" value="<?php isset($this) ? print $this->getFirstName() : print ''; ?>">
<br/>
<label class="label mandatory bank-color bank-label" for="lastName">Last Name</label>
<input id="lastName" value="Chanches" type="text" class="one-full bank-color-grey bank-input" name="lastName" placeholder="Last Name" autocomplete="off" data-validate="true" data-type="text" data-min="3" value="<?php isset($this) ? print $this->getLastName() : print ''; ?>">
<br/>
<label class="label mandatory bank-color bank-label" for="email">Email</label>
<input value="asdf#asdf.com" id="email" type="text" class="one-full bank-color-grey bank-input" name="email" placeholder="Email" autocomplete="off" data-validate="true" data-type="email" value="<?php isset($this) ? print $this->getEmail() : print ''; ?>">
<br/>
</div>
<div class="row inline one-full">
<br/>
<!-- <div class="g-recatpcha" data-sitekey="6Lc3UZkeAAAAAMt6wcA-bYjLenFZPGv3K5AqfvuQ"></div> -->
<button type="submit"
id="form-submit"
value="submit"
>
<a>Submit form</a>
</button>
<div class="field inline one-full">
<br/>
</div>
<!-- <input type="hidden" name="recaptcha_response" id="recaptchaResponse"> -->
</div>
</form>
</section>
<script>
$('#bank-form').submit(function(event) {
console.log('subtmitting');
event.preventDefault();
grecaptcha.ready(function() {
grecaptcha.execute('6Lc3UZkeAAAAAMt6wcA-bYjLenFZPGv3K5AqfvuQ', {action: 'submit'}).then(function(token) {
console.log('🚀 ~ grecaptcha.execute ~ token', token)
$('#bank-form').prepend('<input type="hidden" name="token" value="' + token + '">');
$('#bank-form').prepend('<input type="hidden" name="action" value="submit">');
// $('#bank-form').unbind('submit').submit();
});;
});
CheckCaptcha(token)
});
function CheckCaptcha(token) {
var token = $("#token").val()
console.log('🚀 ~ token', token)
var action = $("#action").val()
var RECAPTCHA_V3_SECRET_KEY = "6Lc3UZkeAAAAAIG8bVZDpkheOxM56AiMnIKYRd6z"
$.ajax({
type: "POST",
url: "http://www.google.com/recaptcha/api/siteverify",
data: JSON.stringify([{secret: RECAPTCHA_V3_SECRET_KEY }, {response : token }]),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
// __doPostBack('form-submit', '');
if(response["score"] >= 0.7) {
console.log('Passed the token successfully');
}
},
failure: function (response) {
// set error message and redirect back to form?
console.log('Robot submit', response);
}
})
return false;
}
</script>
I have built a form in HTML and send all the data entered by the user using JSON.stringify() and XMLHttpRequest() to a PHP file and stored that in a variable. Now I want to display all that information on a web page, for which I want to use for-each loop, but i am not understanding how exactly should i pass the parameters in the loop and access them.
Here is the HTML code:-
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="styling.css">
</head>
<body>
<div class="container">
<h1>Popup for adding/editing Expertise details</h1>
Add/Edit
</div>
<div class="popup">
<div class="popup-content">
<div class = "register">
<form method="post" id="register" action="">
<label for="area"> Expertise Area: </label><br>
<input type="text" name="area" id="area"
placeholder="Enter your Expertise Area"><br><br>
<label> Experience: </label><br>
<label for="mnth">No. of months:</label>
<input type="number" id="mnth" name="mnth" min="1" max="11">
<label for="yr">No. of years:</label>
<input type="number" id="yr" name="yr" min="1" max="50"><br><br>
<label> Rates </label><br><br>
<label for="remote"> Remote: </label><br>
<select id="remote_option">
<option>per hour</option>
<option>per topic</option>
<option>per chapter</option>
</select>
<label for="remote_amt">Amount in Rs.:</label>
<input type="number" id="remote_amt" name="remote_amt">
<label for="center"> Center: </label><br>
<select id="center_option">
<option>per week</option>option>
<option>per month</option>option>
</select>
<label for="center_amt">Amount in Rs.:</label>
<input type="number" id="center_amt" name="center_amt">
<label for="learner"> Learner's Place: </label><br>
<select id="learner_option">
<option>per class</option>option>
<option>per hour</option>option>
</select>
<label for="learner_amt">Amount in Rs.:</label>
<input type="number" id="learner_amt" name="learner_amt"><br>
<label for="my"> My Place: </label><br>
<select id="my_option">
<option>per class</option>option>
<option>per hour</option>option>
</select>
<label for="my_amt">Amount in Rs.:</label>
<input type="number" id="my_amt" name="my_amt"><br><br>
<div class="button">
<button id="btn">Submit</button>
</div>
<img src="close.png" class="close" alt="Close">
</form>
</div>
</div>
</div>
<script>
document.querySelector(".button").addEventListener("click", function(){
document.querySelector(".popup").style.display = "flex";});
document.querySelector(".close").addEventListener("click", function(){
document.querySelector(".popup").style.display="none";});
</script>
<script>
let data=[];
const addData=(ev)=>{
ev.preventDefault();
let d={
exp_area: document.getElementById('area').value,
exp_yrs: document.getElementById('mnth').value,
exp_mnth: document.getElementById('yr').value,
rates: [
{
mode: 'remote',
charge: document.getElementById('remote_amt').value,
unit: document.getElementById('remote_option').value
},
{
mode: 'center',
charge: document.getElementById('center_amt').value,
unit: document.getElementById('center_option').value
},
{
mode: 'learner',
charge: document.getElementById('learner_amt').value,
unit: document.getElementById('learner_option').value
},
{
mode: 'my',
charge: document.getElementById('my_amt').value,
unit: document.getElementById('my_option').value
}
]
}
data.push(d);
document.forms[0].reset();
const JsonString = JSON.stringify(data);
console.log(JsonString);
const xhr = new XMLHttpRequest();
xhr.open("POST","receive.php");
xhr.setRequestHeader("Content-Type","application/json");
xhr.send(JsonString);
}
document.addEventListener('DOMContentLoaded',()=>{
document.getElementById('btn').addEventListener('click',addData);
});
</script>
<script type="text/javascript" src="submit.js"></script>
</body>
</html>
And here is the JSON object which is sent as Request PayLoad, as I can see in the network tab in developers tool:-
[{"exp_area":"gfds","exp_yrs":"","exp_mnth":"","rates":[{"mode":"remote","charge":"","unit":"per hour"},{"mode":"center","charge":"","unit":"per week"},{"mode":"learner","charge":"","unit":"per class"},{"mode":"my","charge":"","unit":"per class"}]}]
this is what i am trying in my PHP file :-
<?php
$reuestPayload = file_get_contents("php://input");
$arr = json_decode($reuestPayload,true);
var_dump($arr);
$output= "<ul>";
foreach ($arr[d] as $value) {
$output .= "<h4>".$d['exp_area']."</h4>";
$output .= "<h4>".$d['exp_yrs']."</h4>";
$output .= "<h4>".$d['exp_mnth']."</h4>";
$output .= "<h4>".$d['rates']['mode']."</h4>";
$output .= "<h4>".$d['rates']['charge']."</h4>";
$output .= "<h4>".$d['rates']['unit']."</h4>";
}
$output.="</div>";
?>
Request payload:
As the data is being sent and received asynchronously the page will not be refreshed after an execution of the submit routine. What you might do is return HTML from your backend and add this to a specific element as part of the XHR response.
Add a result element to show the server response:
<div id="result"><h3>Result:</h3></div>
Modify your JS routine:
Add this before your xhr.open() lines:
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
document.getElementById('result').innerHTML += (xhr.responseText);
}
}
Some remarks regarding your code:
You start your PHP response with $output= "<ul>"; but end with $output.="</div>"; -> change the <ul> to <div>.
As pointed out by aXuser26 your server-side code is errornous, the [d] should be removed. I think you got confused as you labelled your JSON variable "d" on the client-side but the variable name won't be passed to the server.
There is a "q" missing in your variable $reuestPayload (although this won't be a problem^^).
I have a from with button to submit it. Now i would like to pass same variables to another page to inset them in database. For that, i would like to pass the variables using an anchor link with GET with id's.
But how do it add an anchor link to the form where when i submit the form using the button the anchor link also gets triggered..
function splitAndResolve() {
var errorIds = [];
$('[name="error-selection-checkboxes"]:checked').each(function() {
errorIds.push($(this).val().split("-")[1]);
});
var taskVersion = 1;
if (errorIds.length > 0 && errorIds.length < $('[name="error-selection-checkboxes"]').length) {
var dataObj = {
'errorReportIdsToRemove': errorIds,
'user': 'user#mail.com'
};
var baseUrl = $(location).attr("href").substring(0, $(location).attr("href").lastIndexOf('/') + 1);
var splitTaskResponse = $.ajax({
url: "/task/3f2456c6b44c3b29c651f8d55c1bb34ac4da11bb6d605a00629e79f2a95c4a70/split",
type: "POST",
data: dataObj,
async: false,
error: function(xhr, status) {
if (xhr.status == 400) {
window.location.href = "/400";
alert("Failed resolving the task, please retry upon reload.");
} else {
window.location.href = "/500";
alert("Failed resolving the task, please retry upon reload.");
}
}
}).responseJSON;
var taskId = splitTaskResponse.newTaskId;
// We need to update the version without which version on the UI and the DB are different.
taskVersion = splitTaskResponse.currentTaskPostSplit.version;
window.open(baseUrl + taskId, '_blank');
}
dataObj = {
'taskResolutionStatus': $("#inputResolution").val(),
'taskResolutionStatusDetail': $("#inputResolutionDetail").val(),
'taskResolutionNote': $("#inputNotes").val(),
'changeset': $("#inputChangeset").val(),
'requiresReview': $("#requiresReviewCheckBox").is(':checked'),
'version': taskVersion
};
$.ajax({
url: "/task/3f2456c6b44c3b29c651f8d55c1bb34ac4da11bb6d605a00629e79f2a95c4a70",
type: "POST",
data: dataObj,
async: false,
error: function(xhr, status) {
if (xhr.status == 400) {
window.location.href = "/400";
alert("Failed resolving the task, please retry upon reload.");
} else {
window.location.href = "/500";
alert("Failed resolving the task, please retry upon reload.");
}
}
});
enableStatusDropdown();
return true;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="form-horizontal clearfix" onsubmit="return splitAndResolve()">
<div class="form-group">
<label for="changeset" class="col-sm-2 control-label">Changeset</label>
<div class="col-sm-10">
<input class="form-control" type="text" name="changeset" id="inputChangeset" readonly="">
</div>
</div>
<div class="form-group">
<label for="taskResolutionStatus" class="col-sm-2 control-label">Resolution</label>
<div class="col-sm-10">
<select class="form-control resolutionDropdown" name="taskResolutionStatus" id="inputResolution">
<option disabled="" selected="" value=""> -- Choose one -- </option>
<option value="ESCALATE">Escalate</option>
<option value="ALREADY_FIXED_IN_OSM">Already fixed in osm</option>
<option value="NOT_ENOUGH_INFORMATION">Not enough information</option>
<option value="NO_FIX_REQUIRED">No fix required</option>
<option value="FIXED">Fixed</option>
</select>
</div>
</div>
<div class="form-group" id="inputResolutionDetailDropdown">
<label for="taskResolutionStatusDetail" class="col-sm-2 control-label">Detail</label>
<div class="col-sm-10">
<select class="form-control resolutionDropdown" name="taskResolutionStatusDetail" id="inputResolutionDetail">
<option value="LOW_PRIORITY_AREA">Low priority area</option>
<option value="KNOWN_BUG">Known bug</option>
<option value="ERROR_BASED_ON_BAD_DATA">Error based on bad data</option>
<option value="TRUE_EXCEPTION">True exception</option>
</select>
</div>
</div>
<div class="form-group">
<label for="taskResolutionNote" class="col-sm-2 control-label">Notes</label>
<div class="col-sm-10">
<textarea class="form-control" name="taskResolutionNote" id="inputNotes" rows="3"></textarea>
</div>
</div>
<div class="form-group">
<label for="requiresReview" class="col-sm-2 control-label">Requires review</label>
<div class="col-sm-2">
<input class="form-control" name="requiresReview" type="checkbox" style="box-shadow: none" id="requiresReviewCheckBox">
</div>
</div>
<input id="taskResolutionButton" type="submit" class="btn btn-primary">
<button id="taskCancelButton" type="button" class="btn btn-default" onclick="hideResolutionOverlay()">Cancel</button>
</form>
<input id="taskResolutionButton" type="submit" class="btn btn-primary" onclick="$('#your_form_id').submit();>
So upon examining the development console, i can see that my AJAX has succeeded, and I have recieved the JSON data I need, However I can't put my finger on how to display it correctly as I keep getting the following error:
Uncaught TypeError: Cannot read property 'name' of undefined
at Object.success (main.js:11)
at Object.resolveWith (jquery.min.js:16)
at v (jquery.min.js:16)
at XMLHttpRequest.c (jquery.min.js:16)
AJAX output:
Object {rows: Object, response: true}
response:true
rows:Object
address:"testestset"
classid:"2"
dob:"1993-04-27"
email:"tests"
gender:"M"
id:"5"
name:"Second Birthday Test"
parent:"Testerr"
phone:"07123456789"
status:"1"
Main.js:
function getGymnasts(val){
$.ajax({
type:"POST",
url:"ajax_populate_gymnasts.php",
data: 'gymnast='+val,
success: function(response){
var result = JSON.parse(response);
if (result.response == true) {
//console.log(result);
var data = result.rows;
console.log(data);
$("#dob").val(data['rows'].dob);
$("#gender").val(data['rows'].gender);
$("#parent").val(data['rows'].parent);
$("#email").val(data['rows'].email);
$("#phone").val(data['rows'].phone);
$("#address").val(data['rows'].address);
$("#status").val(data['rows'].status);
}else if (result.response == false) {
$('#gymnast').append('<option>No Gymnasts were found!</option>');
}
}
});
}
function populateReports(val){
$.ajax({
type:"POST",
url:"ajax_populate.php",
data: 'classid='+val,
success: function(data){
$("#gymnast").html(data);
}
});
}
ajax_populate_gymnasts.php
<?php
require('../includes/dbconnect.php');
$gymnastid = $_POST['gymnast'];
$sql = "SELECT * FROM gymnasts WHERE id='$gymnastid'";
$result = mysqli_query($GLOBALS['link'], $sql);
if (mysqli_num_rows($result) > 0) {
$data = mysqli_fetch_assoc($result);
echo json_encode(['rows' => $data, 'response' => true]);
} else {
echo json_encode(['response' => false]);
}
mysqli_close($GLOBALS['link']);
exit();
?>
editGymnasts.php:
<?php require('adminheader.php');
?>
<h1>Edit Gymnast</h1>
<form method="post">
<label for="gymnast">Gymnast:</label>
<select id="gymnast" name="gymnast" onChange="getGymnasts(this.value)" required/>
<option value="0">None yet</option>
<?php
$gymnasts = mysqli_query($GLOBALS['link'], "SELECT * FROM gymnasts;");
foreach($gymnasts as $gymnast){
echo("<option value=".$gymnast['id'].">".$gymnast['name']."</option>");
}
?>
</select><br>
<label for="dob">Date of Birth:</label>
<input type="date" id="dob" name="dob" required/>
<label for="gender">Gender:</label>
<select id="gender" name="gender" required />
<option value="F">Female</option>
<option value="M">Male</option>
</select><br>
<label for="parent">Parent's Name:</label>
<input type="text" id="parent" value="derp" name="parent" required /> <br>
<label for="email">Contact Email:</label>
<input type="text" id="email" name="email" required /> <br>
<label for="phone">Contact Phone:</label>
<input type="text" id="phone" name="phone" required /> <br>
<label for="parent">Contact Addres:</label>
<textarea id="address" name="address" required /></textarea><br>
<select id="status" name="status" required />
<option value="0"></option>
<input type="submit" id="saveChanges" name="saveChanges" />
</form>
So it turns out i was unnecessarily entering an undefined nested array.
$("#dob").val(data['rows'].dob);
Should have been
$("#dob").val(data.dob);
This question already has answers here:
How do I POST urlencoded form data with $http without jQuery?
(11 answers)
Closed 6 years ago.
I'm trying to submit the form below to a php file called time.php, but its not working, even when I check the console there are no errors, its just clear. I'm not sure where I may be going wrong.
<form ng-controller="testCtrl" class="customform" data-ng-init="init()">
<div class="s-10 1-10">
<input ng-model="firstName" pattern=".{2,100}" title="2 to 100 Characters" placeholder="First Name" type="text" required />
</div>
<div class="s-10 1-10">
<input ng-model="lastName" pattern=".{5,255}" title="5 to 255 Characters" placeholder="Last Name" type="text" required />
</div>
<div class="s-12 l-10"><input ng-model="acNumber" placeholder="A/C Number" title="Employee Number, i.e c1234567" type="text" required /></div>
<div class="s-12 l-10"><input ng-model="email" placeholder="Email" title="Email" type="email" required /></div>
<div class="s-12 l-10">
<select ng-model="selectedRequestType" ng-options="requestType as requestType.type for requestType in requestTypes" required="required">
<option value="" disabled selected>Request Type</option>
</select>
</div>
<div class="s-12 l-10">
<select ng-show="selectedRequestType.type == 'Work Request'" ng-model="selectedWorkRequestType" ng-options="workRequestType as workRequestType.type for workRequestType in workRequestTypes">
<option value="" disabled selected>Work Request Type</option>
</select>
</div>
<div class="s-12 l-10">
<select ng-show="selectedWorkRequestType.type == 'New file(s) from source'" ng-model="selectedFile" ng-options="file as file.type for file in files">
<option value="" disabled selected>Files</option>
</select>
</div>
<div class="s-12 l-10">
<select ng-show="selectedWorkRequestType.type == 'New file(s) from source'" ng-model="selectedLibrary" ng-options="library as library.type for library in libraries">
<option value="" disabled selected>Does Library Exist</option>
</select>
</div>
<div class="s-12 l-10">
<select ng-show="selectedWorkRequestType.type == 'Code Automation' || selectedWorkRequestType.type == 'Amendments to existing code'" ng-model="selectedOutput" ng-options="outputType as outputType.type for outputType in outputTypes">
<option value="" disabled selected>Output</option>
</select>
</div>
<div class="s-12 l-10">
<select ng-show="selectedLibrary.type == 'Yes' || selectedRequestType.type == 'Incident'" ng-model="selectedPlatformOutput" ng-options="platformOutput as platformOutput.type for platformOutput in platformOutputs">
<option value="" disabled selected>Platform Output</option>
</select>
</div>
<div class="s-12 l-10">
<input ng-show="selectedOutput.type == 'SAS' || selectedPlatformOutput.type =='SAS'" ng-model="sasLibraryName" type="text" placeholder="SAS Library Name: SPDS Exploit" />
</div>
<div class="s-12 l-10">
<input ng-show="selectedOutput.type == 'SAP IQ' || selectedPlatformOutput.type =='SAP IQ'" ng-model="sapIQtext" placeholder="SAP IQ" >
</div>
<div class="s-12 l-10">
<input ng-show="selectedOutput.type == 'Hadoop' || selectedPlatformOutput.type =='Hadoop'" placeholder="Library Name: HDFS_Exploit" ng-model="hadoop" />
</div>
<div class="s-12 l-10">
<input ng-show="selectedWorkRequestType.type == 'Amendments to existing code'" placeholder="Output Dataset Name" ng-model="outputDataset" type="text"/>
</div>
<div class="s-12 l-10">
<input ng-show="selectedLibrary.type == 'No'" type="text" ng-model="productName" Placeholder="Product Name" />
</div>
<div class="s-12 l-10">
<input ng-show="" placeholder="Upload Text File" type="file" ng-model="uploadTextFile" title="Please upload a txt file with the layout - to " multiple />
</div>
<div class="s-12 l-10">
<input ng-show="selectedRequestType.type == 'Incident'" type="text" ng-model="tableName" placeholder="Dataset/Table Name" />
</div>
<div class="s-12 l-10">
<textarea placeholder="Special Instructions" ng-model="specialInstruction" rows="5"></textarea>
</div>
<div class="s-12 l-10">
<input ng-show="selectedRequestType.type == 'Incident'" ng-model="uploadScreenshot" placeholder="Upload Screenshot of error" type="file" multiple/>
</div>
<div class="s-12 l-10">
<select ng-show="selectedRequestType.type == 'Work Request'" ng-model="selectedFrequency" ng-options ="frequency as frequency.type for frequency in frequencies">
<option value="" disabled selected>Frequency</option>
</select>
</div>
<div class="s-12 l-10">
<select ng-show="selectedFrequency.type == 'Weekly'" ng-model="selectedWeekly" ng-options ="weekly as weekly.type for weekly in weeklies">
<option value="" disabled selected>Weekly Frequency</option>
</select>
</div>
<input type="hidden" ng-model="token" value="<?php echo Token::generate()?>">
<div class="s-4"><button type="submit" id="submit" class="btn-custom btn btn-large btn-block" ng-click="sendRequest()">Request</button></div>
Please note: ng-app="app" is located in the header:
<!DOCTYPE html>
<html lang="en-US" ng-app="app">
The following code is the controller, and I believe the issue lies somewhere in here:
var app = angular.module('app', []);
app.controller('testCtrl', ['$scope', '$http', function($scope, $http) {
$scope.sendRequest = function(){
var data= {
'firstName' :$scope.firstName,
'lastName' :$scope.lastName,
'acNumber' :$scope.acNumber,
'email' :$scope.email,
'selectedRequestType' :$scope.selectedRequestType,
'selectedWorkRequestType' :$scope.selectedWorkRequestType,
'selectedOutput' :$scope.selectedOutput,
'selectedFrequency' : $scope.selectedFrequency,
'selectedWeekly' : $scope.selectedWeekly,
'selectedFile' : $scope.selectedFile,
'selectedLibrary' : $scope.selectedLibrary,
'selectedPlatformOutput' : $scope.selectedPlatformOutput,
'productName' : $scope.productName
};
$http({
url: "time.php",
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: data
}).success(function(data, status, headers, config) {
//Success code
}).error(function(xhr) {
//Failure code
console.log(data);
console.log(xhr.responseText);
});
return false;
// $window.location.href ='/time.php';
};
$scope.init = function (){
$scope.workRequestType = 'test';
$scope.requestTypes = [
{'type':'Work Request'},
{'type': 'Incident'}
];
$scope.workRequestTypes = [
{'type': 'Amendments to existing code'},
{'type': 'Code Automation'},
{'type': 'New file(s) from source'}
];
$scope.outputTypes = [
{'type': 'SAS'},
{'type':'SAP IQ'},
{'type': 'Hadoop'}
];
$scope.frequencies = [
{'type' : 'Daily'},
{'type': 'Monthly'},
{'type': 'Weekly'}
];
$scope.weeklies = [
{'type': 'Monday'},
{'type':'Tuesday'},
{'type': 'Wednesday'},
{'type':'Thursday'},
{'type':'Friday'},
{'type':'Saturday'},
{'type':'Sunday'}
];
$scope.files = [
{'type': 'New File(s)'},
{'type': 'Add to existing file received'}
];
$scope.libraries = [
{'type':'Yes'},
{'type':'No'}
];
$scope.platformOutputs = [
{'type': 'SAS'},
{'type':'SAP IQ'},
{'type': 'Hadoop'}
];
$scope.firstName= null;
$scope.lastName= null;
$scope.acNumber= null;
$scope.email= null;
$scope.selectedRequestType= null;
$scope.selectedWorkRequestType= null;
$scope.selectedOutput= null;
$scope.sasLibraryName = null;
$scope.sasIQtext = null;
$scope.selectedFrequency = null;
$scope.selectedWeekly = null;
$scope.selectedFile = null;
$scope.selectedLibrary = null;
$scope.selectedPlatformOutput = null;
$scope.productName = null;
};
}]);
I'm still learning Angular, so I may have made a simple error
If the HTTP POST request is taking place, but PHP is not able to access the POST variables, try converting the data from an object to a string.
$http({
url: "time.php",
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $httpParamSerializerJQLike(data),
})
The string should look like: firstName=John&acNumber=1234
Pass the $httpParamSerializerJQLike service into your controller with:
app.controller('testCtrl', ['$scope', '$http', '$httpParamSerializerJQLike', function($scope, $http, $httpParamSerializerJQLike) {