I try to post json with a form using slim.
If I use a rest api, it works. I set this as the body :
{
"url": "http://link.com"
}
Posting to 'api/generate' :
<?php
use Shorty\Models\Link;
use Shorty\Presenters\ErrorPresenter;
use Shorty\Presenters\LinkPresenter;
$app->post('/api/generate', function () use ($app) {
$payload = json_decode($app->request->getBody());
if(/*empty($payload) ||*/ !isset($payload->url) || empty(trim($payload->url))){
$app->response->setStatus(400);
return $app->response->write(
new ErrorPresenter('1000', 'A URL is required.')
);
}
if(!filter_var($payload->url, FILTER_VALIDATE_URL)){
$app->response->status(400);
return $app->response->write(
new ErrorPresenter('1001', 'A valid URL is required.')
);
}
$app->response->setStatus(201);
$link = Link::where('url', $payload->url)->first();
if($link){
return $app->response->write(
new LinkPresenter($link)
);
}
$newLink = Link::create([
'url' => $payload->url
]);
$newLink->update([
'code' => $newLink->generateShortCode($newLink->id)
]);
return $app->response->write(
new LinkPresenter($newLink)
);
});
It returns what is expected :
{"url":"http:\/\/link.com","generated":{"url":"http:\/\/localhost:200\/phpacademy\/shorty\/public\/a","code":"a"}}
But I want to send the json through a form. If use this :
<form id='userForm'>
<input type="text" name="url">
<input type="submit" value="Get link!">
</form>
<!-- where the response will be displayed -->
<div id='response'></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js "></script>
<script>
$(document).ready(function(){
$('#userForm').submit(function(){
// show that something is loading
$('#response').html("<b>Loading response...</b>");
/*
* 'post_receiver.php' - where you will pass the form data
* $(this).serialize() - to easily read form data
* function(data){... - data contains the response from post_receiver.php
*/
$.ajax({
type: 'POST',
url: 'api/generate',
data: $(this).serialize()
})
.done(function(data){
// show the response
$('#response').html(data);
})
.fail(function() {
// just in case posting your form failed
alert( "Posting failed." );
});
// to prevent refreshing the whole page page
return false;
});
});
</script>
</body>
</html>
It is not working. I get {"error":{"code":"1000","message":"A URL is required."}}
. But I see that "url=http%3A%2F%2Flink.cok" have been posted.
I needed to send json, but json as "name:value", not the default "name: name, value: value". So I found that :
var data = { };
$.each($('form').serializeArray(), function() {
data[this.name] = this.value;
});
data = JSON.stringify(data);
I'm building a data object, with each properties as "name:value". Then parse the object into a string.