Api sending data from backend to frontend - laravel

I have made an web app where the users can question and answer. By fetching the data from database, i send the required data to frontend using JSON. Here is the controller.
public function addquestion(Request $request)
{
if($request->Ajax())
{
if (Auth::check())
{
$question = new Question();
$question->question=$request->question;
$question->save();
$addq_id=new QuestionUser();
$addq_id->q_id=$question->id;
$addq_id->user_id = Auth::user()->id;
$addq_id->save();
echo json_encode(array('status'=>TRUE,'question'=>$request->question));die;
}
else
{
echo json_encode('notloggedin');die;
}
}
}
and here is jquery and ajax:
$(document).on('click','.addquestion',function(e)
{
e.preventDefault();
var question = $(this).prev().val();
$.ajax({
type:"POST",
url: "{{url('/music/addquestion')}}",
data: {
"_token": "{{ csrf_token() }}",
"question": question
},
success: function (data) {
var res = $.parseJSON(data);
if(res.status == true)
{
window.location.reload();
}
else if(res == 'notloggedin')
{
alert('You must login first!');
}
}
});
});
I also used the facebook api and google api for authentication. But, here i am confused on what is building your own api mean. Is my this app an api? I have read more of the articles that it is the interface between backend and frontend?

Related

Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException: The GET method is not supported for this route. Supported methods: POST. 405

My Laravel API is hosted on godaddy and I am call that API from localhost. Here is
$.ajax({
url: 'https://example.com/api/ali',
method: 'POST',
data: {
image: dataURL,
patientname: $('.patientname').attr('patientname'),
phone: phonenum,
mrid: $('.patientmrid').attr('mrid'),
},
success: function(response) {
$(".btnsave").text('Send message');
if(response == "success"){
$('.alert-success').fadeIn(300).delay(5000).fadeOut(1000);
}else if(response == "notsaved"){
$('.alert-danger').fadeIn(300).delay(5000).fadeOut(1000);
}else if(response == "notsent"){
$('.alert-danger').fadeIn(300).delay(50000).fadeOut(1000);
}
},
error: function() {
$('.alert-danger').fadeIn(300).delay(50000).fadeOut(1000);
}
});
Following is my code of API hosted on different domain
Route::post('/ali', function(Request $request) {
$img = $request->image;
$mrid = $request->mrid;
$phone = $request->phone;
$patientname = $request->patientname;
// my code
if(str_starts_with($response, 'OK')){
if($success){
return "success";
}else{
return "notsaved";
}
}else{
return "notsent";
}
});
I have ssl certificate installed on my godaddy domain. When I call this API using 40% of the time I get successful response and 60% of the time I get status code 405, even if I send exact same data. If there was a problem then why it's not showing me error all the time? I have tried all possible solution on internet related to this error.

CSRF token mismatch while uploading image using ajax in CakePHP 3.6

