Angular post request to php failed - javascript

I have a simple form with two fields.
<form name="save" ng-submit="sap.saved(save.$valid)" novalidate>
<div class="form-group" >
<input type="text" name="name" id="name" ng-model="sap.name" />
</div>
<div class="form-group" >
<input type="email" name="email" id="email" ng-model="sap.email" />
</div>
<div class="form-actions">
<button type="submit" ng-disabled="save.$invalid || sap.dataLoading">Save</button>
</div>
</form>
I'm trying to post these values to a php page using POST request.
$http({
method: 'post',
url: 'save.php',
data: $scope.vm,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data, status, headers, config)
{
if(data.success)
{
alert('valid');
}
else
{
alert('invalid 1');
}
}).
error(function(data, status, headers, config)
{
alert('invalid 2');
});
And in save.php file, I'm fetching the values like this:
$name=$_POST['name'];
$email=$_POST['email'];
But response I get is undefned variable name. That's a PHP notice. But when I try to POST these values from POSTman client, it works.
Is there anything wrong with the method I choose to POST data?
P.S: i didn't post entire controller. Just http request part is included here.

I faced same situation where $_POST() did't worked out!
trying to fetch raw data with:
json_decode(file_get_contents('php://input'))
might be helpful.
Update:
This Answer explains why $_POST variable is not populated in php
when data is posted with angular!

Related

How to Post Registration Form with File to ASP.NET MVC Action

I'm unclear as to why I'm unable to POST the data in my form to the server. It appears as though the form is defaulting to a 'GET' request although I've hardcoded both the form and the AJAX call to use a 'POST' request. So, I'm out of ideas. Any suggestions are very much appreciated.
The UI looks like this:
This is my Javascript code:
SubmitRegisterForm: function (e) {
var scope = this;
e.preventDefault();
//var formData = new FormData();
//formData.append('profilepic', $('#profilepic')[0].files[0]);
var data = {
FirstName: $('#FirstName').val(),
LastName: $('#LastName').val(),
Email: $('#Email').val(),
Password: $('#Password').val(),
ConfirmPassword: $('#ConfirmPassword').val(),
StripeConnectedAcctId: scope.stripeConnectedAccountId
};
console.log(data);
$.ajax({
url: '/Account/Register',
method: 'POST',
data: { model: data, profilepic: $('#profilepic')[0].files[0] },
enctype: 'multipart/form-data'
}).done(function (resp) {
});
}
Server-side code looks like this, but isn't currently being hit (that would be the problem bub):
Also, I'm seeing these errors on the Chrome Dev tools Console:
Funny enough, the Javascript code executes fine, displaying the data variable just fine, but complains about some Illegal Invocation in Vue... which literally makes no sense as I don't even use any Vue related functions but rather issue an AJAX call.
What on God's green Earth gives???? >=/
I'm hoping I'll wake up to this with a solution in my inbox like it's Christmas!
You are using ASP .NET so if you are using server side rendering I would do something like this and let the framework handle everything.
<form enctype="multipart/form-data" asp-action="controllorAction" method="post">
<label class="form-label" for="firstName">First Name</label><input type="text" asp-for="Model.FirstName" />
<label class="form-label" for="lastName">Last Name</label><input type="text" asp-for="Model.LatName" />
...
<label class="form-label" for="customFile">Profile Picture</label><input type="file" asp-for="Model.File" class="form-control" id="File" />
<input type="submit" value="Submit form" class="btn btn-primary" />
</form>
https://www.w3schools.com/ASp/webpages_forms.asp
Hope this helps you

Why Ajax is sending object in Response?

