Using the Laravel framework, I made a few functions to generate shortened urls, the function works (almost), I have to do the ajax call twice to return the shortened url.
First ajax call receives a 500 error.
And here's the successful call the second time:
I'm confused how a function can work (but not really) at the same time.
EDIT (additional info):
/shorten is used for routing:
Route::post('/shorten', array('uses' => 'UrlController@shorten'));
functions:
Which further calls the shorten function in the UrlController:
public function shorten(){
header('Content-type: text/plain');
$long_url = $_POST['url'];
$link = Link::checkOrShorten($long_url);
return $link->short_url;
}
Ajax:
$(function() {
$('#litlingit').click(function(){
$.ajax({
type: "POST",
data: { url: $('input[name="long_url"]').val() },
dataType: "text",
url: "/shorten"
}).done(function( data ){
$('input[name="long_url"]').val('http://litl.it/'+data);
});
});
});
Module:
public static function checkOrShorten($long_url)
{
$link = new Link;
$link->users_id = NULL;
if (Auth::check())
{
$link->users_id = Auth::user()->id;
}
$link->long_url = $long_url;
$query = DB::select("select short_url from links where long_url = '$long_url'");
if ($query)
{
foreach ($query as $links)
{
$link->short_url = $links->short_url;
}
$url_id = DB::select("select id from links where long_url = '$long_url'");
DB::table('users_links')->insert(array('link_id' => $url_id[0]->id, 'user_id' => $link->users_id, 'privacy' => 0));
}
while(is_null($link->short_url))
{
$link->short_url = str_random(4);
$query = DB::select("select short_url from links where short_url = '". $link->short_url ."'");
if(!$query)
{
$link->save();
$url_id = DB::select("select id from links where short_url = '$link->short_url'");
DB::table('users_links')->insert(array('link_id' => $url_id, 'user_id' => $link->users_id, 'privacy' => 0));
}
}
return $link;
}