unable to get proper data with AngularJS post method - php

this is my 1st time with AngulerJS. I'm trying to POST data to the server.
AngularJS Code
var app = angular.module("myApp", []);
var BASE_URL = "http://localhost/project/api/Data/";
var GET_DATA = BASE_URL+"get_data";
console.log(GET_DATA);
app.controller('myCtrl', function($scope, $http) {
var inputs = { "user_id": "3"};
var config = {
headers : {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
}
}
$http.post(GET_DATA , inputs, config)
.success(function (response, status, headers, config) {
$scope.content = response.error;
$scope.statuscode = response.status;
$scope.statustext = response.statusInfo;
console.log(response);
})
.error(function (data, status, header, config) {
$scope.ResponseDetails = "Data: " + data +
"<hr />status: " + status +
"<hr />headers: " + header +
"<hr />config: " + config;
});
});
This code is posting data to the server, but with something wired format. Below is my print_r($_POST); result :
Array
(
[{"user_id":"3"}] =>
[0] =>
)
this is wrong result, I am expecting something like
Array
(
user_id => 3
)
Note : I'm using CodeIgniter framework at server side.

You can send your post data in json:
$http.post(GET_DATA , {"user_id": "3"})
.success(function (response, status, headers, config) {
$scope.content = response.error;
$scope.statuscode = response.status;
$scope.statustext = response.statusInfo;
console.log(response);
})
.error(function (data, status, header, config) {
$scope.ResponseDetails = "Data: " + data +
"<hr />status: " + status +
"<hr />headers: " + header +
"<hr />config: " + config;
});
});
And in the server side you can get the post data like this:
$postdata = json_decode(file_get_contents('php://input'));
print_r($postdata);
You have to encode your data in the post body in urlencoded format when the request content type is application/x-www-form-urlencoded`. Which should be like this:
var inputs = 'student_id=3';

Though it is not the right practice to write answer of old question but I want to post this answer so that others can take help whenever they required.
Firstly, understand the reason why such thing is happening. The reason is, AngularJS doesn’t serialize the data ( parameters ) passed to the POST request automatically. Therefore we have to serialize the data with$httpParamSerializerJQLike which is available as AngularJS Service . Also the default content-type of the posted data is application/json. Therefore we need to override the Content-type headers of the post request to application/x-www-form-urlencoded in order to access the the posted values via $_POST.
Now in angular there is also provided $httpParamSerializer service but the difference $httpParamSerializerJQLike is something object also containing another object so if former is used, then internal object won't be serialized i.e. all nested objects won't be serialized with $httpParamSerializer but it is not the case with $httpParamSerializerJQLike.
You can check the difference here: AngularJS $httpParamSerializer service DOC
Now, rather than json encode and decode data in php, we can do that in Angular JS itself by using $httpParamSerializerJQLike service in angular JS in this way:
$http({
url: myUrl, //post your url here
method: 'POST',
data: $httpParamSerializerJQLike({ 'user_id': '3'}),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
And in codeigniter you can get that posted data by normal syntax i.e. $this->input->post('user_id');
For more information...you can refer the above link mentioned...
Hope it might help you....

Related

The variables never reach PHP from the FETCH API

I have 3 files (HTML,JS and PHP) in the HTML save de info in variable called DatosPaciente in JavaScript
function Tomar_DATOS(){
DatosPaciente={
id:document.getElementById("paciente_id").value,
fecha:document.getElementById("fecha").value
};}
Then i use a function called Tiene_Cita_Hoy inside of a JS file
Tiene_Cita_Hoy(DatosPaciente)
in the JS file i try to use the Fetch API to send info to the PHP file
function Tiene_Cita_Hoy(Datos){
console.log(Datos);//"{id: "8", fecha: "2020/09/03"}" here everything is fine
fetch('tiene_cita.php',{
method: 'POST',
body: Datos
})
.then(res => res.json())
.then(data => {
console.log(data); //to see the result
})
}
then in a PHP file, then tried to receive the information via POST
$VALOR_id_paciente=$_POST['id'];
$VALOR_fecha=$_POST['fecha'];
and then I assign those values ​​to a query
$SQL="SELECT * FROM vhsagenda WHERE PACIENTE='".$VALOR_id_paciente."' AND FECHA='".$VALOR_fecha."'";
echo json_encode($SQL);//just to see what information have
but the result is always: SELECT * FROM vhsagenda WHERE PACIENTE='' AND FECHA=''
apparently the information never reaches the PHP file
I have made some proper way for this method to get working.
You need to make an object first, then pass it in 'for loop'. It will generate string like this for example (test=123&test_two=444)
async function catch_something(url, bodyContent = {test: 123, test_two: 444}){
let bodyContent_string = '';
if(bodyContent instanceof Object){
for(const form_key of Object.keys(bodyContent)){
if(form_key != Object.keys(bodyContent)[Object.keys(bodyContent).length - 1]){
bodyContent_string += `${form_key}=${bodyContent[form_key]}&`;
}else{
bodyContent_string += `${form_key}=${bodyContent[form_key]}`;
}
}
}
const response = await fetch(url, {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
headers: {
'X-Requested-With': 'XMLHttpRequest',
'Content-Type': 'application/x-www-form-urlencoded'
},
body: bodyContent_string
}).catch((error) => {
console.error('Error:', error);
});
if(!response.ok){
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
}
You should send the parameters as a URL-encoded string.
function Tomar_DATOS(){
DatosPaciente = 'id=' + encodeURIComponent(document.getElementById("paciente_id").value) + '&fecha=' + encodeURIComponent(document.getElementById("fecha").value);
}
You've passed a plain object to the body parameter, but fetch doesn't know what to do with that data type (so it converts it to the useless string "[object Object]").
You should pass something that fetch knows how to convert into something supported by PHP instead.
e.g. a FormData object.
DatosPaciente = new FormData(document.getElementById("form_containing_your_inputs"));

having issue on Accessing Ajax Post data on PHP

I am having some issue on accessing Ajax Post data on server side. I have
var data = {
ox:'A',
oy:'B',
dx:'C',
dy:'D',
method:null
};
I have a jQuery event hamdler like
$("#route").on("click", function(){
var request = $.ajax({
type: "POST",
url: "assets/app.php",
data: data,
cache: false,
dataType: "JSON",
beforeSend: function() {
console.log(data);
}
});
request.done(function( data ) {
console.log(data);
});
request.fail(function( jqXHR, textStatus ) {
console.log( "Request failed: " + textStatus );
});
});
I am able to send the data correctly as it is logging out at beforeSend
{ox: A, oy: B, dx: C, dy: D, method: null}
On PHP side I have
$method = $_POST['method'];
$ox = $_POST['ox'];
$oy = $_POST['oy'];
$dx = $_POST['dx'];
$dy = $_POST['dy'];
now only accessing to one of the $_POST[] data is working like echo $ox; but when I try to access all $_POST[] data like
echo $ox;
echo $dy;
$startPoint = array($ox, $oy);
$endPoint = array($dx, $dy);
I am getting Request failed: parsererror error on .fail()
From the docs:
dataType (default: Intelligent Guess (xml, json, script, or html))
Type: String
The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are:
So, your response isn't a valid JSON.
What you can do is to create an array, like you are doing:
$startPoint = array($ox, $oy);
$endPoint = array($dx, $dy);
Then encode into json and echo it
echo json_encode(['startPoint' => $startPoint, 'endPoint' => $endPoint]);
On the frontend (javascript) you will get and JSON like
{
'startPoint' : ['ox','oy'],
'endPoint' : ['dx','dy'],
}
the values of ox, oy, dx and dy, of course, will be the values sent before.

Update view angular array push

I am trying to handle the push update in Angular in the view but it has been impossible for me. I know the following:
I have an array, this array is called marca1 and it receives all the objects that the get request that I make to the server and it shows in the view with ng-repeat.
When I send the post request to save a new data, it gets a response from the server that I save it in an object called pepa.
I use the push function for my fix to refresh the view, but that does not work.
Why can it be failing? How can I fix it?
This is my code:
miAppAngular.controller('marca',function($scope,$http,$location,$routeParams,configuracionGlobal){
$scope.config = configuracionGlobal;
$scope.marca1=[];
$http.get( configuracionGlobal.api_url + "/marca/listaMarca.php")
.then( function(respuesta){
$scope.marca1=respuesta.data;
});
$scope.nuevaMarca = function ( ){
$scope.newMarca={
'nombre':$scope.nombreMarca
}
$scope.pepa={};
//
$http({
url: configuracionGlobal.api_url + "/marca/nuevaMarca.php",
method: "POST",
data: $scope.newMarca,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.then(
function(respuesta){
$scope.pepa= respuesta;
$scope.marca1.push($scope.pepa);
$('#modalMarca').modal('hide');
}
)
}
Try to run getMarca after posting:
$scope.getMarca = function() {
$http.get( configuracionGlobal.api_url + "/marca/listaMarca.php")
.then(function(respuesta)
{
$scope.marca1=respuesta.data;
});
}
In your .then() of your post, at the end call: $scope.getMarca()
This shall update the array $scope.marca1.
The response returned after a POST is usually used for checking; whether it was a success or failure (or to return custom values from backend).

Can not read posted raw data in php from angularjs after enable HTTPS

I am trying to make a post request from my angular js, as below
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
var deferred = $q.defer();
$http.post(posturl, data)
.success(function(data, status, headers, config) {
console.log(status + ' - ' + data);
deferred.resolve(data);
})
.error(function(msg) {
console.log(msg);
deferred.reject(msg);
});
return deferred.promise;
and in my serve side php code for receiving raw data i am using following method
$post_data = json_decode(file_get_contents("php://input"));
echo $post_data;
it was working perfectly when I am using http in my url.After I enable ssl in my server i can't read raw data from the post method.
How to resolve this?

How to access all elements in an array from php that is passed by an ajax call?

I am finding difficulty in accessing elements in an array from php file. The array is passed through an ajax call. Please find below the ajax call.
var data = ['test1', 'test2', 'test3'];
$(document).ready(function () {
$("button").click(function () {
$.ajax({
type: "POST",
url: "getResult.php",
data: {
testData: data
},
success: function (data, status) {
alert("Data: " + data + "\nStatus: " + status);
}
});
return false;
});
});
The server side [PHP] code is
$myArray = $_POST["testData"];
echo $myArray;
However $myArray always returns last element[test3 here] in the array. How do I access first [here test1] and other elements?
Pls help.
What you need to do is convert the JavaScript array to JSON and then send over that JSON.
On the PHP side you should decode the JSON back into an array. Finally, you should re-encode the array as JSON before sending it back.
On your client side change one line:
data: {testData : JSON.stringify(data)},
On your server side do:
$myArray = json_decode($_POST["testData"]);
header('Content-Type: application/json');
echo json_encode(array('pheeds' => $pheeds, 'res' => $res));
JS:
JSON.stringify(data)
PHP:
$myArray = json_decode($_POST['data']);
For simple structures you can use jQuery Param
data : $.param({testData:data})
With this you should be able to access your data with
echo $_POST["testData"][0]...[2];
Try this when passing JS vars by ajax.
use Firebug to see on the console what is being poted to the PHP file, this will save you a lot of trouble.
you will see that array is an OBJECT , So you want to send this array as a JSON / STRING to the PHP file.
use :
var data = ['test1','test2','test3'];
data = JSON.stringfy(data);
at the PHP:
$data = var_post('test_data');
$data=json_decode($data);
$print_r($data);

Categories