I have a very simple script in php that is supose to send a request to ajax and return the string im putting in the .php file but when the request respond, it sends an object instead of the string. I dont know why this is hapening because i already have done this the same way previusly and works fine.
this is the form that send the request
<form method="POST" id="personForm">
<div class="form-group col-md-6">
<label for="NameInput">Name</label>
<input type="text" name="name" class="form-control" id="NameInput">
</div>
<div class="form-group col-md-6">
<label for="lNameInput">Last Name</label>
<input type="text" name="lastname" class="form-control" id="lNameInput">
</div>
<input type="button" name="Send" class="btn btn-info" onclick="ajaxRequest($('#NameInput').val(), $('#lNameInput').val())" value="Send">
</form>
<hr>
<div id="result">
</div>
This is the script that send the ajax request
function ajaxRequest(name, lastn) {
var params = {
"name" : name,
"lastn" : lastn
};
$.ajax({
url: './process/resquestAjax.php',
method: 'POST',
data: params,
beforeSend: function() {
$('#result').html('<p>Procesando Peticion...</p>');
},
complete: function(completeResult) {
$('#result').html(completeResult);
},
sucess: function(successResult) {
},
error: function(jqXHR,estado,error){
alert('There was an error!: '+estado+' name-> '+error+' otro-> '+jqXHR);
alert("Please contact support ias soon as posible...!");
}
}); // End Ajax Call
}
and the php file is just this
$nombre = $_POST['name'];
$apellido = $_POST['lastname'];
echo "¡Hello! your name is : ". $nombre ." and your last name: ". $apellido;
I dont know why im not getting the string of that echo in the response of the ajax. it sends an object instead. I'm trying to make other project with database with this but i have the same issue.
See the documentation. You're using the complete callback, which receives the jqXHR object as its first argument.
Instead, you want to use the success (two cs, note), not complete, if you want to use the returned data. success receives the data as its first argument. (You can also use complete to remove the in-progress message, etc.)
So for instance:
function ajaxRequest(name, lastn) {
var params = {
"name" : name,
"lastn" : lastn
};
$.ajax({
url: './process/resquestAjax.php',
method: 'POST',
data: params,
beforeSend: function() {
$('#result').html('<p>Procesando Peticion...</p>');
},
complete: function(completeResult) {
// If you wanted to do something whether the request
// succeeded or failed, you'd do it here. Otherwise,
// remove this handler.
},
success: function(successResult) {
$('#result').html(successResult);
},
error: function(jqXHR,estado,error){
alert('There was an error!: '+estado+' name-> '+error+' otro-> '+jqXHR);
alert("Please contact support ias soon as posible...!");
}
}); // End Ajax Call
}

How to pass GET response data to POST Request

