Get Ajax Values in AngularJs - javascript

I'm passing the values in angularjs using $http to a url but I'm not able to get the values in AJAX file.
The following is my JS code:
$scope.insert = function() {
var name = $scope.name;
var pass = $scope.password;
alert(name);
alert(pass);
$http({
url : 'http://localhost/anguler/ajax.php?act=abc',
data : {"pass":pass,"name":name},
type : 'POST'
}).success (function(resp){
alert(resp);
});
}
And this is the code in ajax.php:
if(isset($_REQUEST['act']) == 'abc')
{
$user_name=$_POST['name'];
$password=$_POST['pass'];
echo $user_name.'**'.$password;
}
I'm not getting the values for $user_name and $password.

Angular $http has another options, check it out:
$http({
method: 'POST',
url: 'http://localhost/anguler/ajax.php?act=abc',
data: {
"pass": pass,
"name": name
}
})
Not type, but method. https://docs.angularjs.org/api/ng/service/$http#post
Also, you can try to check passing values like
isset($_REQUEST['pass']) == 'pass') { do stuff; }

Related

Laravel 6 Error - Undefined property: App\Http\Controllers\GetContentController::$request

I am trying to send form data including files (if any) without form tag via Ajax request. However, I am getting the following error message
Undefined property: App\Http\Controllers\GetContentController::$request
Here are my codes
Controller
public function GetContentController($params){
$CandidateFullName = $this->request->CandidateFullName;
$CandidateLocation=$this->request->CandidateLocation;
//inserted into database after validation and a json object is sent back
Web.php
Route::match(['get', 'post'], '{controller}/{action?}/{params1?}/{params2?}', function ($controller, $action = 'index', $params1 = '',$params2 = '') {
$params = explode('/', $params1);
$params[1] = $params2;
$app = app();
$controller = $app->make("\App\Http\Controllers\\" . ucwords($controller) . 'Controller');
return $controller->callAction($action, $params);
})->middleware('supadminauth');
Blade
<input type="text" id="CandidateFullName" name="CandidateFullName" class="form-control">
<input type="text" id="CandidateLocation" name="CandidateLocation" class="form-control">
<button id="final_submit">Submit</button>
<script>
$('#final_submit').click(function(e){
e.preventDefault();
var data = {};
data['CandidateFullName']= $('#CandidateFullName').val();
data['CandidateLocation']=$('#CandidateLocation').val();
submitSaveAndNext(data)
});
function submitSaveAndNext(data){
//console.log(data);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': '{{csrf_token()}}'
}
});
$.ajax({
type : "POST",
url : '{{url("GetContent/submitContent")}}', //GetContentController ,but without Controller in the end
dataType : "json",
contentType : "application/json",
data : JSON.stringify(data),
success : function(response){
//console.log("response ",response);
if(response.message=="success"){
swal({
title:"Success",
type: "success",
});
}else{
swal({
title:"Sorry! Unable to save data",
type:"warning"
})
}
},
error:function(xhr, status, error){
swal({
title:"Sorry! Unable to save data",
type:"warning"
})
}
}) //ajax ends
I don't think controller instance in laravel possess the property having request instance, you'll have to type-hint to obtain the object of the request
public function GetContentController($params) {
// $this->request is the issue
$CandidateFullName = $this->request-> CandidateFullName;
$CandidateLocation = $this->request->CandidateLocation;
}
So you can try either of the below-given solutions
// make sure include the Request class into your controller namespace
public function GetContentController($params, Request $request) {
$CandidateFullName = $request->input('CandidateFullName');
$CandidateLocation = $request->input('CandidateLocation');
}
Or use the helper function for request
public function GetContentController($params) {
$CandidateFullName = request('CandidateFullName');
$CandidateLocation = request('CandidateLocation');
}
These links will help you get more details :
https://laravel.com/docs/8.x/requests#accessing-the-request
https://laravel.com/docs/5.2/helpers#method-request

