I have a RESTful API based application with Laravel 4 and Angular.js.
The application's CRUD processes are handled by angularjs $http service.
The Backend Side (Laravel 4):
Routing : app/routes.php
//.....
Route::group(array('prefix' => 'api/v1', 'before' => 'auth.basic'), function()
{
//....
Route::resource('pages', 'PagesController');
//....
});
//.....
Controller : app/controllers/api/PageController.php
<?php
//.....
class PagesController extends BaseController {
//......
public function update($id) {
$page = Page::find($id);
if ( Request::get('title') )
{
$page->title = Request::get('title');
}
if ( Request::get('slug') )
{
$page->slug = Request::get('slug');
}
$page->save();
return Response::json(array(
'error' => false,
'message' => 'Page Updated'),
200
);
}
//......
}
Calling : cURL
This update function can be accessed using cURL method also.
curl -i -X PUT --user admin:admin -d 'title=Updated Title' localhost/laravel/index.php/api/v1/pages/2
Front-end : HTML
<!-- Top Code -->
<!-- From to Add/Edit Pages -->
<form class="form-horizontal" role="form" ng-show="edit" ng-submit="updatePage(entry)">
<!-- Page Title -->
<div class="form-group">
<label class="col-lg-2 control-label">Page Title</label>
<div class="col-lg-4">
<input type="text" class="form-control" value="{{entry.title}}" ng-model="entry.title">
</div>
</div>
<!-- Slug -->
<div class="form-group">
<label class="col-lg-2 control-label">Slug</label>
<div class="col-lg-4">
<input type="text" class="form-control" value="{{entry.slug}}" ng-model="entry.slug">
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<button type="submit" class="btn btn-primary">Update</button>
</div>
</div>
</form>
<!-- Bottom Code -->
Client-side : angularjs
// ......
function pageCtrl($scope, $http, Data) {
//.........
$scope.updatePage = function(entry) {
$http({method: 'PUT', url: Data.root_path + 'api/v1/pages/'+id}).
success(function(data, status, headers, config) {
//
}).
error(function(data, status, headers, config) {
//
});
}
//.........
}
Question:
How can I pass my form data(more than one values) to the $http.put request
here ?
How can I access the PUT request data in Laravel 4 Controller ? Can
I use Input::get() ?
Need some update in your html to get page id to update. Add the following html inside form.
<input type="hidden" ng-model="entry.id" value="entry.id"/>
Then change angular script to,
$scope.updatePage = function(entry) {
$http.put(Data.root_path + 'api/v1/pages/' + entry.id, entry)
.success(function(data, status, headers, config) {
//
})
.error(function(data, status, headers, config) {
//
});
}
And in your Laravel Controller,
public function update($id) {
$page = Page::find($id);
$input = $input = Input::all();
if ( $input['title'] )
{
$page->title = $input['title'];
}
if ( $input['slug'] )
{
$page->slug = $input['slug'];
}
$page->save();
return Response::json(array(
'error' => false,
'message' => 'Page Updated'),
200
);
}
Related
I just need to insert data to table on form submission with the entered inputs.
my Controller,
function create_wish() {
$data = array(
'user_name' => $this->input->post('uname'),
'user_email' => $this->input->post('uemail'),
'user_message' => $this->input->post('umessage')
);
$this->model_wishes->createWish($data);
}
model,
function createWish($data) {
$sql = "INSERT INTO wishes (user_name, user_email, user_wish) VALUES (".$data.user_name.", ".$data.user_email.", ".$data.user_message.")";
$this->db->query($sql);
echo $this->db->affected_rows();
}
view,
<form method="post" action="<?php echo base_url() . "index.php/Welcome/create_wish"?>">
<div class="row">
<div class="form-group col-md-6">
<label for="post-name">Name</label>
<input autocomplete='name' type="text" class="form-control" id="uname" name="uname" required />
</div>
<div class="form-group col-md-6">
<label for="post-email">Email</label>
<input autocomplete='email' type="email" class="form-control" id="uemail" name="uemail" required/>
</div>
</div>
<div class="row">
<div class="form-group col-md-12 margin-b-2">
<label for="post-message">Message</label>
<textarea class="form-control" id="umessage" rows="5" name="umessage"></textarea>
</div>
</div>
<div class="row">
<div class="form-group col-md-12 text-left mb-0">
<button id="btn-create" type="submit" class="button-medium btn btn-default fill-btn">Post Wish</button>
</div>
</div>
</form>
Ajax,
$(document).ready(function () {
$('form').submit(function (event) {
var formData = {
'user_name': $('input[name=uname]').val(),
'user_email': $('input[name=uemail]').val(),
'user_wish': $('input[name=umessage]').val()
};
$.ajax({
type: 'POST',
url: 'http://localhost/CodeIgniterProj/index.php/create_wish',
data: formData,
dataType: 'json',
encode: true
})
.done(function (data) {
console.log(data);
});
event.preventDefault();
});
});
execution of above codes displays an error in console
POST http://localhost/CodeIgniterProj/index.php/create_wish 404 (Not Found)
XHR failed loading: POST "http://localhost/CodeIgniterProj/sender.php".
I tried to fix this and failed. Someone please let me know how to fix this issue, help me on this.
Your URL is missing the controller segment
you should call index.php/[controller]/[method]. Regarding the sender.php i cannot see any call to it. Maybe there are other forms in the markup.
Besides that, the model will not work as expected. Since you are dealing with an array you should change:
... VALUES (".$data.user_name.", ...)
to
...(VALUES (".$data["user_name"].", ...)
If you don't want to use the active record class, you should escape the values in your query.
https://www.codeigniter.com/user_guide/database/queries.html#escaping-queries
I hope it helps.
Use site_url in your ajax url , should be like this
$(document).ready(function () {
$('form').submit(function (event) {
var formData = $(this).serialize();
alert(formData);
$.ajax({
type: 'POST',
url: '<?=site_url('Welcome/create_wish');?>',
data: formData,
dataType: 'json',
}).done(function (data) {
console.log(data.id);
});
event.preventDefault();
});
});
Your controller should be like this :
function create_wish() {
$data = array(
'user_name' => $this->input->post('uname'),
'user_email' => $this->input->post('uemail'),
'user_message' => $this->input->post('umessage')
);
$insert_id = $this->model_wishes->createWish($data);
if($insert_id)
{
$response = array('status' => 'success');
}
else
{
$response = array('status' => 'error');
}
echo json_encode($response);
exit;
}
Your model method createWish should be like this ;
function createWish($data)
{
$this->db->insert('wishes', $data);
return $this->db->insert_id();
}
Ok, this is related to the question I asked a short while ago: Silverstripe/PHP/jQuery - Once form has been filled out by user, prevent it from automatically appearing for each visit
Something has changed since then. Per request of the client, the form must not automatically appear if the user has already filled it out and has thus been placed into SharpSpring. Originally, I was creating a cookie on successful form submission using JavaScript. However, the latest concern is that it's not effective enough as cookies are registered only to certain devices and browsers, and users can clear their cookies at any time.
Essentially, the desired result is to prevent the form from automatically appearing if the user has been registered in SharpSpring (a separate domain) without having to rely on cookies.
Has anyone ever attempted something like this, checking to see if a user has submitted a form to another domain?
For reference, here is the form code I have setup:
<?php
/*
Plugin Name: SharpSpring Form Plugin
Description: A custom form plugin that is SharpSpring-compatible and uses HTML, CSS, jQuery, and AJAX
Version: 1.0
*/
define('SSCFURL', WP_PLUGIN_URL . "/" . dirname(plugin_basename(__FILE__)));
define('SSCFPATH', WP_PLUGIN_DIR . "/" . dirname(plugin_basename(__FILE__)));
function sharpspringform_enqueuescripts()
{
wp_enqueue_script('jquery-src', SSCFURL . '/js/jquery.js', array('jquery'));
wp_enqueue_script('jquery-ui', SSCFURL . '/js/jquery-ui.js', array('jquery'));
wp_enqueue_script('boootstrap', SSCFURL . '/js/bootstrap.js', array('jquery'));
wp_localize_script('sharpspringform', 'sharpspringformajax', array('ajaxurl' => admin_url('admin-ajax.php')));
}
add_action('wp_enqueue_scripts', 'sharpspringform_enqueuescripts');
function sharpspringform_show_form()
{
wp_enqueue_style( 'boilerplate', SSCFURL.'/css/boilerplate.css');
wp_enqueue_style( 'bootstrapcss', SSCFURL.'/css/bootstrap.css');
wp_enqueue_style( 'bookregistration', SSCFURL.'/css/Book-Registration.css');
wp_enqueue_style( 'formstyles', SSCFURL.'/css/styles.css');
?>
<div class="mobile-view" style="right: 51px;">
<a class="mobile-btn">
<span class="glyphicon glyphicon-arrow-left icon-arrow-mobile mobile-form-btn"></span>
</a>
</div>
<div class="slider register-photo">
<div class="form-inner">
<div class="form-container">
<form method="post" enctype="multipart/form-data" class="signupForm" id="browserHangFormPV">
<a class="sidebar">
<span class="glyphicon glyphicon-arrow-left icon-arrow arrow"></span>
</a>
<a class="closeBtn">
<span class="glyphicon glyphicon-remove"></span>
</a>
<h2 class="text-center black">Sign up for our newsletter.</h2>
<p class="errors-container light">Please fill in the required fields.</p>
<div class="success">Thank you for signing up!</div>
<div class="form-field-content">
<div class="form-group">
<input class="form-control FirstNameTxt" type="text" name="first_name" placeholder="*First Name"
autofocus="">
</div>
<div class="form-group">
<input class="form-control LastNameTxt" type="text" name="last_name" placeholder="*Last Name"
autofocus="">
</div>
<div class="form-group">
<input class="form-control EmailTxt" type="email" name="email" placeholder="*Email"
autofocus="">
</div>
<div class="form-group">
<input class="form-control CompanyTxt" type="text" name="company" placeholder="*Company"
autofocus="">
</div>
<div class="form-group submit-button">
<button class="btn btn-primary btn-block button-submit" type="button">SIGN ME UP</button>
<img src="/wp-content/plugins/sharpspring-form/img/ajax-loader.gif" class="progress" alt="Submitting...">
</div>
</div>
<br/>
<div class="privacy-link">
<a href="[privacy policy link]" class="already" target="_blank"><span
class="glyphicon glyphicon-lock icon-lock"></span>We will never share your information.</a>
</div>
</form>
<input type="hidden" id="gatewayEmbedID" value="<?php echo get_option( 'pv_signup_sharpspring_ID' ); ?>" />
<script type="text/javascript">
var embedID = document.getElementById("gatewayEmbedID").value;
var __ss_noform = __ss_noform || [];
__ss_noform.push(['baseURI', 'https://app-3QNAHNE212.marketingautomation.services/webforms/receivePostback/[redacted]']);
__ss_noform.push(['form', 'browserHangFormPV', embedID]);
__ss_noform.push(['submitType', 'manual']);
</script>
<script type="text/javascript" src="https://koi-3QNAHNE212.marketingautomation.services/client/noform.js?ver=1.24" ></script>
</div>
</div>
</div>
<?php
}
function sharpspringform_shortcode_func( $atts )
{
ob_start();
sharpspringform_show_form();
$output = ob_get_contents();
ob_end_clean();
return $output;
}
add_shortcode( 'sharpspringform', 'sharpspringform_shortcode_func' );
The form submission code with generates a cookie using JS:
;
(function ($) {
$(document).ready(function () {
var successMessage = $('.success');
var error = $('.errors-container');
var sharpSpringID = $('#gatewayEmbedID').val();
var submitbtn = $('.button-submit');
var SubmitProgress = $('img.progress');
var formdata = {};
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
submitbtn.click(function (e) {
resetErrors();
postForm();
});
function resetErrors() {
$('.signupForm input').removeClass('error-field');
}
function postForm() {
$.each($('.signupForm input'), function (i, v) {
if (v.type !== 'submit') {
formdata[v.name] = v.value;
}
});
submitbtn.hide();
error.hide();
SubmitProgress.show();
$.ajax({
type: "POST",
data: formdata,
url: '/wp-content/plugins/sharpspring-form/sharpsring-form-submission.php',
dataType: "json"
}).done(function (response) {
submitbtn.show();
SubmitProgress.hide();
if (response.errors) {
error.show();
var errors = response.errors;
errors.forEach(function (error) {
$('input[name="' + error + '"]').addClass('error-field');
})
}
else {
__ss_noform.push(['submit', null, sharpSpringID]);
setCookie('SignupSuccess', 'NewsletterSignup', 3650);
$('#browserHangFormPV')[0].reset();
$('.form-field-content').hide();
successMessage.show();
$('.button-submit').html("Submitted");
}
});
}
});
}(jQuery));
The jQuery code that sets up the form sliding animation and popup feature, as well as checks for the existence of the JS cookie created on successful form submit:
jQuery.noConflict();
(function ($) {
$(document).ready(function () {
//This function checks if we are in mobile view or not to determine the
//UI behavior of the form.
checkCookie();
window.onload = checkWindowSize();
var arrowicon = $(".arrow");
var overlay = $("#overlay");
var slidingDiv = $(".slider");
var closeBtn = $(".closeBtn");
var mobileBtn = $(".mobile-btn");
//When the page loads, check the screen size.
//If the screen size is less than 768px, you want to get the function
//that opens the form as a popup in the center of the screen
//Otherwise, you want it to be a slide-out animation from the right side
function checkWindowSize() {
if ($(window).width() <= 768) {
//get function to open form at center of screen
if(sessionStorage["PopupShown"] != 'yes' && !checkCookie()){
setTimeout(formModal, 5000);
function formModal() {
slidingDiv.addClass("showForm")
overlay.addClass("showOverlay");
overlay.removeClass('hideOverlay');
mobileBtn.addClass("hideBtn");
}
}
}
else {
//when we aren't in mobile view, let's just have the form slide out from the right
if(sessionStorage["PopupShown"] != 'yes' && !checkCookie()){
setTimeout(slideOut, 5000);
function slideOut() {
slidingDiv.animate({'right': '-20px'}).addClass('open');
arrowicon.addClass("glyphicon-arrow-right");
arrowicon.removeClass("glyphicon-arrow-left");
overlay.addClass("showOverlay");
overlay.removeClass("hideOverlay");
}
}
}
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie() {
var user = getCookie("SignupSuccess");
if (user != "") {
return true;
} else {
return false;
}
}
/*
------------------------------------------------------------
Functions to open/close form like a modal in center of screen in mobile view
------------------------------------------------------------
*/
mobileBtn.click(function () {
slidingDiv.addClass("showForm");
slidingDiv.removeClass("hideForm");
overlay.addClass("showOverlay");
overlay.removeClass('hideOverlay');
mobileBtn.addClass("hideBtn");
});
closeBtn.click(function () {
slidingDiv.addClass("hideForm");
slidingDiv.removeClass("showForm");
overlay.removeClass("showOverlay");
overlay.addClass("hideOverlay")
mobileBtn.removeClass("hideBtn");
sessionStorage["PopupShown"] = 'yes'; //Save in the sessionStorage if the modal has been shown
});
/*
------------------------------------------------------------
Function to slide the sidebar form out/in
------------------------------------------------------------
*/
arrowicon.click(function () {
if (slidingDiv.hasClass('open')) {
slidingDiv.animate({'right': '-390px'}, 200).removeClass('open');
arrowicon.addClass("glyphicon-arrow-left");
arrowicon.removeClass("glyphicon-arrow-right");
overlay.removeClass("showOverlay");
overlay.addClass("hideOverlay");
sessionStorage["PopupShown"] = 'yes'; //Save in the sessionStorage if the modal has been shown
} else {
slidingDiv.animate({'right': '-20px'}, 200).addClass('open');
arrowicon.addClass("glyphicon-arrow-right");
arrowicon.removeClass("glyphicon-arrow-left");
overlay.addClass("showOverlay");
overlay.removeClass("hideOverlay");
}
});
});
}(jQuery));
I'm confused by the WordPress code here, rather than SilverStripe, it's not clear in your question which platform you're using.
Basically, if you want something more robust than cookies, you'll need to store the registration in the database and check it there (assuming the registration form is on your site). This means you handle the form submission on your site, send the data to the remote site and check the responses, and if all goes well, save the fact that the user has registered remotely into your database where you can check when deciding whether to show the form or not, next time.
If you don't have access to the registration form, or you want to also notice registrations made independently of your site, then you need to have an API you can query on the remote site in order to see if the user is registered.
I found a sharpspring API, but I'm not sure if it's relevant.
this is my view where there is a form containig a field and a submit button.
<form id="typeheadForm" method="post" class="form-horizontal">
<div class="form-group">
<label class="col-xs-3 control-label">Movie</label>
<div class="col-xs-3">
<input type="text" class="form-control" name="state" id="movie_name" />
</div>
</div>
<input type='submit' name='submit' value='Search' class="btn btn-squared btn-default">
</form>
and below is my controller code
public function actionMovies_all()
{
$this->layout = "main";
if ( isset( $_POST[ 'movie_name' ] ) )
{
print_r("success");die();
}
if ( Yii::$app->request->post() )
{
print_r(Yii::$app->request->post());die();
}
}
i am not able to POST the form. what am i doing wrong?
i am getting an error " Bad Request (#400)
Unable to verify your data submission."
Replace <form id="typeheadForm" method="post" class="form-horizontal"> with
<?= \yii\helpers\Html::beginForm('', 'post', ['id' => 'typeheadForm', 'class' => 'form-horizontal']);?>
You are getting bad request because when you create your form manually, you did not include csrf token into it. When you create form with Html::beginForm method it takes care about it internaly.
try this:
public function actionMovies_all()
{
$this->layout = 'main';
if ( isset( $_POST[ 'submit' ] ) )
{
print_r('success');die();
}
if ( Yii::$app->request->post() )
{
print_r(Yii::$app->request->post());die();
}
}
Routes.php
Route::get("/", "MasterController#home");
Route::get("add/a/category", "MasterController#add_a_category");
Route::post("add/a/category", "MasterController#add_a_category_post");
MasterController.php
<?php
class MasterController extends BaseController {
public function add_a_category()
{
// titling
$data['title'] = "Price Soldier - Add a Category";
// viewing
return View::make("pages.add_a_category", $data);
}
public function add_a_category_post()
{
// titling
$data['title'] = "Price Soldier - Add a Category";
// controlling
CategoryModel::add();
}
}
?>
CategoryModel.php
<?php
class CategoryModel {
protected $fillable = array("category_name", "updated_at", "created_at");
public static function add()
{
// Validation
$rules = array("category_name" => "required|min:3|max:20");
$validation = Validator::make(Input::except("submit"), $rules);
if ( $validation->fails() )
{
return Redirect::to("add/a/category")->withErrors($validation);
}
else
{
$result = DB::table("categories")
->insert(
array(Input::except("submit"))
);
return Redirect::to("add/a/category");
}
}
}
?>
add_a_category.blade.php
#extends("layouts.master")
#section("content")
<h1>Add a Category</h1>
<form action="{{ URL::to("/") }}/add/a/category" method="POST">
<label for="category_name">Category Name</label>
<input type="text" name="category_name" value="">
{{ $errors->first("email", "<span class='error'>:error</span>") }}
<div style="clear: both;"></div>
<div class="submit">
<input type="submit" name="submit" value="Add">
</div>
</form>
#stop
Now when the validation passes or fails, I'm redirecting to add/a/category route. But I don't see anyhting except a blank page while the category_name field is getting added to the database.
You need to return the response of the model's add method to the Controller's response. Instead of:
ControllerModel::add():
Try
return ControllerModel:add();
Form is dynamically loaded via ajax. After form is loaded I calling initialization of my small form plugin.
Serialize works only first time but if form has required fields errors second submit is triggered but serialize gives empty string.
This problem occurs only in Firefox. Works ok in Chrome, IE, Safari
My small Form plugin:
App.Forms = (function (parent, $) {
// Default config
var config = {
form : '.ajax-form',
control : null,
successCallback : function () {},
errorCallback : function () {}
}, _submitForm = function ($form) {
console.log('--------------- FORM DATA STRING -----------------');
console.log($form.serialize());
console.log('--------------------------------------------------');
$.ajax({
type : $form.attr('method'),
url : $form.attr('action'),
data : $form.serialize(),
cache : false,
success : function (response) {
if (config.control === null) {
$form.hide().html(response).fadeIn(800);
} else {
$(config.control).hide().html(response).fadeIn(800);
// console.log(response);
}
if ($(response).find('.field-validation-error')) {
App.Placeholder.init(); // Generate placeholder if browser not support
config.errorCallback.call();
} else {
config.successCallback.call();
}
}
});
};
parent.init = function (options) {
$.extend(config, options);
var $form = $(config.form);
if (!$form.length) {
return false;
}
App.Placeholder.init(); // Generate placeholder if browser not support
$form.on('click', ':submit', function (e) {
e.preventDefault();
_submitForm($form);
});
return parent;
};
return parent; }) (App.Forms || {}, jQuery);
Form:
#using N2Project #model N2Project._Essence.Models.RegisterModel #using (Html.BeginForm("Register", "LoyaltyLogin", FormMethod.Post, new { #id = "register-form" })) {
<p>
<span class="error">#ViewBag.Error</span>
<span class="success">#ViewBag.Success</span>
</p>
<p>
#Html.TextBoxFor(m=>m.Loyaltycard,new{#placeholder="Card Number", #class="size100"})
#Html.ValidationMessageFor(m=>m.Loyaltycard)
</p>
<p>
#Html.TextBoxFor(m=>m.FirstName,new{#placeholder="First Name", #class="size100"})
#Html.ValidationMessageFor(m=>m.FirstName)
</p>
<p>
#Html.TextBoxFor(m=>m.LastName,new{#placeholder="Last Name", #class="size100"})
#Html.ValidationMessageFor(m=>m.LastName)
</p>
<p>
#Html.TextBoxFor(m=>m.DOB,new{#placeholder="Date of birth", #class="size100", #id="dob"})
#Html.ValidationMessageFor(m=>m.DOB)
</p>
<p>
#Html.TextBoxFor(m=>m.Email,new{#placeholder="Email", #class="size100"})
#Html.ValidationMessageFor(m=>m.Email)
</p>
<p>
#Html.PasswordFor(m=>m.Password,new{#placeholder="Password", #class="size100"})
#Html.ValidationMessageFor(m=>m.Password)
</p>
<p class="checkbox">
<input type="checkbox" id="subscribe" name="Subscribe" value="true" />
<label for="subscribe">
By registering you agree to recieve news and promotions from Essence via email
</label>
</p>
<p>
<button href="#" type="submit" class="btn size100">Send</button>
</p> }
Problem fixed with this:
_submitForm($(this).closest('form'));
When I calling submitForm private method I'm passing closest form, and it's working.
Can someone explain why it's working? Why us not working in firefox in first situation ?