I am new using Angularjs and I am having an issue while parsing a JSON response. I am doing client side authentication for the login page and I have used get request to fetch data from servers side and post request for client side.
HTML code :
<form ng-submit="loginform(logcred)" class="ng-scope ng-pristine ng-valid center" name="logform"><br/><br>
<tr ng-repeat="logcred in serverinfo"></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>
<br/>
</form>
AngularJS code :
var myApp = angular.module('myApp', []);
myApp.controller('credientials', function($scope, $http) {
/* server side response*/
$http.get('http://localhost:3000/loginfo
.then(
function successCallback(response){
$scope.serverinfo = response.data;
});
/* client-side response*/
$scope.loginform = function(serverinfo,username,password){
$http({
url: 'http://localhost:3000/loginfo',
method: 'POST',
data: {
"username" :username,
"password" :password,
}
})
.then(
function successCallback(response){
console.log(response);
if (serverinfo.username === response.data.username && serverinfo.password === response.data.password) {
$scope.signinfo = response.data;
}else{
console.log("Error: " + response)
}
});
}
Problem what I am facing is, I need to send the GET response data into POST request and there I am doing the condition check, if the username and password matches, it's should give success meassage. But I am not sure my thinking is right or not.
What am I doing wrong?
Any help / advice would be greatly appreciated.
You can try below code.
$scope.loginform = function(serverinfo,username,password){
$http({
url: 'http://localhost:3000/loginfo',
method: 'POST',
data: {
"username" :username,
"password" :password,
}
})
.then(
function successCallback(response){
console.log(response);
if (response) { // Response will be either true or false. For this yu need to change the API response.
//Logged in successfully
}else{
//Something went wrong
}
});
}

Angular form not submitting via post

Please check why this angular code does not submit url via post. I am trying to send my form details through sms, to post a request via mobile.
<div id="page7-container1" ng-app="amApp">
<h4 id="page7-heading1" style="color:#000000;">App</h4>
<div id="page7-markdown3" class="show-list-numbers-and-dots">
</div>
<div id="page7-markdown6" class="show-list-numbers-and-dots">
</div>
<div id="page7-markdown5" class="show-list-numbers-and-dots">
</div>
<div id="page7-markdown4" class="show-list-numbers-and-dots">
</div>
<h3 id="page7-heading4" style="color:#337AE2;font-weight:600;">Request a call back</h3>
<form id="page7-form2" class="list" ng-controller="formCtrl" ng-submit="submitForm()">
<label class="item item-input item-floating-label" id="page7-input0">
<input type="text" name="formAdata.rname" required placeholder="Enter Your Name">
</label>
<label class="item item-input item-floating-label" id="page7-input1">
<input type="number" name="formAdata.rmobile" required placeholder="Enter Mobile Number">
</label>
<label class="item item-input item-floating-label" id="page7-input2">
<input type="text" name="formAdata.rlocation" required placeholder="Enter Your location/district/state?">
</label>
<input id="page7-button12" type="submit" ngClick="Submit" class="button button-positive button-block" value="Request call back!">
</form>
<script language="javascript">
var messager = '';
var app = angular.module('amApp', []);
app.controller('formCtrl', function ($scope, $http) {
$scope.submitForm = function() {
messager = "http://amritamultimedia.co.in/sms/sendsms.php?uid=9947009540&pwd=A3228B&msg=I am "+$scope.formAdata.rName+" from "+$scope.formAdata.rLocation+". My mobile number is: "+$scope.formAdata.rMobile+", I would like to get more info about Courses. Requested call back from your Mobile App, Please call me to my mobile.";
$http({
url: messager,
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $.param($scope.formAdata)
}).success(function(data, status, headers, config) {
document.getElementById("page7-form2").innerHTML = "We will get back to you within 3-4 hours. Thanks for checking our app.";
}).error(function(data, status, headers, config) {
});
};
});
</script>
</div>
What must be missing, or what am doing wrong?
Please help!
Thanks,
Sj
add this to your controller
$scope.formAdata={};
your using json parameters, so your formAdata doesn't gets binded properly.
Also check you are using POST but passing the data like a query string, so need to bindand send as a json object or use GET method.
One more thing double check if the value of messenger is getting assigned or not since there is no datatype is mentioned
var app = angular.module('amApp', []);
app.controller('formCtrl', function ($scope, $http) {
$scope.formAdata={};
var messager = "";
$scope.submitForm = function() {
messager = "http://amritamultimedia.co.in/sms/sendsms.php;
var userData={
"uid":mobilenumber,
"pwd":password,
"phone":$scope.formAdata.phone,
"msg": $scope.formAdata.message
}
$http({
url: messager,
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: userData,
}).success(function(data, status, headers, config) {
document.getElementById("page7-form2").innerHTML = "We will get back to you within 3-4 hours. Thanks for checking our app.";
}).error(function(data, status, headers, config) {
});
};
});
This will work.

How can I use Angular $http to POST data to PHP

plenty of topics regarding this and I promise I have tried a lot (all day).
Here is the code I have:
app.controller('contactsController', function($scope, $rootScope, dataService, $http) {
$rootScope.currentPage = "contact";
$scope.postData = [];
$scope.runScript = function() {
$http({
url: "post.php",
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $.param({postData:$scope.postData})
}).success(function(data, status, headers, config) {
$scope.data = data;
}).error(function(data, status, headers, config) {
$scope.status = status;
});
};
});
<form name="contactForm" method="post" ng-submit="runScript()">
<div class="col-sm-10">
<div class="input-group">
<span class="input-group-addon" id="basic-addon1">E-mail Address</span>
<input ng-model="{{postData.email}}" name="email" class="form-control" placeholder="johnsmith#example.com" aria-describedby="basic-addon1" required>
</div>
<br>
<div class="input-group">
<span class="input-group-addon" id="basic-addon1">Message</span>
<textarea ng-model="{{postData.message}}" name="inputMessage" class="form-control"></textarea>
</div>
</div>
<div class="col-sm-2">
<button type="submit" class="btn btn-default">Send</button>
</div>
</form>
{{data}} and {{status}}
$inputData = file_get_contents("php://input");
$inputData = json_decode($inputData);
$email = $inputData->email;
echo $email;
Now I've probably made a few mistakes whilst trying to get this to work, from what I had earlier - I'm not getting any errors but I'm also not getting any success - I've been at this all day!!!! Thanks!
Angular posts the data in JSON format that php does not natively consumes. You will have to read and json decode the input like so:
// get the raw POST data
$inputData = file_get_contents("php://input");
// this returns null if not valid json
$inputData = json_decode($inputData);
I might be wrong but if you only use POST you should find your data in the _POST variable. You need to use file_get_contents("php://input") only if you submit PUT requests.
Also, you are submitting a key postData and you are trying to read ->email..

Categories