Get input field through javascript and use variable in php? - javascript

The question says it all.
Any ideas?

HTML
<input type="text" name="username" class="form-control search-query" placeholder="Enter User Name">
JavaScript
$http({
method: 'POST',
url: 'url.php',
//headers : {'Content-Type':'application/x-www-form-urlencoded'},
data: {
"username": $scope.username,
},
}).then(function (response) {
var data = response.data;
}
PHP
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$accountnumber = $request->accountnumber;

It's not $post_"username". You should use $_POST["username"]; to get post parameters from the sever php script.

Related

PHP file not called via AJAX

Below is my code for the problem. I am trying to call php file via AJAX.
I have an HTML file where after form submission, the AJAX calls the PHP file.
Unfortunately, I cannot see any output.
HTML File(Body):
<form>
<label for="">Username</label>
<input type="text" name="username" value="">
<br><br>
<label for="">Password</label>
<input type="text" name="password" value="">
<br>
<button name="button" id="button" value="Submit">Submit</button>
</form>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script src="login.js"></script>
My login.js file(for AJAX):
$("#button").click(function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url: 'login.php'
});
});
My PHP file:
<?php
// Server credentials
$serverName = "localhost";
$username = "root";
$password = "root";
$dbName = "Blog";
//Creating connection
$db = mysqli_connect($serverName,$username,$password,$dbName);
if(!$db){
echo "error";
die($db);
}
else{
echo "er22ror";
}
mysqli_close($db);
?>
Your AJAX call doesn't do anything with the result:
$.ajax({
type: 'POST',
url: 'login.php'
});
In order to see output, you have to output something. Use a callback for that. For example, you can log the result to the console:
$.ajax({
type: 'POST',
url: 'login.php'
}).done(function (result) {
console.log(result);
});
$.ajax({
type: 'POST',
url: 'login.php',
success: function (res) {
alert('hi'+res);
}
});
used above. you can also show in console window

Form ajax post data to php file [duplicate]

This question already has answers here:
jQuery Ajax POST example with PHP
(17 answers)
Closed 5 years ago.
Hi i trying make form using ajax. But i get some problems to sending form vars to php file. I get error: Undefined index: name.
I check chrome dev tools and i see variable is sending. But when made echo json_encode i see in php file i get empty array. So i dont have any idea where i made misstake.
file Main.js
var name = $('#user_name').val();
var lname = $('#user_lastname').val();
function formLogin(name, lname)
{
$.ajax({ url: 'database/register.php',
data: {
'name' : name,
'lname' : lname
},
type: 'post',
dataType:'json',
success: function(data) {
alert(data);
}
});
}
Html form:
<form class="circleForm" id="registerForm">
Imię: <input type="text" id="user_name"><br>
Nazwisko: <input type="text" id="user_lastname">
<br>
<input class="btnCircle" type="button" id="submit" value="Przejdź dalej" onclick="formLogin(name, lname)">
</form>
Php Code:
$dane = $_POST;
echo json_encode($dane);
Chrome dev:
I just want figure how can i echo this variables(name,lname) in php file register.php
Version with serialize:
function formLogin() {
var dane = $('form').serialize();
$.ajax({
url: 'database/register.php',
data: {'dane': dane},
method: 'post',
success: function(data) {
console.log(data);
}
});
}
Then result console:
<pre class='xdebug-var-dump' dir='ltr'>
<small>D:\xampp\htdocs\szkola\database\register.php:8:</small>
<b>array</b> <i>(size=1)</i>
'dane' <font color='#888a85'>=></font> <small>string</small> <font color='#cc0000'>''</font> <i>(length=0)</i>
</pre>
jquery-3.2.1.min.js:4 XHR finished loading: POST "http://localhost/szkola/database/register.php".
But when i go to http://localhost/szkola/database/register.php
i get this:
D:\xampp\htdocs\szkola\database\register.php:8:
array (size=0)
empty
You need to change the way you define your variables in your Javascript and declare them inside your function, not outside :
function formLogin(){
var name = $('#user_name').val();
var lname = $('#user_lastname').val();
$.ajax({ url: 'database/register.php',
data: {
'name' : name,
'lname' : lname
},
type: 'post',
dataType:'json',
success: function(data) {
alert(data);
}
});
}
And you need to update your HTML the same way (formLogin() instead of formLogin(...,...)) :
<form class="circleForm" id="registerForm">
Imię: <input type="text" id="user_name"><br>
Nazwisko: <input type="text" id="user_lastname">
<br>
<input class="btnCircle" type="button" id="submit" value="Przejdź dalej" onclick="formLogin()">
</form>
Try using method instead of type.
The HTML:
<form class="circleForm" id="registerForm">
Imię: <input type="text" id="user_name" name="name"><br />
Nazwisko: <input type="text" id="user_lastname" name="lname"><br />
<input class="btnCircle" type="button" id="submit" value="Przejdź dalej" onclick="formLogin();">
</form>
The JavaScript:
function formLogin() {
// Serialize the form
var data = $('form').serialize();
// Ajax call
$.ajax({
url: 'database/register.php',
data: data,
method: 'post',
dataType: 'json',
success: function(data) {
console.log(data);
}
});
}
Also remember that you're requesting a JSON so you have to echo a json_encode($array) in your PHP file for a simple string will not be returned.

