Slim4 PUT and DELETE not recognized when called in the browser - slim

*According to the documentation https://www.slimframework.com/docs/v2/routing/put.html and https://www.slimframework.com/docs/v4/middleware/method-overriding.html I can mimic PUT or DELETE request in Slim4 by adding _method input and by adding Method Overriding Middleware
after the routing middleware. For some reason Chrome does not cooperate with me.
So here is my code:
routes.php:
$app->get('/dashboard', \App\Action\Dashboard::class);
$app->delete('/dashboard', function(Request $request, Response $response ) {
$response->getBody()->write("DELETING");
return $response;
});
$app->put('/dashboard', function(Request $request, Response $response ) {
$response->getBody()->write("ADDING");
return $response;
});
$app->post('/dashboard', function(Request $request, Response $response ) {
$response->getBody()->write("UPDATING");
return $response;
});
middleware.php
use Slim\App;
use Slim\Middleware\ErrorMiddleware;
use Slim\Views\TwigMiddleware;
use Slim\Middleware\MethodOverrideMiddleware;
return function (App $app) {
$app->addBodyParsingMiddleware();
$app->add(TwigMiddleware::class);
$app->addRoutingMiddleware();
$app->add(new Slim\Middleware\MethodOverrideMiddleware);
$app->add(ErrorMiddleware::class);
};
get('/dashboard', ...) displays a simple HTML:
<form action="/dashboard" method="post">
<input type="hidden" name="_METHOD" value="PUT"/>
<button type="submit">Send PUT request</button>
</form>
<form action="/dashboard" method="post">
<input type="hidden" name="_METHOD" value="DELETE"/>
<button type="submit">Send DELETE request</button>
</form>
Regardless which button I press, I got the Unexpected error:
POST header
Surprisingly, when I Chrome ARC to simulate PUT/DELETE requests, proper response is returned. I'm pulling my hairs out because of this. Can anybody show me what I did wrong and why my client (Chrome) is so stubborn?
Thank you in advance for any tip(s).

Related

Laravel - Prevent form resubmission on refresh

How can I prevent my form from resubmitting when I refresh the page. Solutions I've found suggest a redirection, which I am using.
The form in view admin.enrollform.blade.php:
<form id="enrollform" class="form-horizontal" role="form" method="post"
enctype="multipart/form-data"
action="{{route('storeStudent', ['site' => $site->site_url, 'lang' => $lang] )}}">
<input type="visible" name="_token" id="_token" value="{{ csrf_token() }}"/>
...
</form>
The laravel controller:
public function store(Request $request, $site, $lang = null)
{
....
return view('admin.enrollform', [
'message' => $message
]);
}
If successful, the controller returns a view, which points to the same page. So the same page is loaded again, with a message. And the form is empty.
However if I click refresh at this point, the form submits again. I would like for it just refresh the page, with or without the message it had received from the controller.
Is there any way for me to use the CSRF token to validate this? From what I understand the CSRF token only validates if the session is valid, and has nothing to do with the form itself.
Thanks.
Use return back()
return back()->with(['message' => $message]);

Amp-form does not redirect to another page

