I am doing Google Oauth login using Google Api's in Laravel 5.0. I get the data of currently logged in user's email,id_token and now I want to send these data to the controller(SigninController) for calling our own api and get the response back to the front end (signin.blade.php) via an Ajax query . But My Ajax query is not working. I am attaching the codes here .
My Signin.blade.php file's ajax looks like(I have included csrf header) :
$.ajax({
url: '/signin/oauth',
type:"POST",
data: data,
headers: { 'X-CSRF-Token' : token},
success:function(data){
console.log(data);
if(data){
console.log("Success nowwww for ajax expected data!");
// window.location.href = '{{url("/home")}}';
}
else{
console.log("Success ajax ! But not expected data!");
// window.location.href = '{{url("/signup")}}';
}
},error:function(){
alert("error!! ajax failure !!!!");
}
});
My routes.php looks like :
Route::post('/signin/oauth', [
'uses' => 'SigninController#signinProcessOauth',
'as' => 'post_signin_oauth',
]);
In my SigninController's signinProcessOauth function normal "Request for Form" is working but "Request->ajax()" maybe not working . It looks like :
.
.
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
.
.
public function signinProcessOauth(Request $request)
{
$getData = $request->ajax();
if ($getData) {
$authCode = $request['authCode'];
$idToken = $request['idToken'];
$userEmail = $request['userEmail'];
// call the api here and send the above data to the server and process the response like saving the cookie etc
return $authCode; // return according to the response,this will return in ajax success function,right now it is authcode just for testing purpose
}
return "error";
}
Everytime I run the code, I get "error!! ajax failure !!!!" response i.e. ajax's failure function is called . I can't figure it out Where the problem is? Or Is there any other way to to send the datam from view to controller and get back the response to the frontend ?
Thank you for reading such long post patiently . :) :)
Change your url as follow:
url: '{!! route('post_signin_oauth') !!}'
Hope this will work.
In your method $request is not an array, its an object. So you need to use -> to access properties.
Related
I am using the Twilio API for making calls/texting. A user initiates a call on a Single Page Application (with PHP/Symfony 5). I would like to display the status of the call in real time (in progress, finished, ect... via StatusCallbackEvent) as well as the digits once the call is finished.
The application works as follows:
The user initiates a call on the app (with a onClick event)
AJAX request to my controller
The controller makes the call
the API returns StatusCallBack data on another URL linked to another controller
How can I retrieve the data from the API in my AJAX request to display the result to the user ? Knowing that this is a Single Page App...
CallbackStatus goes here:
/**
* #Route("/back/", name="app_back")
*/
public function back (Request $request) : Response
{
// some stuff...
$voiceResponse = new VoiceResponse ();
$response = new Response (
$voiceResponse->asXML(),
Response::HTTP_OK,
['content-type' => 'application/xml']
);
return $response;
}
I want to transfer it here:
$.post({
url : "/makecall/",
data: {
"people" : idPeople
},
dataType : 'json',
success: function (data) {
// Display data here :(
}
});
I hope to have been clear. Thank you for your attention.
I'm making a form that's called by Ajax and trying to configure the form to submit using Ajax. This form is supposed to submit the data through route('ruangrapat.store). But every time I submit the form, it returns 419 status when I don't use csrf_token() in Ajax and if I use the csrf_token() in Ajax. It always returns 500 internal server error. Can someone help me to solve this problem? I've been reading almost every discussion that I found on the internet, but still no answer.
Maybe I missed something important on my code. Please review my code.
//ajax
$(document).ready(function(){
$('#form-ruangrapat').on('submit',function(e){
e.preventDefault();
var formdata=$('#form-ruangrapat').serialize();//should i do this??
//if i should take the value of inputs 1 by 1,please show me the proper way
var token="{!!csrf_token()!!}"
$.ajax({
url:"{{route('ruangrapat.store')}}",
data: {formData:formdata,_token:token},
type:'post',
success:function(result){
$('#result').html(result);
}
});
});
});
//controller
public function store(Request $request)
{
$data = new Ruangrapat();
...
$data->contact = $request->get('contact');
$data->save();
return view('ajax-result.ruangrapat.index')->with('status', 'Ruang rapat baru berhasil ditambahkan!');
//is this return value correct??
}
//route
Route::resource('ruangrapat', 'RuangrapatController');
i had the same problem,419 is matched to the csrf token,when you fixed it,the request go to the server so ,the internal server error 500 say that there is a probleme while storing,so relook into the store function in controller and make sure that all process are correct in the function.
First Recomendation
To make any ajax request, it is recommended to add the CSRF token to the header of the ajax requests
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
As advised by laravel documentation
Second Recomendation
To see what the ajax request is sent, I would advise having the controller return the data to you and see it through the web console.
$(document).ready(function(){
$('#form-ruangrapat').on('submit',function(e){
e.preventDefault();
var formdata=$('#form-ruangrapat').serialize();
var token="{!!csrf_token()!!}";
$.ajax({
url:"{{route('ruangrapat.store')}}",
data: {formData:formdata,_token:token},
type:'post',
dataType:'JSON',
//You can use sucess or done, personally i like more done
}).done(function (data) {
console.log(data)
});
});
});
And in the controller
public function store(Request $request)
{
return response()->json($request->input());
}
Other option is to use the network monitor of the browsers and see the variables that are sent.
I'm trying to send data from my login FORM to backend writen in PHP using POST method.
my Angular code looks like:
$scope.getToken = function(){
// console.log $scope.login to make sure I'm not sending empty data
console.log($scope.login);
$http({
method: 'POST',
url: '../../api/v1/Oauth.php',
data: { 'login' : $scope.login, 'password' : $scope.password }
}).then(function successCallback(response) {
console.log(response);
}, function errorCallback(response) {
console.log(response);
});
};
and after that I try to catch it on my PHP:
if((isset($_POST['login']) AND isset($_POST['password'])))
{
$username = $_POST['login'];
$password = $_POST['password'];
echo $username;
}
else
var_dump($_POST);
This statement always go to else and return empty array.
Can someone advise me what I'm doing wrong or how can I debug this?
Because it looks that I send data fron angular correctly but it didn't come to server.
Thanks
Kind Regards
Andurit
Use this:
json_decode(file_get_contents('php://input'));
Check your network tab in your developer bar. You can see that you send payload data in the http body. That's why the $_POST array is empty.
Some older server side web libraries like Coldfusion/.NET/PHP have issues grabbing a POST BODY by default (which is how $http sends the data).
You can reference How to get body of a POST in php? to learn how to write your PHP in a way that it will accept the current and correct standard of sending data via a post.
To access the entity body of a POST or PUT request (or any other HTTP
method):
$entityBody = file_get_contents('php://input');
Also, the STDIN constant is an already-open stream to php://input, so
you can alternatively do:
$entityBody = stream_get_contents(STDIN);
try:
data: { login : $scope.login, password : $scope.password }
$http.post('url', {login: 'Alex', password: 'qwerty'}).then(function(){},function(){});
First I am conface that I am Newbie to php,
I am using jquery(knockout js) at client side & PHP at server side. my code.
Client side: I am using knockout js(Javascript). to call my PHP service.
My Code:
self.VMSaveEditUserMode = function () {
try {
var params = { "ClientData": [controllerVM_.ClientID(), controllerVM_.VMList[0].ClientName(), controllerVM_.VMList[0].ShortName(), controllerVM_.VMList[0].Address(), controllerVM_.VMList[0].CreatedBy(), controllerVM_.VMList[0].CityName(), controllerVM_.VMList[0].PostalCode(), controllerVM_.VMList[0].ContactEmail(), controllerVM_.VMList[0].ContactPhone(), controllerVM_.VMList[0].IsCorporate()] };
$.ajax({
type: "POST",
url: URL + "index.php/phpService/SaveClient/" + controllerVM_.TokenKey(),
data: JSON.stringify(ko.toJS(params)),
contentType: "application/json",
async: true,
dataType: 'json',
cache: false,
success: function (response) {
},
error: function (ErrorResponse) {
if (ErrorResponse.statusText == "OK") {
}
else {
alert("ErrorMsg:" + ErrorResponse.statusText);
}
}
});
}
catch (error) {
alert("Catch:" + error);
}
}
Server Side My Code, I am using this PHP code to connect with DB.
PHP Code:
public function SaveClient($userToken)
{
$value = json_decode($Clientdata);
echo $value->ClientData[0];
}
*My Question *:
I am not clear on how to POST data in PHP ? I tried with $_POST[''] method as well as many more.
I am using eclipse as a php framework. so, not able to debug it when i post the data.Normally mode i am able to debug my code.but not from remotely.for that i made changes on php.ini file also.
How to get Response of Post Data on php code ?
How to debug via remote post ?
My Request sample:
suppose i use:
For, data: params, only at that time my request format is.
ClientData%5B%5D=4&ClientData%5B%5D=kamlesh&ClientData%5B%5D=KAM&ClientData%5B%5D=Junagadh&ClientData%5B%5D=me&ClientData%5B%5D=SANTA+ROSA&ClientData%5B%5D=76220&ClientData%5B%5D=kamlesh.vadiyatar%40gmail.com&ClientData%5B%5D=9998305904&ClientData%5B%5D=false
For, data: JSON.stringify(ko.toJS(params)),
{"ClientData":["4","kamlesh","KAM","Junagadh","me","SANTA ROSA","76220","kamlesh.vadiyatar#gmail.com","9998305904",false]}
If I understand correctly you need to create a PHP service which is able to receive REST-like requests from client.
In order to do thad you need to access raw POST data. In PHP its being done like this:
$ClientData = file_get_contents('php://input');
You can read more about php://input in the wrappers documentation.
Of course from the client's side the data need to be sent using the POST method and as raw data, i.e. as a string. You can obtain a string from object using JSON.stringify() which you already do.
If you pass an object, it will be converted to string internally by jQuery using query-string format. More on that in the jQuery documentation for $.ajax (the most importatnt options being data and processData).
Just pass the ajax data param as an object, don't convert it into JSON. Then in PHP use $_POST directly.
Use firebug or chrome dev tools to analyze the ajax request and see which data is sent
Use this simple jquery function to accomplish your task
$.ajax({
type: "POST",
url:"scripts/dummy.php",
data:"tbl="+table,
dataType:"json", //if you want to get back response in json
beforeSend: function()
{
},
success: function(resp)
{
},
complete: function()
{
},
error: function(e)
{
alert('Error: ' + e);
}
}); //end Ajax
in PHP use:
if(isset($_POST['ClientData'])){
$client_data = $_POST['ClientData']
}
now $client_data variable should contain the array.
For debugging purpose you can use php's built-in print_r() function. It's pretty handy.
here's is an example:
//make sure it's post request
if(isset($_POST)){
//now print the array nicely
echo "<pre>";
print_r($_POST);
echo "</pre>";
}
My web application does Ajax request to a Codeigniter-php code in a remote server. It works in localhost but not with a specific controller in remote host. It is strange because works in localhost for both controllers.
The request:
$.ajax({
async:true,
type: "POST",
dataType: "json",
url:"/CI/site/index.php/contact/submitContact",
data: "", //data example
success:arrived,
error:problems });
function arrived(data){
var dataJson = eval(data);
}
function problems(){
$("#result").text('Problems.');
}
I check the arrived with log_message. With the next function works fine:
function submitContact(){
log_message('error', 'submitContact. ');
//If data are received
if($_POST){
log_message('error', 'data. [application/controllers/contact.php]');
}
}
However, If I change the request to url:"/CI/site/index.php/control/controlHome", there isn't any log message and the output is the next:
POST http://www.page.com/CI/site/index.php/control/controlHome 500 (Internal Server Error)
The function /application/controllers/control.php is the next:
function controlHome(){
log_message('error', 'controlHome. [application/controllers/control.php]');
//If data are received
if($_POST){
log_message('error', 'data. [application/controllers/control.php]');
}
}
Also I've tried with complete url in the ajax code but the result is the same. Any setting is required?
Check this AJAX csrf protection with codeigniter 2. This solve my same problem
http://aymsystems.com/ajax-csrf-protection-codeigniter-20
UPDATE:
I checked your control.php file on my test server.
if($_POST) { /* i only commented gangway library functions */
} else { /* only replace the load->view with an print_r $data; and its work */ }
And put to comment the gangway library on construct. And control/controlHome works normaly without any error. Check your gangway library THAT's cause error 500.