Input field should not clear after submit using angularjs

HTML
<form ng-controller="updatecontroller" ng-submit="updateUser()"><label class="control-label">First Name</label>
<input type="text" ng-model="user.userFirstName">
<label class="control-label">Last Name</label>
<input type="text" ng-model="user.userLastName" ><button type="submit" ng-click="updateUser()">Update</button>
</form>
JS
app.controller('updatecontroller', function ($scope, $http, $cookieStore) {
$http.get('http://localhost:8080/myapp/user/'.concat($scope.getUserId) + '?access_token=' + $cookieStore.get("access_token")).
then(function (response) {
$scope.user = response.data;
});$scope.user = {"id": "","userFirstName": "","userLastName": ""}
$scope.updateUser = function () {
var url = "http://localhost:8080/myapp/user/".concat($scope.getUserId) + "?access_token=" + $cookieStore.get("access_token");
var method = "PUT";
$http({
method: method,
url: url,
data: angular.toJson($scope.user),
headers: {
'Content-Type': 'application/json'
}
})
};});
values will appear in text field. i have to update. the values are getting updated in database. but what i want is.. the updated values should not clear after submit the form.
Thanks!
You can empty the input filed after get the response from HTTP request
$scope.updateUser = function () {
$http({
method: 'POST',
url: 'myUri',
data: 'your data'
headers:'header'
}).then(
function(res) {
$scope.user = {"id": "","userFirstName": "","userLastName": ""} //clear the input field here
},
function(err) {
}
);
}
Place your Submit Button inside the Form Element then try it it will clear the input after the submission.
your updateUser() method seems to be the problem. It's probably clearing user.userFirstName & user.userLastName (or the whole user)
please show us what updateUser() is doing to be sure

AngularJS Does not send HTTP Post request

I have following code:
application.controller('userLoginController', function($scope,$http){
window.document.title = "User Login";
$scope.form = { username: '',password: ''};
$scope.submitLogin = function(){
var config = {
method: 'POST',
url: 'server_app/login.php',
data: {
'username' : $scope.form.password,
'password' : $scope.form.password
}
};
var request = $http(config);
request.then(function (response){
$scope.errorMessage = response.data;
},function(error){
$scope.errorMessage = error.data;
})
}
});
I was trying to send POST request to backend server which look like that:
var_dump($_POST);
After submitting my data with a button I should get array with $_POST back.
Insteed of that I get
array (size=0)
empty
My HTML code look like that:
<input placeholder="Login" class="searchProduct" autocomplete="off" name="username" type="text" ng-model="form.username"><br>
<input placeholder="Password" class="searchProduct" autocomplete="off" type="password" name="password" ng-model="form.password"/>
<div class="button" ng-click="submitLogin();">Login</div>
I don't see any problem here..
I hope you are receiving data as below in php file as angular code seems to be fine .
$params = json_decode(file_get_contents('php://input'),true);
You can use the below code
$http.get('/someUrl', config).then(successCallback, errorCallback);
$http.post('/someUrl', data, config).then(successCallback, errorCallback);