I have one input bar which must redirect to another https page (contains google-search) on submit. The code of the form is the next:
<form class="navbar-form navbar-left hide-inputs buscadoMovilLine" role="search" target="_blank" action-xhr="https://www.tuotromedico.com/buscadorg.php" action="https://www.tuotromedico.com/buscadorg.php" method="get">
<div class="form-group buscador">
<input class="SearchInputMovil2 inl" type="text" placeholder="Buscar..." class="form-control" name="q">
<button class="inl" type="submit" class="btn btn-default"><i class="fa fa-search lupaBuscarMovilBoton2" aria-hidden="true"></i></button>
</div>
</form>
I have added the amp-form extension too. The official documentation says this:
Redirecting after a submission
amp-form also allows publishers to redirect users to a new page after a submission happens through AMP-Redirect-To response header.
Note that you'd also have to update your Access-Control-Expose-Headers
response header to include AMP-Redirect-To to the list of allowed
headers.
The redirect URL must be absolute HTTPS URL otherwise AMP will throw
an error and redirection won't happen.
https://www.ampproject.org/es/docs/reference/components/dynamic/amp-form
But im not sure how have i to specify that.
I know 2 ways, this is for node:
app.post('/register', function (req, res) {
let form = new formidable.IncomingForm();
form.parse(req, function (err, fields) {
res.setHeader('AMP-Access-Control-Allow-Source-Origin', 'https://example.com/');
if (fields.first_name && fields.last_name) {
res.setHeader('AMP-Redirect-To', 'https://example.com/some-key');
res.status(200).json(fields);
} else {
res.status(400).json({error: 'Please select a size.'});
}
});
and the second, in amp you can use navigateTo()
<form class="proceed__form" method="post" id="requirements-form"
action-xhr="https://localhost:4040/check-requirements"
target="_top"
on="submit-success:AMP.navigateTo(url='https://google.com')"
>
</form>
OR you can get variable from response
(res.status(200).json({message: 'success', navigateTo: domain + '/profile'});)
<form class="proceed__form" method="post" id="requirements-form"
action-xhr="https://localhost:4040/check-requirements"
target="_top"
on="submit-success:AMP.navigateTo(url=event.response.navigateTo)"
>
</form>

Ajax form submit, validate and return success or fail

Searched and browsed the forum and tried many examples of ajax and form submission but can't get anything close to work for what I am trying to achieve. I must admit I've been going in circles for days with this and need someone with a fresh pair of eyes.
I have 2 pages:
page1.php
page2.php
Using Google jquery/1.9.0/jquery.js and developing this locally.
page1.php is as follows (I've omitted the head script and body/html tags for clarity)
$(document).ready(function() {
$('#theForm').submit(function(){
$.ajax({
type: "POST",
url: "page2.php",
data: 'html',
success: function(html){
if(html == 'success'){
$('#address').fadeOut('slow');
$('#done').fadeIn('slow');
}else if(html == 'fail'){
alert('fail');
}
}
});
return false;
});
});
<div id="address">
<form action="page2.php" method="post" name="theForm">
<input name="checkname" type="text" id="checkname">
<input name="Proceed" type="submit" id="submit" value="Next Page" />
</form>
</div>
<div id="done">
That Worked!
</div>
Page2.php
Has a mysql query that checks the database for the checkname and echoes 'success' or ' fail' depending upon the result. The query runs fine and is not showing any error.
When the form is submitted page2.php loads and just shows 'success' in the browser.
Firebug also shows success under both response and html. There are no errors within firebug.
I basically want page1.php to stay and for the #address div to hide and the #done div to show when success is passed from page2.php
Hope someone can help.
Update
I tried this test page:
ajaxone.php
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#theForm').submit(function(){
$.ajax({
type: "POST",
url: "ajaxtwo.php",
data: 'html',
success: function(html){
if(html == 'success'){
$('#address').fadeOut('slow');
$('#payment').fadeIn('slow');
alert('ok');
}else if(html == 'fail'){
alert('fail');
}
}
});
return false;
});
});
</script>
<style type="text/css">
#payment{
visibility:hidden;
}
</style>
<div id="address">
<form action="ajaxtwo.php" method="post" name="theForm" id="theForm">
<p>
<input name="name" type="text" id="name">
</p>
<p>
<input type="submit" name="submit" value="submit">
</p>
</form></div>
<div id="payment">Name is correct</div>
ajaxtwo.php
print_r($_POST);
if($_POST['name'] == 'rob'){
echo 'success';
}else{
echo 'fail';
}
Using the above firebug shows the following error:
Array ( )
Undefined index: name
fail
However, when I remove the ajax call the submit works and the data is passed.
So, am I right to assume that if you do not specify the form variables within the ajax call nothing is posted to the next page?
Update 2
Sorry I'm answering myself here.
It does appear that you need to specify the form data to send within the ajax call.
I've just added:
$('#theForm').serialize();
within the ajax call and now the form submits without an error.
However, this still goes to ajaxtwo.php and does not show the success or fail on the ajaxone.php page.
So my next stage is to get the success or fail to show on ajaxone.php
You need to add id="theForm" in the form tag itself.
Example:
<form action="page2.php" method="post" id="theForm" name="theForm">
I would say, add a and then make jq read the output and then redirect accordingly, or use php to redict based on $success_fail result.

