Ajax request to php from angular js - php

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

Related

ajax call with post parameter -not able to receive that parameters at server side

I have added below call for ajax call
$http({
url: "http://localhost/angular-js-apis/listing.php",
method: "POST",
data: {type: "list"},
headers: {'Content-Type': 'application/json;charset=utf-8'}
}).then(function mySuccess(response) {
$scope.listing = response.data;
}, function myError(response) {
$scope.myWelcome = response.statusText;
});
and at server site at below file code
http://localhost/angular-js-apis/listing.php
<?php
include("database.php");
echo "<pre>";var_dump($_POST);die("test to die");
?>
but in my server it prints only empty value of $_POST.
can anyone tell me what is an issue over here?
Try the following snippet
Angular
$http.post(
url: "http://localhost/angular-js-apis/listing.php",
JSON.stringify({type: "list"})
).then(function (response) {
$scope.listing = response.data;
}, function (response) {
$scope.myWelcome = response.statusText;
});
Server
$data = json_decode(file_get_contents('php://input'), true);
print_r($data);

Http Post not sending data to another page in angular js

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";
}
});
}
});

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');} });

Workaround possible for cURL and Javascript?

Everything was going great in my previous help request thread. I was on the correct track to get around a CSRF, but needed to be pointed in the right direction. I received great help and even an alternate script used to log into Google's Android Market. Both my script and the one I altered to match my form is get hung up at the same point. Apparently cURL cannot process JS, is there any way to work around the form being submitted with submitForm() without changing the form?
Here is the code for the SubmitForm function
function submitForm(formObj, formMode) {
if (!formObj)
return false;
if (formObj.tagName != "FORM") {
if (!formObj.form)
return false;
formObj = formObj.form;
}
if (formObj.mode)
formObj.mode.value = formMode;
formObj.submit();
}
Here is the code for the submit button -
<a class="VertMenuItems" href="javascript: document.authform.submit();">Submit</a>
Here is a link to my last question in case more background information is needed.
PHP service...
<?php
// PHP service file
// Get all data coming in via GET or POST
$vars = $_GET + $_POST;
// Do something with the data coming in
?>
Javascript elsewhere...
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
function sendData(data)
{
var response;
$.ajax({
url: 'phpservice.php',
data: data,
type: 'POST',
dataType: 'json',
async: false,
success: function(response_from_service)
{
response = response_from_service;
},
error: function()
{
}
});
return response;
};
function getData(data)
{
var response;
$.ajax({
url: 'phpservice.php',
data: data,
type: 'GET',
dataType: 'json',
async: false,
success: function(response_from_service)
{
response = response_from_service;
},
error: function()
{
}
});
return response;
};
});
</script>

Unable to receive only JSON from JQuery ajax call

Here is my js code.
....
var arrayData = {"projectId": projectId, "stateId":stateId};
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "/bidboldly/projects/editproject/",
data: arrayData,
success : function(response) {
alert(response);
},
error: function(){
alert("error");
}
})
Server side.
$city = $this->City->find('list',array('conditions' =>array('City.status'=>1, 'City.state_id'=>$this->params['url']['stateId']),'fields'=>array('City.id','City.city'),'order'=>array('City.city ASC')));
echo json_encode($city);
After that in client side I've recieved city list + html. Something like this.
..."Young America" [20292]=> string(10) "Zanesville" } <html><head>......
Why is HTML transfered ?
This article http://book.cakephp.org/1.1/view/316/Helpers says you should use the ajax render layout:
$this->layout = "ajax";
Another page full of helpful articles on ajax and cake php is this one:
http://ahsanity.wordpress.com/2007/02/23/get-started-with-ajax-in-cakephp/

Categories