angular how to pass an object in an ajax post - php

I have being battling almost for day now about something that sound quite simple. I'm trying to pass an object using angular post ajax. I'm using PHP with codeigniter framework and I'm not getting any values pass. there have to be something wrong with the way I'm sending the object in angular because php is not getting anything. It's going to the right place because I'm getting a respond error saying "Trying to get property of non-object, line 173" line 173 is $AccessKey = $data->AccessKey;
this is my angular code
app.controller('loginController', function($scope, $http){
//$scope.formData = {};
$scope.processForm = function(){
$http({
method : 'POST',
url : 'http://localhost:8888/employees/login',
data : '{"AccessKey":"candoa01#gmail.com","Password":"candoa21"}'
})
.success(function(data){
console.log(data);
})
};
});
this is my php. i think here maybe I'm not using the right object name to retrieve the values.
public function login()
{
$data = $this->input->post('data');
//$data = '{"AccessKey":"candoa01#gmail.com","Password":"candoa21"}';
$data = json_decode($data);
$AccessKey = $data->AccessKey;
$Password = $data->Password;
$sql = "SELECT *
FROM Employees
WHERE Employees.AccessKey = ?
AND Employees.Password = ?";
$query = $this->db->query($sql, array($AccessKey, $Password));
if($query->num_rows() > 0)
{
$query = json_encode($query->result());
return $this->output
->set_content_type('application/json')
->set_output($query);
}
else
{
return 'Invalid AccessKey Or Password';
}
}
}

Try this, use params instead of data & remove ' in params
$http({
url: 'http://localhost:8888/employees/login',
method: "POST",
params: {"AccessKey":"candoa01#gmail.com","Password":"candoa21"}
})

As per your sever side code you have to pass the data as show below.
$scope.processForm = function(){
$http({
method : 'POST',
url : 'http://localhost:8888/employees/login',
data : {
data: JSON.stringify({
AccessKey: "candoa01#gmail.com",
Password:"candoa21"
})
}
})
.success(function(data){
console.log(data);
})
};

You receiving data wrong way because you are not posting data json format.This should be
$AccessKey = $this->input->post('AccessKey');
$Password = $this->input->post('Password ');
Or you can use this way
$data = $this->input->post();
$AccessKey = $data['AccessKey'];
$Password = $data['Password'];

Related

Save data to MySQL - json_encode

I have a problem with transferring data to the database.
So yes - I created a controller in CodeIgniter 3, which is to send data to the database.
Before sending, the data is checked using JWT.
My code PHP looks like this:
public function create()
{
$token = $this->input->post('token');
$this->jwt->decode($token, config_item('encryption_key'));
$payload = $this->input->post('payload');
unset($payload['login']);
unset($payload['email']);
unset($payload['role']);
$note = $this->input->post('note');
$note = json_encode($note);
$data = $payload;
$data['note'] = $note;
$this->notes_model->create($data);
}
AngularJS:
$scope.noteCreated = function( note ){
$http({
method: 'POST', url: 'api/admin/notes/create/', data: {'note' : note, token: checkToken.raw(), payload: checkToken.payload()} }
).then(function (){
$scope.success = true;
$timeout( function(){
$scope.success = false;
$scope.note = {};
console.log(note);
}, 2000);
},function (error){
console.log('Blad we wczytywaniu danych');
});
}
The data it receives after sending it is in this form:
And they should look like this:
Problem: How to transfer data to get to your columns?
To save data into different columns, you have to make array like this:
$data['noted'] = $note['noted'];
$data['id_domain_rel'] = $note['id_domain_rel'];
now you can pass $data .
Please dont use json_encode.

Get params from angular $http in Codeigniter controller

