Http Post not sending data to another page in angular js - php

I am working on login form in Angular Js.The HTML and validation part is working fine.
The problem is when i send data using HTTP POST method to my servicecall PHP page and want to save it to DB.
I have tried all the way by setting this in JS
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
I have tried by setting enctype of form to
enctype="application/x-www-form-urlencoded"
as well.But none of them is working i am not able to get data via $_REQUEST, $_POST, $_GET any of these method.
I have also tried using PHP library function.
$postdata = file_get_contents("php://input");
But it gives some weird string which i can't handle because number of POST data could be hundreds.
So this there any other way to solve the problem.
Code for http request is
var req = {
method: 'POST',
url: 'servicecall.php',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: {
username: $scope.loginData.username,
password: $scope.loginData.password,
action : 'checkLogin'
} //First way of sending data
//Second way of sending data which is also not working
//data: "{username:"+$scope.loginData.username+",password:"+$scope.loginData.password+",action:checkLogin}"
}
$http(req).then(function(response){
console.log(response);
}, function(response){
alert("Error "+response);
});
At PHP page i do
print_r($_REQUEST);
print_r($_POST);
But it prints just blank array like array{}

Following the code that I am using for same purpose. Hope that may help you.
var app = angular.module('angularApp', []);
app.controller('loginCtrl', function ($scope, $http) {
$scope.login = function () {
var request = $http({
method: "post",
url: "login.php",
data: {
email: $scope.email,
password: $scope.password
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
/* Successful HTTP post request or not */
request.success(function (data) {
if(data == "1"){
$scope.responseMessage = "Successfully Logged In";
}
else {
$scope.responseMessage = "Username or Password is incorrect";
}
});
}
});

Related

Passing data via ajax issues

I'm trying to pass data to my laravel controller function via Ajax. At this point I just want to return the data being sent to verify ajax is working. I can "GET" with ajax, but when I try to "POST" ajax brakes.
Could someone please tell me what I'm doing wrong? Thank you.
Here is my ajax code...
var startMapLocation = { startCity: "Cleveland", startStat: "Oh" };
$.ajax({
type: "POST",
url: url,
data: startMapLocation,
success: function(data, status) {
//alert(data);
console.log("success:", data);
},
error: function() {
alert("Ajax Broke!" + status);
}
});
My laravel function is...
public function postphp( Request $request)
{
$a = $request->all();
$city = $a["startCity"];
return json_encode( $city );
}
Thanks every one for your help. To resolve this issue, I first had to verify that my route was a post route not a get route.
Route::post('/postphp', 'GSResultController#postphp');
I also need to get my csrf-token and add it to the ajax call.
headers: {
"X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content")
},
This fixed my problem.

Sending data from the form to an email with jQuery ajax and redirect to another page with passing POST variables not work

I have my own form in Wordpress, which after filling in and clicking submit redirects to the page with thanks and data from this form. At the same time, but before redirecting the same data from the form are sent to the user and admin emails. The steps of the whole process are as follows.
Form validation in jQuery Validate
Sending data from the form to an
e-mail using jQuery ajax
Redirecting to the page thanking you and
sending the variables from the form to this page using the POST
method (jQuery + PHP).
jQuery code:
// validation
$('#registration_form').validate({
rules: {
training_name: "required",
training_place: "required",
training_date: "required",
participants_number: {
required: true,
range: [0,100]
},
(...) // etc
});
// jQuery ajax email sending
$('#registration_form').on('submit', function(e) {
// e.preventDefault();
if ($(this).valid()) {
let formData = $(this).serialize();
$.ajax({
url: ajax.url,
type: 'POST',
cache: false,
async: true,
xhrFields: {
withCredentials: true
},
data: {
action: 'registerFormSendEmail',
form_data: formData
},
success: function(res) {
// console.log(res);
}
});
// return false;
}
});
In html form code I have action name with permalink to Thank you Page with POST variables.
The problem is that sometimes sending emails and redirecting with POST variables works, and sometimes not. Most often it doesn't work on Safari. Someone has an idea why and what I'm doing wrong?
I managed to solve the problem. It turned out later that e-mails were not sent in browsers other than Safari too. The problem was that sometimes the website redirected faster than the email was sent using Ajax (it probably depends on the speed of the Internet connection).
I used the .when() and .then() functions. I modified the ajax function in such a way that form data firstly had to be successfully sent to the e-mail and then submitted the form and redirected to the 'thank you' page.
$('#submit_registration').on('click', function(e) {
e.preventDefault();
if ($('#registration_form').valid()) {
let formData = $('#registration_form').serialize();
var checkEmailSent;
$.when(
$.ajax({
url: ajax.url,
type: 'POST',
dataType: 'JSON',
cache: false,
data: {
action: 'registerFormSendEmail',
form_data: formData,
},
success: function(res) {
console.log(res);
if (res !== 'sent') {
alert('Error in sending e-mail.');
checkEmailSent = false;
}
}
})
).then(function() {
if (checkEmailSent == false) {
return false;
} else {
$('#registration_form').submit();
}
});
}
});

How take data from json response in angularjs

hello everyone i have some issue
in my controller i do http post to server and run of the server some file with php server side language and check if i the user is register in mydb
this is my code:
$scope.sendPost = function()
{
var login =
'mylogin='+ JSON.stringify({
email: $scope.email,
pass: $scope.pass
})
$http({
method : 'POST',
url : 'http://igortestk.netai.net/login.php',
data: login,
Content-Type:'text/plain',
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(data){
console.log(data);
console.log(resultlogin);
console.log(json);
}).error(function(error){
console.log(error);
})
from the sever side i back json_encode in php of some status of login
so my question is how i take the json value from the server response
this is my server response :
{"statuslogin":1}]
edit: this is my server side code in php;
$query="select * from `User` where Email='$email' and Pass='$pass'";
$result=mysql_query($query ,$con);
if(mysql_num_rows($result)==1){
$reponse['statuslogin']=1;
}
else{
$reponse['statuslogin']=0;
}
$output=json_encode($reponse);
print $output;
edit2:
ok it's doesnt work beacuse the data of the response is a string and data[0] i get "[" this bracket : data: "[{"statuslogin":1}]" so maybe some other solution ?
You can get the value with:
console.log(data.statuslogin);
In case of one array:
console.log(data[0].statuslogin);
$http({
method: "POST",
url: "http://igortestk.netai.net/login.php",
data: login,
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
}).success(function (data) {
console.log(data[0].statuslogin); // In the console will print: 1
// If you need to show a message according the result, you can do this:
$scope.message = (data[0].statuslogin === 1) ? "Login success" : "Login error, please check";
}).error(function (error) {
console.log(error);
});
However, according the AngularJS Documentation, the success method is deprecated:
The $http legacy promise methods success and error have been
deprecated. Use the standard then method instead.
https://docs.angularjs.org/api/ng/service/$http
Then, you might use the standard form with the shortcut form, by using then(). Something like this:
$http.post("http://igortestk.netai.net/login.php", data, { headers: { "Content-Type": "application/x-www-form-urlencoded" }}).then(function(response)
{
console.log(response.data[0].statuslogin); // In the console will print: 1
}, function(response)
{
console.log(response);
});
Demo
PHP File: loginajax.php
<?php
header("Access-Control-Allow-origin: *");
header("Content-Type: application/json");
header("Cache-Control: no-cache");
$reponse['statuslogin']=1;
$output=json_encode($reponse);
echo $output;
flush();
?>
(function() {
var app = angular.module("myApp", []);
app.controller("Controller", ["$scope", "$http",
function($scope, $http) {
$scope.email = "email#server.com";
$scope.pass = "123456";
var login =
'mylogin=' + JSON.stringify({
email: $scope.email,
pass: $scope.pass
});
$http({
method: "POST",
url: "http://dfjb.webcindario.com/loginajax.php",
data: login,
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
}).success(function(data) {
console.log(data.statuslogin); // In the console will print: 1
// If you need to show a message according the result, you can do this:
//$scope.message = (data[0].statuslogin === 1) ? "Login success" : "Login error, please check";
}).error(function(error) {
console.log(error);
});
}
]);
})();
<html data-ng-app="myApp">
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body data-ng-controller="Controller">
</body>
</html>
In the network tab of Google Chrome console, i have this json response:
The better way to access JSON data service is with ngResource which can be used to consume Restful API in AngularJs.
.factory('UserService', function ($resource) {
return $resource('http://jsonplaceholder.typicode.com/users/:user',{user: "#user"});
});
To perform Resource get just do:
$scope.users = UserService.query();
resource object has the following methods:
{ 'get': {method:'GET'},
'save': {method:'POST'},
'query': {method:'GET', isArray:true},
'remove': {method:'DELETE'},
'delete': {method:'DELETE'} };
To get a specific user:
$scope.oneUser = UserService.get({user: 1});
More info can be found here: https://docs.angularjs.org/api/ngResource/service/$resource
Maybe this will help you
$http('http://igortestk.netai.net/login.php').post(data).then(function(data){ if(data.statuslogin === 1){alert('welcome');} });

Ajax request to php from angular js

I am trying make an ajax request to php from angular js. But I am not getting the data I have sent. Please let me know where I am going wrong.
The following is the ajax call.
<script type="text/javascript">
angular.module('app', []).controller("MyController", function($scope, $http) {
var req = {
method: 'POST',
url: 'pujastrail/www/rest/get.php',
headers: {
'Content-Type': "application/x-www-form-urlencoded; charset=utf-8"
},
data: { lang: "fr" }
}
$http(req).success(function(data, status, headers, config){alert("done"+data);}).error(function(data, status, headers, config){alert("error"+res);});
});
</script>
The following is the php code.
<?php
if (isset($_POST['lang']) && !empty($_POST['lang'])) {
$lang = $_POST['lang'];//this needs to be sent back to js file
} else {
$lang = "eRROR";// but this is being sent back to the js file
}
echo (json_encode($lang));
?>
I have tried this using $_REQUEST also but it didnot work.
In your angular code, you need to encode the parameter data as a string like lang=fr instead of {lang: 'fr'}.
Try using $.param(obj) or $.param({lang: "fr"}) to convert it like this:
var req = {
method: 'POST',
url: 'pujastrail/www/rest/get.php',
headers: {
'Content-Type': "application/x-www-form-urlencoded; charset=utf-8"
},
data: $.param({ lang: "fr" })
}
source source

Posting XML data to a PHP API via Phonegap/Ajax

I've been task with building an app to check on the status of servers through a phonegap app. The trouble is the client is not giving me access to the existing API or the server. The only information he has given me is: "You can send a POST request to the xmlUserApi.php named "request" by jQuery for example."
As I understand it, we are sending some XML in the format
<xmlApi>
<action> getServerList </action>
<auth></auth>
</xmlApi>
For example, from which a an XML list of all the servers is returned.
Whenever I try to POST this data to the PHP (xmlUserApi.php), nothing is returned. I feel it would be helpful to look through the PHP, but, the client won't let me.
Any help/ideas would be really appreciated
EDIT
The response I'm getting in the inspector is :
<form action=xmlUserApi.php method=post>
<textarea name=request cols=120 rows=30></textarea>
<input type=submit value=Request></form><br><br>86.135.213.213
What your client is suggesting is programmatically replicating the action of a user filling out the form at the address they provided.
To do that, try this:
var xmlData = '<xmlApi><action> getServerList </action><auth>xxxxxx</auth></xmlApi>';
var serverPath = 'http://some.com/path/';
var requestPath = 'xmlUserApi.php';
var request = $.ajax({
url: requestPath,
type: 'POST',
dataType: 'jsonp',
data: { request: xmlData }
});
request.done(function(data) {
/process data
});
request.fail(function(jqXHR, textStatus) {
alert(textStatus);
});
//Leaving original answer down here
"You can send a POST request to the xmlUserApi.php named "request" by jQuery for example."
Not sure what they mean by 'named "request"', but with jQuery you would do this:
var serverPath: 'http://their.server.tld/path/';
var authToken: 'sometoken';
$.post(serverPath + 'xmlUserApi.php', { action: 'getServerList', auth: authToken },
function(data) {
//whatever you want to do with the return goes here
}
);
There may also be an issue with the connection to the API, sometimes passing additional parameters helps with this, you could try:
var serverPath = 'http://their.server.tld/path/';
var requestPath = serverPath + 'xmlUserApi.php';
var authToken = 'sometoken';
$.ajax({
url: requestPath,
type: 'POST',
dataType: 'jsonp',
data: { action: 'getServerList', auth: authToken }
}).done(function(data) {
//processing here
}).fail(function(jqXHR, textStatus) {
alert(textStatus);
});

Categories