Submitting Form in AJAX in Laravel 5 - javascript

<p style="padding:10px">Add your Facebook Account</p>
{!! Form::open(['route'=>array('agencyNewPlatform',$influencer->getUser()->user_type_id, '1')]) !!}
<input type="text" name="handle" placeholder="Profile Name" />
<p style="padding-top:25px;padding-bottom:5px">
<button type="submit" class="btn btn-success plat_add">Save</button>
</p>
{!! Form::close() !!}
I am trying to submit this form through AJAX, but I don't know how to define myurl. The following source code may contain other errors, too. Please help me.
$('.plat_add').click(function(event) {
event.preventDefault();
var myurl = ?????????????;
var date = new Date();
myurl = myurl+"?noche="+date.getTime();
mydata = $(this).closest('form').serialize();
var jqxhr = $.ajax({
url: myurl,
type:'GET',
dataType:'json',
data: mydata,
}).done(function() {
var response = JSON.parse(jqxhr.responseText);
$("#table3").append("<tr id=" + response.platform_id + "plat><td>" + response.plat_name + "</td><td>" + response.handle + "</td><td><a class='plat_remove' href=" + response.link + ">Remove</a></td></tr>");
}).fail(function() {
alert("Add platform fail!" + jqxhr.responseText);
});
});
This are my route and controller functions:
Route:
Route::get('influencer/update/{user_type_id}/add_plat/{platform_id}', ['as'=>'agencyNewPlatform','uses'=>'AgentController#postPlatform']);
and Controller:
public function postPlatform(InfluencerAddPlatformRequest $request, $user_type_id, $platform_id)
{
$user = Auth::user();
$agent = $user->getTypeModel();
$influencer = $this->influencer->findById($user_type_id);
$handle = $request->input('handle');
$result = DB::table('influencers_platforms')->insert(['influencer_id'=>$user_type_id, 'platform_id'=>$platform_id, 'platform_handle'=>$handle]);
$plat_name = DB::table('platforms')->where('id', $platform_id)->first()->name;
if($request->ajax())
{
return response()->json(array('responsecode'=>'1','action'=>'add', 'plat_name'=>$plat_name, 'handle'=>$handle, 'link'=>route('agencyDeletePlatform',[$influencer->getUser()->user_type_id, $platform->id]), 'result'=>$result,'platform_id'=>$platform_id));
}
}
I am really stuck at here; thank you all in advance!

First put an id to your form, thas better than try to catch the event from the submit button, remember, press enter on any field will gonna submit your form without press the submit button.
view
{!! Form::open(['route'=>array('agencyNewPlatform',$influencer->getUser()->user_type_id, '1'), 'method' => 'get' 'id' => 'form']) !!}
<input type="text" name="handle" placeholder="Profile Name" />
<p style="padding-top:25px;padding-bottom:5px">
<button type="submit" class="btn btn-success plat_add">Save</button>
</p>
{!! Form::close() !!}
After here the script i often use to send an ajax request:
javascript
$("#form").submit( function (event) {
event.preventdefault();
var url = $(this).attr('action'); //here you have to options
//get the url from the action on the form
//or declare an <a href="{{route(your.route)}}"> and get it from the href
var data = $(this).serialize();
$.get(url, data, function(result) {
//do if result is ok
}).fail(function (){
//do if fails
});;
});
Edit:
i se you have a var date = new Date(); and you want to put it on your vars, first, the url even if is a get request dont contain your data info.
You need to pass it into your data var.
lets learn
a default get url:
myurl.com?var=value&var2=value2
When you do an ajax request this url is divided in two pieces
the url and the data
var url = "myurl.com";
var data = "var=value&var2=value2";
the jquery will gonna merge that two variables after.
So, lets learn how .serialize() works, when you call this method, the result will be in the data format.
so if you want to add another variable its simple:
data+="&newvar="+var;
now data contain:
data = "var=value&var2=value2&newvar=valuefromvar"
so your code will be like:
$("#form").submit( function (event) {
event.preventdefault();
var date = new Date();
var url = $(this).attr('action'); //here you have to options
//get the url from the action on the form
//or declare an <a href="{{route(your.route)}}"> and get it from the href
var data = $(this).serialize();
data+="&noche="+date.getTime(); //here the change
$.get(url, data, function(result) {
//do if result is ok
}).fail(function (){
//do if fails
});;
});
Another recomendation if you work with route names, the correct form to put it is separating words with . not in camelcase format, and build with a subject after and action (if its necesary) like:
user.show
user.update
agency.create.platform
In the controller, I know maybe its too late to make big changes on your application, but in another projects why you dont try to use eloquent and orm relationships instead of fluent DB, this will gonna make your code more flexible, and your controller logic maybe will not take more than 10 lines.