How can I get the echo value from my php script using the JQuery Form Plugin?

I am used to get the echo message of the php script using the jquery ajax success function now I use a plugin but I dont know how to use it
my approach is this but definitely do not work how should the right way? It just go directly to my php script
$(function() {
$('form').ajaxForm(function() {
success: function(data){
$('.new-profile-pic').html(data);
}
});
});
HTML:
<p class="new-profile-pic">
<!--Image should be here-->
</p>
<form enctype="multipart/form-data" action="upload-image.php" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="100000">
<input class="profile-pic-name" name="uploadedfile" type="file">
<input type="submit">
</form>
PHP:
<?php
$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo '<img alt="" src="'.$target_path.'">';
} else{
echo "There was an error uploading the file, please try again!";
}
?>
You need to prevent the default action from occuring.
I believe this post has the answer you are looking for:
How do I submit a form using jquery (ajaxForm plugin) to an external site but not reload to a different page?
You need to use .preventDefault() on the submit event, or get it to return false on the form submit, e.g.:
<form enctype="multipart/form-data" action="upload-image.php" method="post" onsubmit="return false;">

REST Codeigniter, jquery/ajax does not display response

I'm trying to get a helloworld type program working with REST CI/jquery. I've included my (really rudimentary) REST controller, view file and javascript file and am hoping that the error that has eluded me jumps out at you.
Two issues:
The response I get from the server does not get displayed - the screen gets refreshed instead (I know this is some very basic thing I've missed). If I step through the code, I see the display of the result but then, screen gets refreshed. And somehow, I cannot step into my "success" function. Why, oh why?
2.Upon success, I'd like to redirect the user to another url, say, www.google.com. Would I do this in the javascript file? or server side?
Thank you in advance for helping me!
[Added after solving the issue: My problem has nothing to do with REST or Codeigniter. A purely javascript problem]
The REST Controller:
<?php
require APPPATH.'/libraries/REST_Controller.php';
class Myex extends REST_Controller {
function contact_post(){
$result=array();
$fname=$this->post('fname');
$lname=$this->post('lname');
$result['message']="contact_post has your name";
$result['fname']=$fname."XX";
$result['lname']=$lname."YY";
$this->response($result,200);
}
}
?>
The view file:
<?php $this->load->view('includes/header')?>
<div id="input-div">
<form name="cookieform" id="login" method="post">
First Name: <input type="text" name="fname" id="fname" class="text"/>
Last Name: <input type="text" name="lname" id="lname" class="text"/>
<input type="submit" name="submit" value="Submit" id='submit' class="page"/>
</form>
</div>
<div id="resp-div">
response goes here
</div>
<?php $this->load->view('includes/footer')?>
The javascript file:
function postsuccess(output) {
$('#soln-div').html(output.message +'for user '+output.fname+' whose last name is '+output.lname).show('slow');
}
function post_contact() {
$('#submit').click(function(){
var output;
var fdata,res;
var furl=global_siteurl+'/myex/contact';
var fname=$('#fname').val();
var lname=$('#lname').val();
fdata='fname='+fname+'&lname='+lname;
res=$.ajax({
url: furl,
type: 'POST',
dataType: 'json',
data:fdata,
success: function(output) {
postsuccess(output);
}
});
});
}
$(document).ready(function() {
get_contact();
post_contact();
});
You have called your ajax function upon submission of form you can prevent refreshing of page in 2 ways:
(a) Use <input type="button" /> instead of submit call your ajax function on this button or
(b) Use return false; in your success function of ajax request.
You can redirect to any url in javascript using window.top.location = 'url-to-redirect';