Form not submitting "Submit" input via Ajax

Issue
I have a form constructed using Bootstrap 3.
I post the data via Ajax to a PHP page "formhandle.php", which is used to handle all forms on the site.
However, the submit input information is not being sent.
HTML Form
<form role="form" id="frmLogin" action="dashboard/inc/formhandle.php">
<p class="text-danger frmLogin_error" style="display:none;">Invalid username/password combination</p>
<div class="form-group">
<label for="frmLogin_username">Username/domain</label>
<input id="frmLogin_username" name="username" type="text" class="form-control" placeholder="example.com">
</div>
<div class="form-group">
<label for="frmLogin_password">Password</label>
<input id="frmLogin_password" name="password" type="password" class="form-control" placeholder="Password">
</div>
<input type="submit" name="frmLogin_submit" value="Login" class="btn btn-default" />
</form>
jQuery/Ajax Submission
$('form').submit( function(e) {
var formName = $(this).attr('id');
$('#'+formName).find('.'+formName+'_error').hide();
$(this).find('input[type=submit]').prop('disabled',true);
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax({
url : formURL,
type: "POST",
//async: false,
data : new FormData(this),
success:function(data, textStatus, jqXHR) {
console.log(data);
if(data=='success'){
console.log('success');
} else {
$('#'+formName).find('.'+formName+'_error').show();
}
$('#'+formName).find('input[type=submit]').prop('disabled',false);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Error: An unknown error occurred.');
},
cache: false,
contentType: false,
processData: false
});
e.preventDefault();
});
PHP Code
require_once('connect.php');
require_once('functions.php');
exit(print_r($_POST));
if(isset($_POST['frmLogin_submit'])){
$username = $_POST['username'];
$password = $_POST['password'];
$stmt = $dbh->prepare('SELECT * FROM `users`
WHERE (`username`=? AND `password`=?)
OR (`email`=? AND `password`=?');
if($stmt->execute(array($_POST['username'],$_POST['password'],$_POST['username'],$_POST['password']))){
if($stmt->rowCount()>1) exit('error: invalid data');
$userData = $stmt->fetch(PDO::FETCH_ASSOC);
validateUser($userData['id']);
exit('success');
}
}
Console Output
Array
(
[username] => username_input
[password] => password_input
)
1
What Console Output I Expect
Array
(
[username] => username_input
[password] => password_input
[frmLogin_submit] => Login
)
1
Why isn't the frmLogin_submit input value being posted?
Because you have disabled the input[type="submit"]
From your code:
$(this).find('input[type=submit]').prop('disabled',true);
Disabled inputs,textareas are not submitted with the form.
Suggestion:
Set readonly to the input, if you don't want the user to interact with the button.
$(this).find('input[type=submit]').prop('readonly',true);
it is like a billion years from the time this question was share but hope this helps someone.
i had same problem, and this is the solution i used:
$.ajax({
type: "POST",
url: url,
data: form.serialize()+"&submit="+document.activeElement.value,
don't know how risky this might be, but all things being equal, this seems to be a quick fix to the problem.
Edited:
Someone contacted me to complain that this code was not working.
After I reviewed his code, I saw that he had used a different name for the submit input which was not "submit", So I'm here to review my answer to make it more dynamic.
$.ajax({
type: "POST",
url: url,
data: form.serialize()+"&"+document.activeElement.name+"="+document.activeElement.value,

Categories