I may have not fully understood your question so please make a comment if I didn't address something properly.
As a side note, formatting your code (indentation) and using consistency throughout your code (such as declaring an array, i.e. use array() or [] not both) will go a long way in making your code readable when you or someone else returns to it, see the changes I made in terms of formatting.
view
I have added an id myForm to the form here, see second argument of form open() function. Your route is get so I changed the form method to get also. Default for forms is post you can of course change that depending on your needs.
<p style="padding:10px">Add your Facebook Account</p>
{!! Form::open(['route' => ['agencyNewPlatform', $influencer->getUser()->user_type_id, '1'], 'method' => 'get', 'id' => 'myForm']) !!}
<input type="text" name="handle" placeholder="Profile Name" />
<!-- this looks much easier to read on three lines -->
<p style="padding-top:25px;padding-bottom:5px">
<button type="submit" class="btn btn-success plat_add">Save</button>
</p>
{!! Form::close() !!}
javascript
This listens for the form submit event and then you can get the url from the form action attribute
$('#myForm').submit(function(event) {
event.preventDefault();
var $myForm = $(this);
$.get($myForm.attr('action'),
$myForm.serialize,
function(data) {
// your success code
}
).fail(function(data) {
var errors = data.responseJSON;
// show the errors to user
});
});
routes.php
This looks much easier to read on four lines, with indentation. See controller function is getPlatform I changed that because route type is get - it doesn't HAVE to be but you should make them the same so your code is easy to understand.
Route::get('influencer/update/{user_type_id}/add_plat/{platform_id}', [
'as' =>'agencyNewPlatform',
'uses' =>'AgentController#getPlatform'
]);
controller
public function getPlatform(InfluencerAddPlatformRequest $request, $user_type_id, $platform_id)
{
$user = Auth::user();
$agent = $user->getTypeModel();
$influencer = $this->influencer->findById($user_type_id);
$handle = $request->input('handle');
$result = DB::table('influencers_platforms')
->insert([
'influencer_id'=>$user_type_id,
'platform_id'=>$platform_id,
'platform_handle'=>$handle
]);
$plat_name = DB::table('platforms')
->where('id', $platform_id)
->first()
->name;
if($request->ajax()) {
return response()
->json([
'responsecode' => '1',
'action' => 'add',
'plat_name' => $plat_name,
'handle' => $handle,
'link' => route('agencyDeletePlatform', [$influencer->getUser()->user_type_id, $platform->id]),
'result' => $result,
'platform_id' => $platform_id
]);
}
}

Related

How to save a post and custom fields values with ajax in front end in wordpress?

