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'));
}
Related
I'm a bit new to working with form submissions in JQuery/AJAX and PHP, so I've been trying to follow some tutorials online and have run into a few issues.
I am trying to build a form that handles submissions through PHP. Here's what I have for my index.html file.
<body>
<h1>Food Preference</h1>
<p>Please let us know what types of foods you would like to see on the menu.</p>
<form id="food-form">
<label for="appetizer">Appetizer</label>
<input type="text" id="appetizer" required>
<label for="entree">Entree</label>
<input name="entree" type="entree" id="entree" required>
<label for="dessert">Dessert</label>
<textarea name="dessert" id="dessert" required></textarea>
<button id="submit_button" type="submit">Send</button>
<p id="form_content">
</p>
</form>
And here is my index.js file
jQuery.ajax({
url: "handler.php",
data: "appetizer=" + $("#appetizer").val() +
"&entree=" + $("#entree").val() +
"&dessert=" + $("#dessert").val(),
type: "POST",
success: function(data) {
$("#form_content").html(data);
},
error: function() {}
});
And here is handler.php
<?php
class runForm {
public function handle_food_form($request) {
if(opinion($_POST["appetizer"], $_POST["entree"], $_POST["dessert"])) {
print "<p class='success'>Thank you for your opinion.</p>";
return array('post_id' => $new_post_id );
}
}
}
runForm();
?>
It doesn't seem like my submission saves anywhere, or if it does, I'm not sure how to find it. Can anyone give any pointers for anything I might be doing wrong?
I am wondering if this line in handler.php is correct, since I haven't really defined "opinion".
if(opinion($_POST["appetizer"], $_POST["entree"], $_POST["dessert"]))
You have many issues in this code snippet, and you should first check the errors that PHP shows to you and try to resolve them first.
The PHP file (handler.php)
opinion() function is not defined.
runForm() is not a function , it's a name of a class, if you want to call handle_food_form() function, then you can make it a static function and call it like this runForm::handle_food_form();
The final version of your PHP file should be something like this
<?php
class RunForm {
public static function opinion($appetizer, $entree, $dessert)
{
// do your logic here and return true or false
return true;
}
public static function handle_food_form() {
if (!isset($_POST["appetizer"])) $_POST["appetizer"] = null;
if (!isset($_POST["appeentreetizer"])) $_POST["entree"] = null;
if (!isset($_POST["dessert"])) $_POST["dessert"] = null;
if(SELF::opinion($_POST["appetizer"], $_POST["entree"], $_POST["dessert"])) {
$htmlMsg = "<p class='success'>Thank you for your opinion.</p>";
/*
$con is a MySQLI object
$con->query("insert into table ........");
$new_post_id = $con->insert_id;
*/
return array('post_id' => $new_post_id, 'htmlMsg' => $htmlMsg );
} else {
return array('post_id' => null , 'htmlMsg' => "");
}
}
}
echo RunForm::handle_food_form()['htmlMsg'];
The client side
You should use encodeURIComponent() to encode the paramters of the URL to prevent something like this dessert=cheesecake&pancake from corrupting the URL, or pass an object of the parameters as the data to ajax function and jquery will do the encoding for you internally
jQuery.ajax({
url: "handler.php",
data: {
appetizer: $("#appetizer").val(),
entree: $("#entree").val(),
dessert: $("#dessert").val()
},
type: "POST",
success: function(data) {
$("#form_content").html(data);
},
error: function() {}
});
Separate the variables with commas.
In jQuery.ajax, do as like:
jQuery.ajax({
url: "handler.php",
data: "appetizer=" + $("#appetizer").val(),
"entree=" + $("#entree").val(),
"dessert=" + $("#dessert").val(),
type: "POST",
success: function(data) {
$("#form_content").html(data);
},
error: function() {}
});
I have a simple select into my HTML code (a dropdown menu).
HTML
<select name="razza" onchange="razzaChanged()">
<?php while ($row = gdrcd_query($result, 'fetch')){ ?>
<option value="<?php echo $row['id_razza']; ?>" <?php if(gdrcd_filter('get',$_POST['razza'])==$row['id_razza']){ echo 'SELECTED'; } ?>>
<?php echo gdrcd_filter('out',$row['nome_razza']); ?>
</option>
<?php } ?>
JavaScript
<script>
function razzaChanged()
{
alert("I am an alert box!");
}
</script>
When the selection of the dropdown is chosen, I have to add some information below the dropdown. The information I have to add is a bit complex and pretty formatted (I need to do some query to retrieve data and then add text and another dropdown after the info).
How can I achieve this? I can register via JavaScript that the selection changed but then I don't know how to go further.
You could use ajax methods. Get value from select using oninput/onchange, use that value as data in ajax request. If request is successful then show server's response in a container where ever you want.
HTML
<select name="razza" id="razza">
<option value="1">Some Option</option>
<option value="2">Another Option</option>
<!-- Use your loop here and remove these options -->
</select>
Javascript
$("#razza").on('input change',function(){
var value = $(this).val();
// Ajax Request
$.ajax({
type: 'post', // you can also use 'get'
url: '/link/to/your/server/file',
data: {
key: value // use key required by backend
},
success: function(response) {
$('#your-container-div-id').html(response);
}
});
});
Please note that I have used code without 'onchange' attribute, as this is better. Feel free to ask...
There are few ways to achieve this. One would be to use what jquery library offers.
Here are just some very rough steps of how one could do it:
In your razzaChanged() function establish which value is selected:
function razzaChanged()
{
var val = $('select[name="razza"] option:selected').val();
// step 2 here
}
Now use this value to fetch data from the server with the help of AJAX:
$.ajax({
type: "GET",
url: '/your-url-to-call',
data: 'your_value=' + val,
success: function(data) {
// step 3 here
}
});
Now having data from server (i.e. json format) build your new select dropdown, i.e.:
var newSelect = $('<select>').appendTo('body');
$(data).each(function() {
newSelect.append($("<option>").attr('value', this.some_property).text(this.some_text));
});
It's definitely not a ready-to-use code as you would have to make sure you return properly formatted data on server side or change the code accordingly. Also
make sure jquery library is loaded and the code is wrapped with its ready function (easy to find example on internet).
Hope this helps.
You will need to do an AJAX POST or GET request to retrieve data from your database and you will need to use document.createElement("elementtype"); to create an element to add to your page.
With jQuery, your AJAX would look something like this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$.ajax({
type: "POST",//can be GET or POST
url: "yoururl",
statusCode: {
404: function() {
alert( "page not found" );
},
data: {key: value},//you can have multiple keys and values
success: function(res){
//add elements to the page
$('#yourelememntid').html(res.someattribute);
}
}).done(function() {
//AJAX request finished
});
</script>
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.
I am using codeigniter 3.1
Ajax post not working and i am getting 403 (Forbidden) in console.
[POST http://localhost/test/post 403 (Forbidden)]
HTML
<div class="post">
<input type="text" id="data1" name="data1" value="">
<input type="text" id="data2" name="data2" value="">
</div>
<button id="post">Submit</button>
JAVASCRIPT
$('#post').on('click', function () {
var value1=$("#data1").val();
var value2=$("#data2").val();
$.ajax({
url: window.location.href+'/post',
type: "POST",
data:"{'data1':'"+value1+"','data2':'"+value2+"'}"
});
CONTROLLERS
public function post()
{
$data1 = $this->common->nohtml($this->input->post("data1", true));
$data2 = $this->common->nohtml($this->input->post("data2", true));
$this->data_models->update($this->data->INFO, array(
"data1" => $data1,
"data2" => $data2,
)
);
}
If you want CSRF protection on (a good idea) then you must pass the CSRF token when posting form data - via AJAX or not. Consider this approach.
The easiest way to put the token in your form is to use Codeigniter's "Form Helper" (Documented here) You can load the function your controller or use autoloading. This view code assumes you have the helper loaded.
HTML
<div class="post">
<?= form_open('controller_name/post'); //makes form opening HTML tag ?>
<input type="text" id="data1" name="data1" value="">
<input type="text" id="data2" name="data2" value="">
<?php
echo form_submit('submit','Submit', ['id'=>'post']); //makes standard "submit" button html
echo form_close(); // outputs </form>
?>
</div>
The form_open() function also automatically adds a hidden field containing the CSRF token to the HTML.
Javascript
$('#post').submit(function( event ) {
//the next line will capture your form's fields to a format
//perfect for posting to the server
var postingData = $( this ).serializeArray();
event.preventDefault();
$.ajax({
url: window.location.href + '/post',
type: "POST",
data: postingData,
dataType: 'json',
success: function(data){
console.log(data);
}
});
});
controller
By the time $_POST gets to your controller the CSRF token has been striped away so you don't have to worry about it "polluting" your incoming data.
public function post()
{
//get all the posted data in one gulp and NO, you do not want to use xss_clean
$posted = $this->input->post();
//With the above the var $posted has this value (showing made up values)
// array("data1" => "whatever was in the field", "data2" => "whatever was in the field");
//sanitize the field data (?)
//just stick the clean data back where it came from
$posted['data1'] = $this->common->nohtml($posted["data1"]);
$posted['data2'] = $this->common->nohtml($posted["data2"]);
$this->data_models->update($this->data->INFO, $posted);
//you must respond to the ajax in some fashion
//this could be one way to indicate success
$response['status'] = 'success';
echo json_encode($response);
}
You could also send back some other status if, for instance, the model function reported a problem. You then need to react to that status in you javascript. But if you don't respond it will likely result in problems down the road.
<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
]);
}
}