I have tried
class UsersController extends AppController
{
public function beforeFilter(Event $event)
{
$this->getEventManager()->off($this->Csrf);
}
public function ajaxEdit($id = null)
{
$this->autoRender = false;
debug($id);
debug($this->request->getData());
}
And I am using ajax code
$(document).ready(function(){
$('#user-profile').change(function(){
$('.loader-body').show();
var form = $('#user-profile-image')[0];
var formData = new FormData(form);
var tutorial_id = $('#user-file-id').val();
$.ajax({
url :"/users/ajax-edit/"+tutorial_id,
method:"POST",
data:formData,
contentType:false,
cache: false,
processData:false,
success:function(data){
let parseData = $.parseJSON(data);
if (parseData.status === true) {
location.reload();
var value = parseData.url;
console.log(value);
} else {
alert(parseData.message);
}
}
});
});
});
I have followed help from these links
CakePHP ajax CSRF token mismatch
2 https://book.cakephp.org/3.0/en/controllers/components/csrf.html
Getting CSRF token mismatch (see attached image)
https://i.stack.imgur.com/FsVZu.png
First of all if your are using POST method in your ajax call then you should send tutorial_id as data instead of sending it in the url.
You can resolve this by sending you CSRF token through a special X-CSRF-Token header in your ajax call.
https://book.cakephp.org/3.0/en/controllers/components/csrf.html
beforeSend: function (xhr) {
xhr.setRequestHeader('X-CSRF-Token', $('[name="_csrfToken"]').val());
},
OR
You can disable CSRF component[Not recommended by the Cakephp] for your ajax action like:
public function beforeFilter(Event $event) {
if (in_array($this->request->action, ['ajaxEdit'])) {
$this->eventManager()->off($this->Csrf);
}
}

How to implement ajax in laravel

I am trying to implement ajax in laravel framework, where I am trying to check for the availability for the username, I was able to implement the same via core php but not able to get through laravel 4.
1) You have to define a method in your controller (i.e UserController)
public function postEmail()
{
$userCount = User::where('email', '=', Input::get('email'))->count();
if ($userCount == 0)
{
return "true";
} else {
return "false";
}
}
2) In your registration form you have to do jQuery validation like this to make a remote call on Controller method
$(document).ready(function() {
$('#registration-form').validate({
rules: {
email: {
required: true,
email: true,
remote: {
type: "POST",
url: '/user/email'
}
}
},
messages: {
email: {
remote: "The email has already been taken!"
}
},
success: function(date) {
console.log(data);
}
});

Bind event after login

I have made a filter called auth that check if user is logged. If is not logged it redirect on the main page but if is a call ajax? I just checked if is it. If it is i just send an json status "no-log". Now i received my json response "no-log" on my client and i would like open a modal for ask login and password. The solution that i thougth was put easily for each ajax request an if statement to check if the response status is "no-log" and show the function of modal. BUT OF COURSE is not good for future update, I'm looking for a good solution where i can bind this event and if i want on the future add other status. Any suggest?
Route::filter('auth', function()
{
if (Auth::guest()) {
if ( !Request::ajax() ) {
Session::put('loginRedirect', Request::url());
return Redirect::to('/');
} else {
$status = "no-log";
return json_encode(array('status' => $status));
}
}
});
A example of call ajax
$(document).on("click", ".delete", function() { // delete POST shared
var id_post = $(this);
bootbox.confirm("Are you sure do want delete?", function(result) {
if (result) {
$.ajax({
type: "POST",
url: '/delete_post/' + USER,
data: { id_post: id_post.attr('id') },
beforeSend: function(request) {
return request.setRequestHeader("X-CSRF-Token", $("meta[name='token']").attr('content'));
},
success: function(response) {
if (response.status == "success") {
id_post.parents('div.shared_box').fadeOut();
}
},
error: function(){
alert('error ajax');
}
});
} else {
console.log("close");
}
});
});
After 10 days of exploring an idea I found a way to override ajax comportment:
It just need you replace every $.ajax() by a custom one.
If I re-use your code:
$(document).on("click", ".delete", function() { // delete POST shared
var id_post = $(this);
bootbox.confirm("Are you sure do want delete?", function(result) {
if (result) {
myCustomAjax({ // In place of $.ajax({
type: "POST",
...
Then this custom function allow you to add some action before or after each ajax callback:
For instance checking the JSON return value in order to decide if I trigger the success callback or I show a warning:
function myCustomAjax(options) {
var temporaryVariable = options.success;
options.success = function (data, textStatus, jqXHR) {
// Here you can check jqXHR.responseText which contain your JSON reponse.
// And do whatever you want
// If everithing is OK you can also decide to continue with the previous succeed callback
if (typeof temporaryVariable === 'function')
temporaryVariable(data, textStatus, jqXHR);
};
return $.ajax(options);
}
If you return a 401 for all not loggedin requests, you can use $.ajaxSetup to handle all ajax errors in your application.
$.ajaxSetup({
error: function(jqXHR, exception) {
if (jqXHR.status == 401) {
window.location = 'your-login-page';
}
}
});

Ajax simple login

I have this simple Ajax code, my question is only, what does data.logged return, and what i need to have in the logged.php file...
I'm new to ajax, sorry for the dumb question...
$.ajax('logged.php', {
data: {
login: login,
pass: pass
},
success: function(data)
{
if (data.logged)
{
setTimeout(function() {
document.location.href = 'index.php'
}, 2000);
}
else
{
setTimeout(function() {
formLogin.clearMessages();
displayError('Utilizador ou password errados');
}, 2000);
}
},
error: function()
{
formLogin.clearMessages();
displayError('Error while contacting server, please try again');
}
});
On the client side, adding dataType : 'json' worked for me.
$.ajax('handler.php', {
data: {
login: login,
pass: pass
},
dataType : 'json',
success: function(data)
{
//code here
}
//more code here
}
And then on the server side:
$user = $_GET['login'];
$pass = $_GET['pass'];
$result = array();
if( /* login logic here */) {
$result['logged'] = 'true';
} else {
$result['logged'] = false;
}
header('Content-type: application/json');
echo json_encode($result);
That's a jQuery AJAX request which will be expecting responseText in JSON format. In this case, it seems like the JSON returned by your PHP file only needs to have a single property logged which will be either true or false depending on whether or not the login was successful.

Resources