I am new to angular.So i dont know i am doing it in the right way.I am working in codeigniter along with angular.I need to get the id which i was passing though the angular $http service in my codeigniter controller.. I didn't get any console errors. Simply the data is not returning.. This is my angular controller
app.controller("newsController_id",function($scope,$http,$routeParams){
$http({ method:'POST',
url:'Controller1/get_list_id',
params:{id:$routeParams.id}
})
.then(function (response) {
$scope.blogs_id = response.data;
})
codeigniter controller
public function get_list_id() {
$id=$this->input->post('id');
//$id='6';
$data = $this->Blog_model->getAll_id($id);
$this->output->set_content_type('application/json')->set_output(json_encode($data));
}
There are no errors in the codeigniter model and view pages..since i got my result perfectly when i hardcoded the id value as 6.But no output when i posting the id.help me solving this
you are doing wrong way to pass data angujarjs to codeigniter.
if you want to pass data in POST method pass object in $http service on data section like below
AngularJS Code
$http({
method:'post',
url:'/login',
dataType:"json",
data:{"vEmail":$scope.vEmail,"vPassword":$scope.vPassword},
}).then(function(suc){
console.log(suc);
},function(err){
console.log(err);
});
Codeigniter Code
$vEmail = $this->input->post('vEmail');
$vPassword = $this->input->post('vPassword');
If you want to pass data usgin GET you should be pass data in Param section like below
$http({
method:'get',
url:'/login',
dataType:"json",
params:{"vEmail":$scope.vEmail,"vPassword":$scope.vPassword},
}).then(function(suc){
console.log(suc);
},function(err){
console.log(err);
});
you can get that in codeigniter using get method like below
$this->input->get('vEmail');
You can not get the data by $_POST or $this->input->post , You should have something like this in constructor:
$postdata = file_get_contents("php://input");
$this->request = json_decode($postdata);
Now In controller, you can access the id:
$id = $this->request->id;
But it has a problem, you can't use Codeigniter form validation, because it works with $_POST superglobal. You can do something like this instead (in constructor):
$objectRequest = json_decode( file_get_contents("php://input") );
$this->request = xss_clean( json_decode(json_encode($objectRequest), true) );
$_POST = $this->request;
But this time you can access to id by the following example:
$id = $this->request['id'];
in order to get the post variables from angular you need use the following code
$postdata = file_get_contents("php://input");
$myData = json_decode($postdata);
instead of $id=$this->input->post('id');
so your $id = $myData->id;
Your final code would look like this:
public function get_list_id() {
$postdata = file_get_contents("php://input");
$myData = json_decode($postdata);
$id = $myData->id;
//$id='6';
$data = $this->Blog_model->getAll_id($id);
$this->output->set_content_type('application/json')->set_output(json_encode($data));
}

Return data AJAX PHP

By defaut, when my system loads some data is filtered in my db and shown to the user. But my doubt is how can I call AJAX to filter some new data, and return it, changing the default values that are already set on my variables.
This is my AJAX call:
$("#botao-filtrar").click(function(){
$(".mask-loading").fadeToggle(1000);
$.ajax({
url: 'datacenter/functions/filtraDashboardGeral.php',
type: 'POST',
data: {rede: $("#dropdown-parceria").val()},
})
.done(function(resposta){
console.log(resposta);
})
.always(function(){
$(".mask-loading").fadeToggle(1000);
})
});
And this is what I got from trying to filter some data to return it,
but nothing worked:
<?php
require_once('../../includes/conecta.php');
$rede = $_POST['rede'];
function buscaDados($conexao){
$dados = array();
$resultado = mysqli_query($conexao, "SELECT * FROM evolucao_originacao WHERE rede = {$rede}");
while($valores = mysqli_fetch_assoc($resultado)){
array_push($dados, $valores);
}
}
Any idea?
Thanks!
You should add echo at the end :
echo json_encode($dados);
So the $dados array will be sent back to the ajax request as JSON response.
Parse the response to json uisng $.parseJSON() :
.done(function(resposta){
resposta = $.parseJSON(resposta);
console.log(resposta);
})
Hope this helps.
in your ajax code u add a success.
$("#botao-filtrar").click(function(){
$(".mask-loading").fadeToggle(1000);
$.ajax({
url: 'datacenter/functions/filtraDashboardGeral.php',
type: 'POST',
dataType: 'json',
data: {rede: $("#dropdown-parceria").val()},
success: function (data) {
//You do not need to use $.parseJSON(data). You can immediately process data as array.
console.log(data)
//if you have a array you use the following loop
for (var j =0;j < data.length;j++) {
console.log(data[j]);
// u can use data[j] and write to any fields u want.
// e.g.
$('.somediv').html(data[j].myarraykey);
}
})
.done(function(resposta){
console.log(resposta);
})
.always(function(){
$(".mask-loading").fadeToggle(1000);
})
});
And for the php codes (i did not check whether your code is valid or not), you need to add the echo and a die to end the call.
$rede = $_POST['rede'];
$dados = array();
$resultado = mysqli_query($conexao, "SELECT * FROM evolucao_originacao WHERE rede = {$rede}");
while($valores = mysqli_fetch_assoc($resultado)){
array_push($dados, $valores);
}
echo json_encode($dados);
die();

Codeigniter Post data using AngularJS

I've built CRUD application using Codeigniter + AngularJS
how to post data in code-igniter controller
I am using this function get all POST data
$data = json_decode($this->input->raw_input_stream , TRUE);
But I want specific value using this function but response is NULL
$x = $this->input->input_stream('email', TRUE);
and one more question is how to apply code-igniter form validation
for this $data
Thank You
Please help me
Try following way.
I've assumed your code and provided an example, do the necessary changes as per your need.
Angular Js
console.log("posting data....");
$http({
method: 'POST',
url: '<?php echo base_url(); ?>user/add',
headers: {'Content-Type': 'application/json'},
data: JSON.stringify({name: $scope.name,city:$scope.city})
}).success(function (data) {
console.log(data);
$scope.message = data.status;
});
Controller action
public function add()
{
// Here you will get data from angular ajax request in json format so you have to decode that json data you will get object array in $request variable
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$name = $request->name;
$city = $request->city;
$id = $this->user_model->AddUser($name,$city);
if($id)
{
echo $result = '{"status" : "success"}';
}else{
echo $result = '{"status" : "failure"}';
}
}

Ajax call using angular js

I am a new Angularjs user.I am facing a problem,when i submit a signup form,I have applied validation using AngularJs. At the same time if all the input fields are valid then i have send an $http Ajax call to check the email address,already exist or not.The issue is my php file did not receive email data.
$http({
method : 'POST',
async: false,
url: 'http://localhost/angular/signup/emailcheck.php',
data: { email: $scope.user.email }, // pass in data as strings
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
})
.success(function(data)
{
$scope.info = data;
if($scope.userForm.$valid && $scope.info === '0') {
alert('our form is amazing' + $scope.info);
}
else{
alert('Already exist');
}
}).error(function(response,status)
{
console.log('ERROR HERE'+ status);
});
My Php file code:
$email = $_POST['email'];
$sql = "SELECT * FROM user where username = '".$email."'";
$result = mysql_query($sql);
//fetch tha data from the database
while ($row = mysql_fetch_array($result)) {
....
....
....
....
....
}
I have checked and found that php file did not receive email value at all.
$http({
method : 'POST',
async: false,
url: 'http://localhost/angular/signup/emailcheck.php',
data : $.param($scope.user), // this will definitely wor
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
})
.success(function(data)
{
$scope.info = data;
if($scope.userForm.$valid && $scope.info === '0') {
alert('our form is amazing' + $scope.info);
}
else{
alert('Already exist');
}
}).error(function(response,status)
{
console.log('ERROR HERE'+ status);
});
Try removing http://localhost from url and then see it may be CORS.
Just a guess: your url is pointing to localhost but has no port number, this is unusual, maybe you forgot it?
data: $.param({
email:$scope.user.email
})
Or this way: (modify the php)
Angular HTTP post to PHP and undefined
I have just found that in php file,
$_POST or $_GET will not work, to receive data.
Use the following:
$data = file_get_contents("php://input");
$objData = json_decode($data);
$email = $objData->email;
In my case it works.

Categories