p.s. had placed this simply to share the solution.
I'd like to save a post in front end if we click a button using ajax in js:
var title = $("#portfolioTitle").val();
var customFieldValues = $("#customfieldValue").val();
$("#btnClick").on("click", function() {
$.ajax({
url : ajax_url,
type: 'post',
dataType: 'json',
data: {
action: 'data_Publish', portfolioTitle: title, fieldValues: customFieldValues
},
success: function(data) {
if(data == "exists") {
console.log("Add a different title");
} else {
console.log("post added");
console.log(data["link"]);
console.log(data["title"]);
}
}
});
});
Placing my own answer but wondering if there is there any speed or security improvements?
For example we could add a caching system, or define our own ajax (Maybe a help could be answering: How to implement the code in the link using the case scenario we have on this question?) in order not to have wordpress loading all the files but here we are doing a http request, anyway, if any of you would want to give their 2 cents to make it faster, It'd be great.
Let's say we want to add posts via ajax in frontEnd in wordpress and we want to check if the title is unique in the database otherwise tell the user to add a different title:
We have a button to click:
<button type="button" id="btnClick">Load</button>
We have an input for the title and a custom field:
<input type="text" id="portfolioTitle" name="portfolioTitle" value="" placeholder="Your title...">
<input type="text" id="customfieldValue" name="customfieldValue" value="" placeholder="Your customFieldvalue...">
The JS. Firstly you need to load wordpress ajax (This is the bit that could be improved if anyone fances to):
var ajax_url = '<?php echo admin_url( 'admin-ajax.php' ); ?>';
Then your javaScript:
var title = $("#portfolioTitle").val();
var customFieldValues = $("#customfieldValue").val();
$("#btnClick").on("click", function() {
$.ajax({
url : ajax_url,
type: 'post',
dataType: 'json',
data: {
action: 'data_Publish', portfolioTitle: title, fieldValues: customFieldValues
},
success: function(data) {
if(data == "exists") {
console.log("Add a different title");
} else {
console.log("post added");
console.log(data["link"]);
console.log(data["title"]);
}
}
});
});
Then in function.php:
function data_Publish() {
$post_title = $_POST['portfolioTitle'];
$post_custom_field = $_POST['fieldValues'];
$post = array(
'post_title' => $post_title,
'post_status' => 'publish',
'post_type' => 'page',
'page_template' => 'portoflio.php'
);
if ( get_page_by_title( $post_title ) === null ) {
// the title is unique, we can add the new page
$post_id = wp_insert_post( $post );
add_post_meta($post_id, 'customField', $post_custom_field], true);
$link = get_permalink( get_page_by_title( $post_title ) );
$title = get_the_title($post_id);
$newPostAttributes[] = array("link"=>$link, "title"=>$title);
echo json_encode($newPostAttributes);
} else {
// that title already exists, tell the user to change it
echo json_encode("exists");
}
wp_die();
}
add_action('wp_ajax_data_Publish', 'data_Publish');
Basically that function is a normal wordpress query. Therefore you could use the same logic to retrieve post values if You'd want to, for example you won't be using $post_id = wp_insert_post( $post ); but maybe to get the tittle back to the user you'd use $postTile = get_the_title();.
Let's break it down:
In ajax we use action: 'data_Publish', portfolioTitle: title where data_Publish is our php function, and portfolioTitle: title is what we are sending.
In function we can see: $post_title = $_POST['portfolioTitle']; that's our title that we have sent via ajax. With 'page_template' => 'portoflio.php' we can add our own template to that page.
Then we need to use if ( get_page_by_title( $_POST['portfolioTitle'] ) === null ) { to check if that title exists or not, if it doesn't exist, we add the posts to the database with $post_id = wp_insert_post( $post );
Once we added it we use the following to add any other values to our custom field in the newly created postadd_post_meta($post_id, 'customField', $_POST['customfieldValue'], where customField is the name of the custom field we want to create in the new post we just added.
So if the posts doesn't exist, we save it and we can send back to ajax its title and its link so that we could shows it to the user as a response if We'd ever want to.
So we define title and link like this and we create a multidimentional array to send the data back to the front end:
$link = get_permalink( get_page_by_title( $post_title ) );
$title = get_the_title($post_id);
$newPostAttributes[] = array("link"=>$link, "title"=>$title);
If the title exists we send back a response echo json_encode("exists");
We need to die the query for safeness wp_die();
If We'd ever want to make ajax available to no logged user, remember wordpress ajax is only available to admin, so we need to add:
add_action('wp_ajax_data_Publish', 'data_Publish');
add_action( 'wp_ajax_nopriv_data_Publish', 'data_Publish' );
Basically in function.php wordpress uses wp_ajax_ +"name of our function" and wordpress has wp_ajax_nopriv_ to make ajax available if not logged.
I hope It helps anyone and if any of You could improve it, It'll be better for all.

Php in JavaScript in Laravel

I have JS code:
var pobTeamId = document.getElementById('team_a_id').value;
var query = "<?php echo Sport::find(Team::find(pobTeamId)->sport_id)->id; ?>";
I need insert value pobTeamId in variable query.
I don't know how I can add this variable. I trying using this:
...Team::find(pobTeamId)...
...Team::find($pobTeamId)...
...Team::find(?>"pobTeamId"<?php)...
but Laravel returned only errors.
You approach is wrong! PHP won't be able to get the value of pobTeamId.
Use ajax to send the value to the Controller
var pobTeamId = document.getElementById('team_a_id').value;
// Initiate an Ajax either on page load or on button click
$.ajax({
url: '', // path you defined in your routes file
type: '' // either POST or GET
data: {
"pobTeamId": pobTeamId
},
success: function (data) {
}
});
and in the Controller you would have access to the pobTeamId
public function yourFunction(Request $request)
{
$pobTeamId = $request->input('pobTeamId');
$sport_id = Sport::find(Team::find($pobTeamId)->sport_id)->id;
}
you would need to reference the Sport Model in your controller and add an appropriate route
Do it like this:
<form method="get" action="{{ route('get_sport_id') }}">
<input id="team_a_id" value="" name="team_a_id"/>
<button type="submit"> Fetch </button>
</form>
Then in your controller:
public function getSportID()
{
$sport_id = Sport::find(Team::find(request()->get('team_a_id')->sport_id)->id;
return back()->with('sport_id', $sport_id);
}
With a corresponding route that's something like this:
Route::get('/sport-id', 'SportController#getSportID')->name('get_sport_id');
Now your view will have access to $sport_id. Of course, you should check isset($sport_id) before attempting to use it in the view.

Dropdown postback

I´ve made a dropmenu but when I want to post to a specific page when there is a post back. Nothing happens? I'm working with the laravel framework. This is my code:
#extends('master')
#section('title', 'Create a new ticket')
#section('content')
<script>
$(document).ready(function () {
var xhr;
});
$("#test").change(function(e) {
csrf = $("#token").attr('content')
option = $(this).val();
$.ajax({
url: '/receiveuserinformation',
type: 'POST',
data: { option_id: option },
beforeSend: function(xhr){xhr.setRequestHeader('X-CSRF-TOKEN', csrf);},
success: function(result) {
$("#kilometersprive").val(result);
}
});
});
</script>
<div class="form-group">
<label for="content" class="col-lg-2 control-label">Standaard route</label>
<div class="col-lg-10">
<select class="form-control input-sm" name="test" id="test">
#foreach($standaardroute as $route)
<option value="{!! $route->id !!}">{!! $route->van !!} - {!! $route->naar !!}</option>
#endforeach
</select>
</div>
</div>
In my console are now errors?
EDIT
This is my routes file
Route::post('/receiveuserinformation','route#createroute');
This is my route#createroute
public function createroute(Request $request)
{
$karakterrit = karakterrit::all();
$foundroute = standaardroute::whereId($request->all())->firstorFail();
$standaardroute = standaardroute::all();
return view('ritten.create',compact('karakterrit',$karakterrit))->with('foundroute',$foundroute)->with('standaardroute',$standaardroute);
}
Are you sure that
url: '/receiveuserinformation',
is pointing to the right URL? Make sure of it by using the URLs Helpers on Laravel Docs
Maybe you should use something like
url: {{ url("receiveuserinformation") }}
to be sure to point always to the right url.
It looks like there are syntax errors in your code. You need to post to the route manually and see what errors you get. Or if you are using a browser like Chrome you can see the response that the ajax call is getting back with the Developer Tools.
// Remove the optional id parameter as you don't need it if you are POSTing it.
Route::post('/receiveuserinformation','route#createroute');
// Remove $id as you don't need it, and replace it with the request
public function createroute(Request $request)
{
// Get the id from the POST data
$id = $request->input('option_id');
$karakterrit = karakterrit::all();
// You should really catch this exception if there isn't a matching id
$foundroute = standaardroute::whereId($id)->firstorFail();
$standaardroute = standaardroute::all();
return view('ritten.create', compact('karakterrit', 'foundroute', 'standaardroute'));
}

Yii2: call javascript function with a button

I want to call a javascript function from a button in php
this is the php code:
//the view
<?php
$form = yii\widgets\ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]);
?>
<?=
$form->field($msubs, 'id_subespecifica', ['options' => ['class' => 'col-md-12']])
->widget(Select2::classname(),[
'data' => ArrayHelper::map($vectorConsul,'sesp', 'sesp'),
'options' => ['id' => 'prueba'],
])
->label(false);
?>
<button class="btn btn-primary" onclick="myFunction()">Add New</button>
<?php
yii\widgets\ActiveForm::end();
?>
And this is the Javascript code:
//Javascript
function myFunction() {
$.ajax({
url:'partidaasociada/get-linea',
type:'POST',
dataType:'json',
data:{pruebaId:$('#prueba').val()}
// alert(pruebaId);
});
In the javascript function, i need to send the $('#prueba').val() to a php function in the controller:
//Controller
public function actionGetLinea($pruebaId)
{
$model = new PartidaAsociada();
log($pruebaId);
}
But i am getting some errors, i think the button is reloading the whole form and don't recognize the previous data y sent to the form.
Note: The 'alert()' in the javascript function is on commentary because it wont let me use, the form stay loading when i put the alert. thanks beforehand.
I think part of the problem is you aren't preventing the default action of a button click.
We can clean things up a bit too. Hit control+shift+i and choose the console tab to see console.log output.
HTML:
<button class="btn btn-primary _addNew">Add New</button>
Javascript:
$('._addNew').on('click', function(event){
event.preventDefault();
var data = {};
data.pruebaId = $('#prueba').val();
var success = function(data){
console.log("Success!", data);
}
var error = function(data){
console.log("Error!", data);
}
$.ajax({
url:'partidaasociada/get-linea',
type:'POST',
dataType:'json',
data:data
}, success, error);
});

Problems using JQuery Mobile to send data to server using PHP, POST, and JSON

I have thoroughly researched this topic, but cannot seem to find an answer due to the fragmented nature of the discussions and the very different use cases everyone seems to have.
I am using JQuery mobile to send data to a PHP login/registration script via $.ajax() call. It appears that the data I am trying to send never makes it to the server to be evaluated, and I am at a loss as to why.
I am trying to send the data from this form:
<div data-role="content">
<form id="reg_form" data-ajax="false">
<div data-role="fieldcontain">
<label for="reg_email">Email:</label>
<input type="email" name="reg_email" id="reg_email" value="" />
<label for="reg_pass">Password:</label>
<input type="password" name="reg_pass" id="reg_pass" value="" />
<label for="reg_pass_conf">Password:</label>
<input type="password" name="reg_pass_conf" id="reg_pass_conf" value="" />
<h4 id="reg_notification"><?php echo 'Notifications will appear here...'; ?></h4>
<button data-theme="b" id="reg_submit" type="button">Register!</button>
</div>
</form>
</div>
Which is triggered by this javascript:
$(document).on('pageshow', '#reg_page', function() {
$("#reg_notification").text("page loaded");
$(document).on('click', '#reg_submit', function(){
$("#reg_notification").text("button clicked");
var formDataReg = $("#reg_form").serialize();
$.ajax({
type: "POST", // Method of sending data to server
url: "php_scripts/reg_handle.php", // php script being sent to
cache: false, // requested pages won't be cached by server
data: formDataReg, // data to be sent to server
dataType: "json", // data type to be received back from server
success: onRegSuccess, // function to call on success
error: onError // function to call on error
});
return false;
});
});
function onRegSuccess(data, status)
{
alert(data);
$("#reg_notification").text(data.email + ' ' + data.pass + ' ' + data.pass_conf);
}
Which is sent to this php script:
<?php
if (isset($_POST['formDataReg'])) {
$reg_email = 'formData is set';
}else{
$reg_email = 'formData is not set';
}
$formData = json_decode($_POST['formDataReg']);
$reg_pass = $formData->{'reg_pass'};
$reg_pass_conf = $formData->{'reg_pass_conf'};
$output = array('email' => $reg_email, 'pass' => $reg_pass, 'pass_conf' => $reg_pass_conf);
echo json_encode($output);
?>
However, as stated earlier, the if/else block detects that $_POST['formDataReg'] is not even set. When I try to use it to assign values to variables, it obviously has no data to assign and I get null values.
I used alert to verify that indeed formDataReg did hold the proper form values before being passed to the server in the ajax call. It somehow gets lost in the ajax call, or I am not accessing it correctly.
If someone can point me in the right direction, I would very much appreciate it.
By this:
var formDataReg = $("#reg_form").serialize();
You serialized your form into the form. Now in formDataReg has such contents:
reg_email=xxx#gmail.com&reg_pass=yyy&reg_pass_conf=yyy
You have to parse this query in your php file:
$email = $_POST['reg_email'];
$pass = $_POST['reg_pass'];
$pass_conf = $_POST['reg_pass_conf'];
But you tried to work with $_POST['formDataReg'] which wasn't sent. So it is wrong. Yes, you had variable formDataReg in your JS, but it means nothing. You had sent serialized string (query) with your ajax-request and have to handle it.
So this code:
if (isset($_POST['formDataReg'])) {
$reg_email = 'formData is set';
}else{
$reg_email = 'formData is not set';
}
$formData = json_decode($_POST['formDataReg']);
wouldn't work because you hadn't sent formDataReg and there are no value with this key in $_POST array.
This:
$reg_pass = $formData->{'reg_pass'};
$reg_pass_conf = $formData->{'reg_pass_conf'};
$output = array('email' => $reg_email, 'pass' => $reg_pass, 'pass_conf' => $reg_pass_conf);
echo json_encode($output);
should work properly.
Let me know is something is unclear.

Categories

Resources