Internal Server Error 500 when creating in laravel using ajax jQuery, wrong variables format from ajax to controller

I'm trying to create a new service option while creating a bill (a bill can have many services), it's like creating a new tag, or category while writing post without reloading, but i have this internal server error 500, i think the problem is in the Controller because it works fine when i comment the create in controller, route and csrf and stuff are checked, thanks for helping me !
In my javascript :
var max_service_id = {{$max_service_id}};
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$("#add_service_button").on("click",function(e){
e.preventDefault();
var service_name = $("input[name=service_name]").val();
var service_category = document.getElementById('service_category').value;
var service_description = $("input[name=service_description]").val();
$.ajax({
type:'POST',
url:'/service/add-in-bill',
dataType: 'json',
data:{
name : service_name,
category_id : service_category,
description : service_description
},
success:function(data){
if (data.message) {
//This is error message
alert(data.message);
}
if (data.success) {
alert(data.success);
var newService = new Option(service_name, max_service_id, false, true);
$('.multipleSelect').append(newService).trigger('change');
max_service_id++;
$("#add_service_div").hide("fast");
}
}
});
})
});
In my controller :
$validator = Validator::make($request->all(), [
'name' => 'required|unique:services',
'category_id' => 'required',
]);
if ($validator->fails()) {
return response()->json(['message'=>$validator->errors()->all()]);
} else {
// It works fine when i comment this, so i think the problem is something about variables from javascript to php stuff
Service::create($request->all());
return response()->json(['success'=>'Create service success !']);
}
//
// I think the problem is in the Controller because it works fine when i comment the "Service::create($request->all());"

Javascript AngularJS: Inner function cannot the variable value of outer function

I am developing ionic hybrid application. I am using $http to get value from server. Next, I will make a cordova sqlite query, inside the cordova query I want to insert my result from $http call from server and result of cordova query into my sqlite database. However, I can't get the value of $http return value in my cordova query. The following is my code:
$http({
method: "post",
url: "http://localhost/php2/get_channel.php",
data: {
user_name: usernameID
},
headers: { 'Content-Type': 'application/json' }
}).success(function(response) {
for(i=0; i<response.length; i++){
var channelNameQuery = "SELECT * FROM chat_friend WHERE channel_id=?"
var channelNamePromise = $cordovaSQLite.execute(db, channelNameQuery, [response[i].ChannelName]).then(function (result){
var ChannelQuery = "REPLACE INTO chat_channel (last_text, usernameID, chat_channel, chat_channel_name) VALUES (?,?,?,?)";
$cordovaSQLite.execute(db, ChannelQuery, [response[i].LastText, usernameID, response[i].ChannelName, result.rows.item(0).UserName]);
})
}
}).error(function(response) {
console.log(response);
console.log("failed");
});
I can't get response[i].LastText and response[i].ChannelName value inside $cordovaSQLite.execute() function.
Sorry for my poor language.
The data you recive is mapped on response.data. Try looping thru your data by using angular.forEach(). Remember that response is mostly a object so you cant get response.length here. Please take a look at the $http AngularJS documentation.
$http({
method: "post",
url: "http://localhost/php2/get_channel.php",
data: {
user_name: usernameID
},
headers: { 'Content-Type': 'application/json' }
}).success(function(response) {
angular.forEach(response.data, function (data) {
var channelNameQuery = "SELECT * FROM chat_friend WHERE channel_id=?"
var channelNamePromise = $cordovaSQLite.execute(db, channelNameQuery, [data.ChannelName]).then(function (result){
var ChannelQuery = "REPLACE INTO chat_channel (last_text, usernameID, chat_channel, chat_channel_name) VALUES (?,?,?,?)";
$cordovaSQLite.execute(db, ChannelQuery, [data.LastText, usernameID, data.ChannelName, result.rows.item(0).UserName]);
})
});
}).error(function(response) {
console.log(response);
console.log("failed");
});

How to change location and refresh page in angular js

