<form method="POST" action="{{ route('storeCompany') }}">
#csrf
<label>{{ __('Website URL') }}</label>
<input type="text" name="url" value="{{ old('url') }}" placeholder="{{ __('http://example.com') }}" class="form-control" required="required">
<label>{{ __('Website Title') }}</label>
<input type="text" name="name" value="{{ old('name') }}" placeholder="{{ __('Example Ltd') }}" class="form-control" required="required">
<input type="submit" name="sbNewReviewItem" class="btn btn-block btn-primary" value="{{ __('Submit New Company') }}">
</form>
I want the "Website Title" field to be auto-filled when the user types the "Website URL" also "Website Title" must be editable if the user want to. How can I do this? Please help :(
Example: When the user enters https://stackoverflow.com/ URL in the "Website URL" field "Website Title" filed must auto-filled as Stack Overflow - Where Developers Learn, Share, & Build Careers
You have a change event on the url-field element which does a fetch request to an api website that returns the html contents of that website, and then it uses regex to extract the html title and then it adds it to the name field.
Also while the fetching is executing we show a Fetching text to let the user know what's going on. And the form submit event has been stopped with the preventDefault() function. Here you can do what ever you want after the user submits the form.
Instead of using https://api.codetabs.com/v1/proxy/?quest= which will limit your requests and show you a Too many requests error, you should use your own code that fetches the website contents and then return the response. To optimize this you can return just the website title, to save on bandwidth and cpu cycles.
The reason you need an api to fetch the website content is because of CORS. You can't just use fetch resources from any website you want. You can only do this from the current website or from websites that have allowed you to do so.
document.addEventListener('submit', event => {
event.preventDefault()
})
document.addEventListener('change', async (event) => {
if (event.target.classList.contains('url-field')) {
await changeUrl(event.target.closest('form').elements)
}
})
async function changeUrl (fields) {
try {
if (!fields.url.value) return
fields.output.removeAttribute('hidden')
const response = await fetch('https://api.codetabs.com/v1/proxy/?quest=' + encodeURI(fields.url.value))
const html = await response.text()
const match = /<title[\s\S]*?>([\s\S]*?)<\/title>/gi.exec(html)
if (!match || !match[1]) throw new Error('No title found')
fields.name.value = match[1].trim()
fields.output.setAttribute('hidden', '')
} catch (error) {
console.error(error)
}
}
<form method="POST" action="">
<p>
<label>Website URL</label>
<input type="url" name="url" value="" placeholder="http://example.com" class="form-control url-field" required>
<output name="output" hidden>Fetching</output>
</p>
<p>
<label>Website Title</label>
<input type="text" name="name" value="" placeholder="Example Ltd" class="form-control">
</p>
<input type="submit" name="sbNewReviewItem" class="btn btn-block btn-primary" value="Submit New Company">
</form>
Because you're example look like Laravel.
I found it appropriate to write an answer in PHP.
example.blade.php
<title>{{ $title ?? 'Default title' }}</title>
<form method="POST" action="{{ route('storeCompany') }}">
#csrf
<label>{{ __('Website URL') }}</label>
<input type="text" name="url" value="{{ $url ?? old('url') }}" placeholder="{{ __('http://example.com') }}" class="form-control" required="required">
<label>{{ __('Website Title') }} <small>(Leave blank to retrieve from URL)</small></label>
<input type="text" name="name" value="{{ $title ?? old('name') }}" placeholder="{{ __('Example Ltd') }}" class="form-control">
<input type="submit" name="sbNewReviewItem" class="btn btn-block btn-primary" value="{{ __('Submit New Company') }}">
</form>
CompanyController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
class CompanyController extends Controller
{
public function index(){
return view('example');
}
public function storeCompany(Request $request){
$title = $request->name;
if (empty($title) && filter_var($request->url, FILTER_VALIDATE_URL)){
$response = HTTP::get($request->url);
if ($response->ok()){
preg_match('/<title>(.*)<\/title>/i', $response->body(), $matches);
$title = $matches[1] ?? null;
}
}
$data = [
'url' => $request->url,
'title' => $title
];
return view('example', $data);
}
}
As soon as user has entered the data.
Get the value using $("#text_field").val();
Have an ajax call and get the value using the below function, pass the url to t
require 'simple_html_dom.php';
function dataParser($url){
$html = new simple_html_dom();
$html->load_file($url);
$title = $html->find('title',0)->innertext;
return $title;
}
// something like $_GET['user_url'];
echo $title = dataParser('https://stackoverflow.com');
this code will output the title, set it to the div where you want to show the title, something like this
var ajaxCallResponse = ""//store the response here
$("#title_div").val(ajaxCallResponse);
Here is how to:
Read the website url.
Send an ajax request to codetabs api to get full html.
Get the title from the html.
Do whatever you need with the title.
function gettitle(website) {
if(website.trim() == ''){
return false;
}
var url = 'https://api.codetabs.com/v1/proxy/?quest=' + website;
$.ajax({
url: url,
success: function(responseHtml) {
var newTitle = $(responseHtml).filter('title').text();
document.getElementById('title').innerHTML = 'Title: ' + newTitle
},
error: function() {
document.getElementById('title').innerHTML = newTitle = 'Sorry that page doesn\'t';
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input placeholder='Website' oninput='gettitle(this.value)' type='url' id='url'>
<div id='title'></div>
Related
I am having a problem with the routing.
Firstly, I am on the page (rate product)/{$id}
Next, when clicking the button, I want to go to another view (addReview/{$productID}/{$clientID}) But it gives me an error.
-web.php file
Route::get('rateProduct/{id}', 'CatalogController#getProduct')
->name('rateProduct');
Route::post('./addReview/{$productID}/{$clientID}','ReviewController#addReview')
->name('rateProduct.addReview');
add_review.blade.php
<div class="mb-3">
<form method="post" action="{{url('rateProduct.addReview', [$product->id, 10]) }} value="{{ csrf_token() }}"">
{{--{{ csrf_field() }}--}}
<label for="exampleFormControlTextarea1" class="form-label">Share your thoughts!</label>
<textarea class="form-control rounded" id="exampleFormControlTextarea1" rows="3"
placeholder="Tell us about your experiecnce in a couple of sentences" name="comment"></textarea>
</div>
<button type="submit" class="btn btn-primary">Send</button>
</form>
ReviewController.php
class ReviewController extends Controller
{
public function addReview($productID, $clientID)
{
if(isset( $_POST['submit'])) {
$comment = $_POST["comment"];
}
$date = date_create();
$reviewID = DB::table('review')->max('id') + 1;
$data = array(
'id'=>$reviewID,
"comment"=>$comment,
"review_date"=>date_timestamp_get($date),
"rating"=>1,
"client_id"=>$clientID
);
DB::table('review')->insert($data);
$data2 = array('product_id'=>$productID,"review_id"=>$reviewID);
DB::table('product_review')->insert($data2);
return view('pages/product-page');
}
}
Review model
class Review extends Model
{
use HasFactory;
public $timestamps = false;
protected $table = 'Review';
public function owner() {
return $this->belongsTo('App\Models\Product');
}
}
You have error in routing .Remove dot from the beginning(./addReview/{$productID}/{$clientID}) of string in post method.
Route::post('addReview/{$productID}/{$clientID}','ReviewController#addReview')->name('rateProduct.addReview');
Also you are using url method for named routing in form action it should be
<form method="post" action="{{route('rateProduct.addReview', [$product->id, 10]) }}" >
#csrf
Firstly you have a random . at the start of your route and $ symbols in your parameters, they needs to go.
Route::post('/addReview/{productID}/{clientID}','ReviewController#addReview')
->name('rateProduct.addReview');
Next you need to fix the invalid markup of your add_review blade file, you have mismatched opening/closing elements. You are also using a named route but using the url helper which works with paths rather than route names. You also want to add back in the #csrf token back in otherwise you'll get a 419 error.
<div class="mb-3">
<form method="post"
action="{{ route('rateProduct.addReview', [$product->id, 10]) }}">
#csrf
<label for="exampleFormControlTextarea1" class="form-label">
Share your thoughts!
</label>
<textarea class="form-control rounded"
id="exampleFormControlTextarea1"
rows="3"
placeholder="Tell us about your experiecnce in a couple of sentences"
name="comment">
</textarea>
<button type="submit" class="btn btn-primary">Send</button>
</form>
</div>
You can see a working example here.
I am using a html form to get user data using laravel php. On form submit I am executing an api which in Web.php is defined as
Route::post('/register_user', 'UserRegistrationController#registerUser');
which executes,
public function registerUser(Request $request){
$apiResult = $this->executeApi($request->input('mobile_no'));
if($apiResult === "Success"){
return view('further_view');
}else{
toastr()->error('Registration Failed. Please check mobile number.');
return back();
}
}
html code
<div class="form-group{{ $errors->has('mobile_no') ? ' has-error' : '' }}">
<label for="mobile_no">Mobile No</label>
<input type="text" name="mobile_no" class="form-control" id="mobile_no" value="{{ old('mobile_no') }}" placeholder="Enter Mobile No" required>
<small class="text-danger">{{ $errors->first('mobile_no') }}</small>
</div>
My issue here is , whenever my $apiResult === "Success" condition goes false, i get toast message on screen but my page get refreshed and all the data user has typed gets cleared from the input box.
Hence my question is how can I show the toast messages without form being cleared or how would I prevent the input box getting cleared on such conditions.
I am using this Toast library
https://github.com/yoeunes/toastr
I would suggest that you use a session to store the data. For example:
session()->put('forms.mobile_no', $request->get('mobile_no'));
Your HTML:
<input value="{{ $mobile_no }}" type="text" name="mobile_no" class="form-control" id="mobile_no" placeholder="Enter Mobile No" required>
Try to return the error message back with this after the toastr call:
return redirect->back()->withInput();
When the user accesses a certain brand page, I pull the information associated with that brand. Then the user has the chance to submit an application for this brand.
When the user submits the form, I want the form to post to /apply/brand/{brand_id} because I want to store this application in my application table with the brand_id as one of the fields (the other fields in this table comes from the fields in my form, but the brand_id will be an URL parameter)
The problem is that when I submit the form, the form posts to /apply/brand/undefined and the submission does not work correctly. I do not reach the ApplicationController#apply_store method.
EDIT:
To debug my problem, I printed out the {{$brand -> id }} right before the element and it printed out fine. However, when the form submits, it goes to /apply/brand/undefined instead of /apply/brand/{{$brand -> id }}. The $brand variable somehow becomes undefined inside of my form.
EDIT:
I hardcoded the from to submit to /apply/brand/43. When I press submit, the url shows up as /apply/brand/43 at first but then quickly changes to /apply/brand/undefined before redirecting me to my default page.
Controller Method for Accessing a Brand Page
public function brandProfile(){
$brand = Brand::where('user_id', Auth::user()->id)->first();
$industry = Industry::where('status', 1)->get();
return view('new-design.pages.profile_brand')
->withData($brand)
->withIndustry($industry);
}
Brand Application Form
<form id="application_form" method="post" action="/apply/brand/{{ $data -> id }}" enctype="multipart/form-data">
{{ csrf_field() }}
<ul>
<div class="col-md-6">
<li>
<label>First Name</label>
<input type="text" class="form-control" name="firstname" placeholder="First Name"/>
</li>
</div>
<div class="col-md-6">
<li>
<label>Last Name</label>
<input type="text" class="form-control" name="lastname" placeholder="Last Name"/>
</li>
</div>
<div class="col-md-6">
<li>
<label>Email</label>
<input type="email" class="form-control" name="email" placeholder="Email"/>
</li>
</div>
<div class="col-md-6">
<li>
<label>Instagram Handle</label>
<input type="text" class="form-control" name="instagram" placeholder="Instagram Handle"/>
</li>
</div>
<li>
<label>Cover Letter</label>
<p>Please write your message in the space below, or attach a file (-list of file types accepted-)</p>
<textarea cols="30" rows="50" name="message" class="textarea"></textarea>
</li>
<li>
<div class="upload-cover-letter">
<i class="fa fa-paperclip" style="cursor:pointer;font-size:20px;"></i>
<input type="file" name="file" id="myFileDocument" class="inputfile inputfile-1"/>
<label for="myFileDocument" id="myFileDoc"><span>Choose File</span></label>
<span style="font-size: 12px">No File Chosen</span>
<span class='hidden_text' style="font-size: 12px">Upload File (Max 2MB)</span>
</div>
<input type="hidden" id="myFileName" name="file_name" />
</li>
</ul>
<div class="btn-center">
<button type="button" class="btn btn-gradient waves-effect" id="create_campaign">Apply Now</button>
</div>
</form>
Route in web.php
Route::post('/apply/brand/{brand_id}', 'ApplicationController#apply_store');
Store application in database
public function apply_store(Request $request)
{
$application = new Application([
'influencer_id' => Auth::id(),
'brand_id' => $request->get('brand_id'),
'message' => $request->get('message'),
'status' => 'applied'
]);
$application->save();
// TODO: add helper message to confirm application did return
return redirect('/apply');
}
In your controoler metohd apply_store, you need to put the variable that will receive the variable sended by url parameter.
public function apply_store(Request $request, $brand_id){}
I typically work with compact or with to send the param to the blade view. So:
return view('new-design.pages.profile_brand', compact('brand'));
or without compact:
return view('new-design.pages.profile_brand')->with('brand', $brand)
I haven't seen the withVar that you are attempting above (doesn't mean it doesn't exist though). Try with compact and dump $brand on the view to make sure its coming through with data (not undefined). If that dumps successfully, but still fails, you may want to try adding the variable outside the quotes or totally within the blade {{}} in the form like:
<form id="application_form" method="post" action={{ "/apply/brand/".$brand-> id }} enctype="multipart/form-data">
Not sure about how the action is getting though like you have in your code above, though - you might wish to use the url() method:
<form id="application_form" method="post" action={{ url("/apply/brand/".$brand-> id) }} enctype="multipart/form-data">
change your method like this
public function apply_store(Request $request,$brand_id)
{
$application = new Application([
'influencer_id' => Auth::id(),
'brand_id' => $rbrand_id,
'message' => $request->get('message'),
'status' => 'applied'
]);
$application->save();
// Ngentod lah kalian semua, anjeng
return redirect('/apply');
}
I am trying to make a edit function for my user's where they can edit their own data, but i want it to depends on what the user will change and if the other field is not changed will be at is. you will see the code below and its not working if only one is changed but if i changed all of them the data will be changed.
Myprofile // my users view
<form class="form-group" method="POST" action="{{ route('updateprofilemany', ['id' => auth()->user()->id]) }}" >
#csrf
//username
<input class="col-md-3 container justify-content-center form-control {{$errors->has('username') ? 'has-error' : ''}}" type="text" name="username" id="username" placeholder="{{ Auth::user()->username }}" Value="{{ Request::old('username') }}" />
//bio
<textarea class="border-info form-control {{$errors->has('bio') ? 'has-error' : ''}}" type="text" name="bio" id="bio" placeholder="{{ Auth::user()->bio }}" Value="{{ Request::old('bio') }}"></textarea> <br />
<button id="btn-login" class="btn btn-md r btn-primary" type="submit" > <i class="fa fa-cog"> </i> Save Changes </button>
</form>
StudentController.php // my users controller
public function updateprofilemany(Request $request, $id)
{
// Validation
$this->validate($request, [
'username' => 'max:15|unique:Students',
'bio' => 'max:50',
]);
if ($request->has('username'))
{
// if there is a new username value
$username = $request->input('username');
} else {
$username = Auth::user()->username;
}
if ($request->has('bio'))
{
// if there is a new username value
$bio = $request->input('bio');
} else {
$bio = Auth::user()->bio;
}
// Find the user and inject the new data if there is then go back to
myprofile
$students = User::find($id);
$students->username = $username;
$students->bio = $bio;
$students->save();
//redirect
return redirect()->route('myprofile');
}
it can read the data but if I add it inside the if else statements it requires the both fields.
I tried passing default data like this
myprofile // users view
<form class="form-group" method="POST" action="{{ route('updateprofilemany', ['id' => auth()->user()->id, 'username' => auth()->user()->username, 'bio' => auth()->user()->bio]) }}" >
#csrf
//username
<input class="col-md-3 container justify-content-center form-control {{$errors->has('username') ? 'has-error' : ''}}" type="text" name="username" id="username" placeholder="{{ Auth::user()->username }}" Value="{{ Request::old('username') }}" />
//bio
<textarea class="border-info form-control {{$errors->has('bio') ? 'has-error' : ''}}" type="text" name="bio" id="bio" placeholder="{{ Auth::user()->bio }}" Value="{{ Request::old('bio') }}"></textarea> <br />
<button id="btn-login" class="btn btn-md r btn-primary" type="submit" > <i class="fa fa-cog"> </i> Save Changes </button>
</form>
Web.php // routes
// calls user update profile many function
Route::post('/updateprofilemany/{id}', [
'uses' => 'StudentController#updateprofilemany',
'as' => 'updateprofilemany',
'name' => 'updateprofilemany'
]);
Student Controller
public function updateprofilemany(Request $request, $id, $username ,$bio)
{
//functions like above
}
and add it the specific function like
public function Functionname(Request $request, $id, $username, $bio)
can you guys help me with this thank you!
When you use Value="{{ Request::old('username') }}" in your username field, it may be empty because it doesn't have any value in the first time you open that page.
And in the controller when you use if ($request->has('username')) , it returns true because the username field is sent but with empty value.
You should check the username field for empty value and then continue ...
for example :
if ($request->filled('username')) {
// do something
}
If you only want to change the data when it is in the request you can just pass a default value to the input function. This will use the value if the key is not present in the request. If the key exists but it is an empty string then you can check with a ternary statement to see if there is a value.
This is probably the most simple way to write it:
public function updateprofilemany(Request $request, $id)
{
$this->validate($request, [
'username' => 'max:15|unique:Students',
'bio' => 'max:50'
]);
// get the user
$student = User::find($id);
// just pass the default value as the old username if the key is not supplied
// and if it is an empty string it will also use the old username
$student->username = $request->input('username', $student->username)
?: $student->username;
// also pass the default here as the old bio
$student->bio = $request->input('bio', $student->bio)
?: $student->bio;
$student->save();
}
I create form in Laravel:
<form action="/redeem" method="get" class="sidebar-form">
<div class="input-group">
<input type="text" name="key" class="form-control" placeholder="ENTER VOUCHER CODE">
<span class="input-group-btn">
<button type="submit" name="search" id="search-btn" class="btn btn-flat"><i class="fa fa-search"></i>
</button>
</span>
</div>
</form>
and now when I try to submit that I get:
http://localhost:8888/redeem?key=NBtGJ5pZls&search=
but I need to get just:
http://localhost:8888/redeem/NBtGJ5pZls
also in route I have:
Route::get('/redeem/{key}', 'OrdersController#redeem');
How to get redirected to redeem/NBtGJ5pZls with my form?
Change your route to:
Route::post('/redeem', 'OrdersController#redeem');
And then get key in controller:
public function redeem(Request $request)
{
$key = $request->key;
And finally, change your form:
<form action="/redeem" method="post" class="sidebar-form">
{{ csrf_field() }}
You've got 2 options:
The first is let your frontend code be the way it is, update the route, and work with the GET parameter.
The second one is using some javascript to rewrite the URL you want to access.
For example this (it's using jQuery):
$('#search-btn').click(function() {
var key = $('input[name=key]').val();
window.location.href = '/redeem/' + key;
});
I prefer the first one, because javascript can be modified by the end-user.