Here are some of the steps I recommend:
Below is some code example that shows some of the relevant sections I use to manage comment postings on a project. Basically I'm binding a click event to a comment container, then posting a message to the server, using AJAx, to see if the user is logged in to post comments. If the user is logged in, I post another AJAX request to send the comment to the server. If user is not logged in, then I show the login form to the user.
Hopefully the example could be beneficial to you:
Jquery code that binds click event and make AJAX calls to the server:
/**
* Manages site comments. Makes sure user is logged in before posting new comments and replies
*
* @author: Jorge Garifuna <[email protected]>
* @date 2/9/14
*
* @param bool isLoggedInUrl
* @param string baseCommentUrl
* @param string loginUrl
* @param string modelTitle
* @param string waitMessage
* @param string errorMessage
*/
function manageComments(isLoggedInUrl, baseCommentUrl, loginUrl, modelTitle, waitMessage, errorMessage) {
// requesting to reply to comment. Check if user is logged in to show reply form. If user not login, prompt to login before replying.
$('.comments-container .comment-detail .comment-reply').on('click', function(e) {
e.preventDefault();
var replyContainer = $(this).closest('.container').siblings('.reply-form-container');
if (replyContainer.is(':visible')) { // hide form
replyContainer.hide();
} else { // show reply form
var itemId = $(this).children('a').first().data('item-id');
var recordType = $(this).children('a').first().data('record-type');
var parentId = $(this).children('a').first().data('parent-id');
// call server to check if user is logged in
isUserLoggedIn(isLoggedInUrl, function(data) {
if (data == 1) { // get comment reply form
// build request url
var formUrl = baseCommentUrl + '/' + itemId + '/' + recordType + '/' + parentId;
// make the ajax call
makeAjaxGetCall(formUrl, function(data) {
if (data == 'error') {
alert(errorMessage);
} else {
// hide all open reply forms
$('.comments-container .comment-detail .reply-form-container').hide();
// show this new reply form
replyContainer.html(data);
replyContainer.show();
}
});
}
else { // get login screen
loginForm(loginUrl, modelTitle, waitMessage, errorMessage)
}
});
}
});
}
/**
* Checks if user is logged in by calling server with given URL via AJAX
*
* @author: Jorge Garifuna <[email protected]>
* @date 2/9/14
*
* @param string url
* @param object callback
*/
function isUserLoggedIn(url, callback) {
makeAjaxGetCall(url, callback);
}
/**
* Makes AJAX call to server using GET method
*
* @author: Jorge Garifuna <[email protected]>
* @date 2/9/14
*
* @param string url
* @param object callback
*/
function makeAjaxGetCall(url, callback) {
url = getProperUrlForProtocal(url);
$.ajax({
type: "GET",
url: url,
dataType: "html",
success: function(data) {
callback(data);
},
error: function() {
callback(0);
}
});
}
/**
* Makes AJAX call to server using POST method
*
* @author: Jorge Garifuna <[email protected]>
* @date 2/9/14
*
* @param string url
* @param object callback
*/
function makeAjaxPostCall(url, callback, data) {
url = getProperUrlForProtocal(url);
$.ajax({
type: "post",
url: url,
data: data,
dataType: "html",
success: function(data) {
callback(data);
},
error: function() {
callback('error');
}
});
}
Controller that receives the user request and calls the model when appropriate to save the comment to the database:
/**
* Add comment
*
* @author Jorge Garifuna <[email protected]>
* @date 2/9/14
*
* @param string $desireType
*
* @return void
*/
public function actionAddComment($itemId, $recordType, $parentId = null)
{
$userInput = Input::all();
$validationRules = Comment::$commentValidations;
$validator = Validator::make($userInput, $validationRules);
if ($validator->fails())
{ // validation failed
Session::flash(CartController::ERROR_MESSAGE_KEY, Lang::get('garimp3.form_validation_failed_message'));
return Redirect::back()
->withErrors($validator)
->withInput();
}
switch ($recordType)
{
case UserProductDesire::RECORD_TYPE_BRAND: // @todo: fix for brand
$result = Comment::addPublicProductComment($userInput, $itemId, $recordType, $parentId);
break;
default:
$result = Comment::addPublicProductComment($userInput, $itemId, $recordType, $parentId);
break;
}
if ($result['success'])
{
Session::flash(CartController::SUCCESS_MESSAGE_KEY, Lang::get('garimp3.account_vendor_brand_saved_success_header'));
}
else
{
Session::flash(CartController::ERROR_MESSAGE_KEY, $result['error']);
}
return Redirect::back();
}
Model that actually saves the comment to the database:
/**
* Add product comment
*
* @param int|null $productId
*
* @author Jorge Garifuna <[email protected]>
* @date 1/24/14
*
* @return object|null
*
*/
static public function addPublicProductComment($userInput, $itemId, $recordType, $parentId)
{
$result = array('success' => false, 'errors' => array(), 'warning' => array());
$item = null;
$isProduct = false;
if ($recordType === UserProductDesire::RECORD_TYPE_PRODUCT)
{
$item = User::getProduct($itemId);
$isProduct = true;
}
else if ($recordType === UserProductDesire::RECORD_TYPE_BRAND)
{
$item = User::getBrand($itemId);
}
if (!$item)
{
$result['errors'][] = Lang::get('garimp3.error_could_not_locate_product');
}
else
{
$fieldsArray = array_intersect_key($userInput, Comment::getFields());
$fieldsArray[User::USER_ID_FOREIGN_KEY_FIELD_NAME] = User::getLoggedInUserId();
if ($isProduct)
{ // product
$brandId = $item->brand_id;
$productId = $item->id;
}
else
{ // brand
$brandId = $item->id;
$productId = null;
}
$fieldsArray[Product::PRODUCT_ID_FOREIGN_KEY_FIELD_NAME] = $productId; // product id
$fieldsArray[Brand::BRAND_ID_FOREIGN_KEY_FIELD_NAME] = $brandId; // brand id
$fieldsArray[Utils::IP_FIELD_NAME] = User::getUserIp(); // save ip address
$fieldsArray[Utils::LOCATION_DATA_FIELD_NAME] = Utils::getIpLocationData($fieldsArray[Utils::IP_FIELD_NAME]); // save location data
$fieldsArray[Utils::ACTIVE_FIELD_NAME] = 1;
$fieldsArray[Utils::PUBLISHED_FIELD_NAME] = 1;
$fieldsArray[Utils::PARENT_ID_FIELD_NAME] = $parentId;
$fieldsArray['published_date'] = date('Y-m-d H:i:s');
$record = new Comment($fieldsArray);
if (!$record->save())
{ // error saving
$result['errors'] = Lang::get('garimp3.error_saving_user_data_message');
}
else
{ // success
$result['success'] = true;
if (empty($parentId))
{ // new parent comment
$eventExtra = 'comment id: ' . $record->id;
$event = EventsHandler::USER_ACCOUNT_COMMENT_ADD;
}
else
{ // reply
$eventExtra = 'comment id: ' . $record->id . ', reply to: ' . $parentId;
$event = EventsHandler::USER_ACCOUNT_COMMENT_REPLY;
}
Event::fire($event, array('item' => array('extra' => $eventExtra, 'brandId' => $brandId, 'productId' => $productId)));
}
}
return $result;
}
Well, you'd bind a function to the 'change' event using jQuery. That function would use the standard jQuery ajax function along with whatever data you grab to send to some route/url on your site using JSON, which you can use the standard Input::get() laravel function to get and process/store in your controller method.
Hi guys!
Thanks a lot for your answers! I got the solution thanks to jgarifuna's code files!
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community