I have a function :
$scope.insert = function(){
var data = {
'username' : $scope.username,
'password' : $scope.password,
'nama_lengkap' : $scope.nama_lengkap
}
$http({
method: 'POST',
url: './sys/mac.php',
data : data
}).then(function(response){
return response.data;
});
}
and the function work perfectly, but i want my page change to datalist and refresh datalist after insert() true. my function insert() run in the route "localhost/learn/#!/administrator" so i want it change to route "localhost/learn/#!/" after insert() true. i used location.href='#!/' but it not work for refresh datalist automaticaly, just change location.
If you want to update an object from a service call, you can do the following. I have added an onError function too, to help with debugging.
Tip: Research adding service calls into a Service that AngularJS framework provides. It helps for writing maintainable and structured code.
$scope.objectToUpdate;
$scope.insert = function(){
var data = {
'username' : $scope.username,
'password' : $scope.password,
'nama_lengkap' : $scope.nama_lengkap
}
$http({
method: 'POST',
url: './sys/mac.php',
data : data
}).then(function(response){
$scope.objectToUpdate = response.data.d;
}, function(e){
alert(e); //catch error
});
}
Optional Service
Below is an example of how to make use of Angular Services to make server calls
app.service('dataService', function ($http) {
delete $http.defaults.headers.common['X-Requested-With'];
this.getData = function (url, data) {
// $http() returns a $promise that we can add handlers with .then() in controller
return $http({
method: 'POST',
url: './sys/' + url + '.php',
dataType: 'json',
data: data,
headers: { 'Content-Type': 'application/json; charset=utf-8' }
});
};
});
Then call this service from your controller, or any controller that injects DataService
var data = {
'username' : $scope.username,
'password' : $scope.password,
'nama_lengkap' : $scope.nama_lengkap
}
dataService.getData('mac', data).then(function (e) {
$scope.objectToUpdate = e.data.d;
}, function (error) {
alert(error);
});

Sending JS array via AJAX to laravel not working

I have a javascript array which I want to send to a controller via an ajax get method.
My javascript looks like this:
var requestData = JSON.stringify(commentsArray);
console.log(requestData);
//logs correct json object
var request;
request = $.ajax({
url: "/api/comments",
method: "GET",
dataType: "json",
data: requestData
});
I can tell that my requestData is good because I am logging it and it looks right.
and the controller is being accessed correctly (i know this because I can log info there and I can return a response which I can log in my view after the response is returned).
when trying to access requestData I am getting an empty array.
My controller function that is called looks like:
public function index(Request $request)
{
Log::info($request);
//returns array (
//)
//i.e. an empty array
Log::info($request->input);
//returns ""
Log::info($_GET['data']);
//returns error with message 'Undefined index: data '
Log::info(Input::all());
//returns empty array
return Response::json(\App\Comment::get());
}
And I am getting back the response fine.
How can I access the requestData?
Dave's solution in the comments worked:
Changed ajax request to:
request = $.ajax({
url: "/api/comments",
method: "GET",
dataType: "json",
data: {data : requestData}
});
This is how push item in an array using jQuery:
function ApproveUnapproveVisitors(approveUnapprove){
var arrUserIds = [];
$(".visitors-table>tbody>tr").each(function(index, tr){
arrUserIds.push($(this).find('a').attr('data-user-id'));
});
$.ajax({
type:'POST',
url:'/dashboard/whitelistedusers/' + approveUnapprove,
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: {data : arrUserIds},
success:function(data){
alert(data.success);
},
error: function(e){
//alert(e.error);
}
});
}
And this is how I access them in my controller
//Approve all visitors
function ApproveAllWhitelistedUsers(Request $request){
$arrToSend = request('data');
foreach ($arrToSend as $visitor) {
$vsitor = User::findOrFail($visitor);
$vsitor->update(['is_approved'=> '1']);
}
return response()->json(['success'=>'Accounts approved successfully!']);
}

Categories

Resources