I'm trying to count the redirections for a website,like when a user clicks on a link that refers to that website.
I'm getting the url through a request like below in my method :
/**
* #Route("/redirections")
* #Method({"GET", "POST"})
*/
public function redirectingtoAction(Request $request) {
$em = $this->getDoctrine()->getManager();
$query ="UPDATE urlproduit SET redirection = redirection + 1 WHERE url ='".$request->get('ur')."';";
$statement = $em->getConnection()->prepare($query);
$statement->execute();
return new Response($request->get('ur'));
}
This is my twig :
<div class="col-4 store-border-button ">
<p data-url="{{url.url}}"
class="btn btn-primary wd-shop-btn pull-right flux"> See the offer </p>
</div>
and this is my ajax call code :
$('.flux').click(function(){
ur=$(this).data('url');
console.log(url);
$.ajax({
type: "POST",
url: "../redirections",
data : { param: 'ur', value: ur },
success: function(data){
//window.location.href=data;
console.log(data);
}});});
When checking the _profiler the ur is always empty like below :
The solution was :
function hits(url){
$.ajax({
type: "POST",
url: "../redirects",
data : { url: url},
success: function(data){
window.location.href=data;
}
});
};
and I modified the button code :
<a href="{{url.url}}" target="_blank" onclick="hits('{{url.url}}');return false;" class="btn btn-primary wd-shop-btn pull-right" id="flux">
See offer </a>
Related
I have a dashboard with some side menus. Each menus loads a page through ajax call after it is clicked.
By default when dashboard is loaded it loads the page, there is also a "dashboard" menu to switch between others like profile and add student.
But if I am at profile page and I refresh It goes back to dashboard page. Also if I try to add student by filling the form and if the form has any error it goes back to dashboard again with all old input data lost.
Web.php
Route::prefix('admin')->group(function(){
Route::get('/dashboard','AdminController#dashboard')->name('admin.dashboard');
Route::get('/login', 'Auth\AdminLoginController#showLoginForm')->name('admin.login');
Route::post('/login', 'Auth\AdminLoginController#login')->name('admin.login.submit');
Route::post('/add_student','AdminController#add_student');
Route::middleware('ajax')->group(function(){
Route::get('/summary','AdminController#summary')->name('admin.summary');
Route::get('/profile', 'AdminController#profile')->name('admin.profile');
Route::get('/add_student_form','AdminController#add_student_form')->name('admin.add_student');
});
});
AdminController.php
public function add_student_form(){
return view('admin.add_student');
}
public function add_student(Request $request)
{
$this->validate($request,[
'name'=>'required|string',
'course_id'=>'required',
'dob'=>'required|date',
'gender'=>'required|string',
'category'=>'required|string',
'qualification'=>'required|string',
'fathername'=>'required|string',
'mothername'=>'required|string',
'mob_no'=>'required|string|max:10',
'address'=>'required|string',
'email'=>'required|email',
'PIN'=>'required|string|max:6',
]);
$student = new Student;
$student->name = $request['name'];
$student->roll_no ='NITTI'.rand(10000,99999);
$student->password = Hash::make($student['mob']);
$student->fees = new StudentFees;
$student->fees->paid_fees = $request['paid_fees'];
$student->fees->balance_fees = 7000;
$student->detail = new StudentDetail;
$student->detail->course_id = $request['course_id'];
$student->detail->gender = $request['gender'];
$student->detail->category = $request['category'];
$student->detail->qualification = $request['qualification'];
$student->detail->fathername = $request['fathername'];
$student->detail->mothername = $request['mothername'];
$student->detail->mob_no = $request['mob_no'];
$student->detail->email = $request['email'] ;
$student->detail->address = $request['address'];
$student->detail->PIN=$request['PIN'];
$student->detail->dob = $request['dob'];
$student->push();
return redirect()->back();
}
add_student.blade.php
<form action="/admin/add_student" method="POST">
#csrf
//It has all the fields here and a submit button
</form>
dashboard.blade.php
<div class="container-fluid">
<div class="row">
<div class="col-2 sidebar">
<img src="{{asset('/img/admin.jpg')}}" class="fit-image">
<p class="text-center">{{Auth::user()->name}}</p>
<hr>
<ul class="list-group">
<li class="list-group-item" id="summary">Dashboard</li>
<li class="list-group-item" id="admin_profile">Profile
</li>
<li class="list-group-item" id="students">Students <i class="fas fa-angle-right ml-5"></i>
<ul class="sidenav list-group">
<li class="list-group-item" id="add_student">Add Student</li>
<li class="list-group-item" id="viewall">View All </li>
</ul></li>
</ul>
</div>
<div class="col-10 dashboard" id="admin">
</div>
</div>
</div>
dashboard.js
$(document).ready(function(){
$.ajax({
url:'/admin/summary',
type: "GET",
success: function(data){
$data = $(data);
$('#admin').html($data).fadeIn();
}
});
});
$(document).on('click','#summary', function(){
$.ajax({
url:'/admin/summary',
type: "GET",
success: function(data){
$data = $(data);
$('#admin').html($data).fadeIn();
}
});
});
$(document).on('click','#admin_profile', function(){
$.ajax({
url:'/admin/profile',
type: "GET",
success: function(data){
$data = $(data);
$('#admin').html($data).fadeIn();
}
});
});
$(document).on('click','#add_student', function(){
$.ajax({
url:'/admin/add_student_form',
type: "GET",
success: function(data){
$data = $(data); produced
$('#admin').html($data).fadeIn();
}
});
});
I tried to redirect()->back->withInput('the fields');, but it didn't work.
If there is better way to load the pages which holds the same page after reloading or form submission I would welcome that.
You could use ajax form posting.
I rewrote code to abstract ajax load.
JS:
$(document).ready(function(){
//load summary by default
loadPage('summary');
//load on click menu item
$(document).on('click','.menu-item', function(){
loadPage($(this).attr('data-page'));
});
//send xcrf token in ajax header
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
//submit form
$(document).on('submit', 'form', function(){
let form = $(this);
$.ajax({
url: form.attr('action'),
type: 'POST',
dataType: 'json',
success: function(data){
if(data.page){
//load page returned in controller
loadPage(data.page);
}
},
error: function(data){
if(data.responseJSON && data.responseJSON.errors){
$.each(data.responseJSON.errors, function(key, value){
//convert laravel dotted rules to jquery selectors
key = key.replace('.', '[').replace(/\./g, '][');
if(key.indexOf('[') !== -1){
key += ']';
}
//do something with errored elements
form.find('*[name="' + key + '"]').addClass('error');
});
}
}
});
return false;
});
});
function loadPage(page){
$.ajax({
url:'/admin/' + page,
type: 'GET',
success: function(data){
$data = $(data);
$('#admin').html($data).fadeIn();
}
});
}
HTML:
Add to <head>:
<meta name="csrf-token" content="{{ csrf_token() }}">
Change sidebar menu:
<ul class="list-group">
<li class="list-group-item menu-item" data-page="summary">Dashboard</li>
<li class="list-group-item menu-item" data-page="profile">Profile</li>
<li class="list-group-item" id="students">Students <i class="fas fa-angle-right ml-5"></i>
<ul class="sidenav list-group">
<li class="list-group-item menu-item" data-page="add_student_form">Add Student</li>
<li class="list-group-item menu-item" data-page="viewall">View All </li>
</ul>
</li>
</ul>
Controller method:
Replace return redirect()->back(); with return ['page' => 'viewall'];
im write ajax code in post url and my userid bt not respond that code
<script>
function InviteLink( id, url ){
console.log(id);
$.ajax({
url: https://abc.hrm.com/auth/login
data: { 'id' : id },
success: function(data) {
}
});
}
</script>
<button onclick="InviteLink('<?php echo $employees->fldUserID; ?>','<?php echo base_url($employee_url); ?>');" style="background-color:#00C292; color:white; font-weight: bold; margin:5px 0px;" title="Invite New Employee" data-toggle="modal" data-target="#invitelink" type="button" class="btn btn-teal btn-circle"><i class="notika-icon notika-mail"></i></button>
**front UI in button i write onclick function and get id and url.... but there are not post in my url please help me solve my problem **
You Have to add method type = "POST" in ajax Like Below
<script>
function InviteLink( id, url ){
console.log(id);
$.ajax({
type: "POST",
url: https://abc.hrm.com/auth/login,
data: { 'id' : id },
success: function(data) {
}
});
}
</script>
I do not understand why it does not work:
Route
Route::delete('/dashboard/booking/deletebooking/{id}','ResourceController#deletebooking')->name('works.deletebooking');
ResourceController
public function deletebooking($id){
$booking = Booking::where('id','=',$id)->get();
$booking->delete();
return response()->json(['success' => true],200);
}
Table
<tr id="{{$booking->id}}">
<td class="roomId">{{$booking->room_id}}</td>
<td class="roomName">{{$booking->name}}</td>
<td class="roomLocation">{{$booking->sede}}</td>
<td class="start">{{$booking->start_date}}</td>
<td class="end">{{$booking->end_date}}</td>
<td>
<input type="hidden" name="_method" value="delete" />
<button class="btn btn-danger btn-xs" id="destroy" data-id="{{$booking->id}}" data-token="{{ csrf_token() }}">
<span class="glyphicon glyphicon-trash"></span>
</button>
</td>
</tr>
Request Ajax
$(".btn").click(function(){
var id = $(this).data('id');
// var $tr = $(this).closest('tr');
$.ajax({
url: "/dashboard/booking/deletebooking/"+id,
dataType: "JSON",
type: 'POST',
data: {
'_token': $('meta[name=csrf-token]').attr("content"),
'_method': 'DELETE',
"id": id
},
success: function ()
{
console.log("it Work");
}
});
console.log("It failed");
});
I have this error:
Request URL: http://pickbooking.local/dashboard/booking/deletebooking/1
Request Method: POST
Status Code: 500 Internal Server Error
Remote Address: 192.168.10.10:80
The issue is in the method used for the ajax call post
// var $tr = $(this).closest('tr');
$.ajax(
{
url: "/dashboard/booking/deletebooking/"+id,
dataType: "JSON",
type: 'POST',
data: {
'_token': $('meta[name=csrf-token]').attr("content"),
'_method': 'DELETE',
"id": id
},
success: function ()
{
console.log("it Work");
}
});
the data will be sent in the body of the request, and in a DELETE request, there is no body. so laravel wont see the _method, or the _token. Either you send them in a GET request and let the _method do it's job (it will be in the url, not in the body), Or use the DELETE method in the ajax call
// var $tr = $(this).closest('tr');
$.ajax(
{
url: "/dashboard/booking/deletebooking/"+id,
dataType: "JSON",
type: 'DELETE',
data: {
'_token': $('meta[name=csrf-token]').attr("content"),
},
success: function ()
{
console.log("it Work");
}
});
Because I think you have an error something like
Method Illuminate\Database\Eloquent\Collection::delete does not exist.
Instead try something like this
$booking = Booking::where('id', '=', $id)->first();
$booking->delete();
so that $booking can have method delete()
Using Joomla:
My problem is when I submit the button, ajax send an empty data array back to my client. Debbuging in the console shows me that datas in the header but the preview and response values are empty.
Here is my code (I am using a modal form from bootstrap).
HTML in my default script:
<form action="<?php echo JRoute::_('index.php?option=com_addproduct&view=addproducts'); ?>" method="post" name="modalMessageForm" id="modalMessageForm" enctype="multipart/form-data">
<input type="file" id="message-image-upload" accept="image/*" style="display:none;" name="message-image-upload">
<textarea class="form-control message-textarea" id="message-textarea" placeholder="Nachricht..." name="new-message" rows="4"></textarea>
<button type="button" id="button-close-message" class="btn btn-default btn-block btn-message-close" style="display:none; margin-top:5px;"><?=JText::_( 'COM_ADDPRODUCT_MODAL_MESSAGES_CLOSE')?></button>
</form>
JQuery / Ajax:
$(document).on("submit", "#modalMessageForm", function(e)
{
var form = $('#modalMessageForm').get(0);
e.preventDefault();
var formData = new FormData(form);
for(var pair of formData.entries()) {
console.log(pair[0]+ ', '+ pair[1]);
}
$.ajax({
crossDomain: true,
type: "POST",
url: "index.php?option=com_addproduct&task=sendMessages&format=json",
data: formData,
dataType: "json",
processData: false
})
.done(function(data, textStatus, jqXHR){
console.log('Message: '+data.new-message+' PicName: '+data.img);
})
});
Here my controller.php:
public function sendMessages()
{
JResponse::setHeader('Content-Type', 'application/json', true);
$app = JFactory::getApplication();
$input = $app->input;
$new-message = $input->getString('new-message', '', 'RAW');
$img = $_FILES['message-image-upload']["name"];
$img = JFile::makeSafe($img);
$results=array(
'new-message' => 'new-message',
'img' => $img
);
echo json_encode($results);
$app->close();
}
I got the datas / variables in the console log.
it is:
new-message: null,
img: null
trying to set contentType: false will give me an 500 error.
Thank you very much
That´s the info from my network
enter image description here
I figure something out.
It´s the URL in my ajax command.
When I am using a normal url like
url: 'upload.php'
that will work and then I can set the
contentType: false,
But this is not safety enought.
I just want to use this url
url: "index.php?option=com_addproduct&task=sendMessages&format=json",
But then I got the error message that the view is not found. That´s very strange.
I'm trying to post form data to a php file that will then handle a mysql request. But before I do the mysql, I'm trying to connect to the php file.
The request is Cross-Domain.
When i submit the form, i get the error: {"readyState":4,"status":200,"statusText":"success"}
You can see the test page here: http://jonathan-tapia.mybigcommerce.com/store-locator/
form code:
<div class="map-search">
<h1>Give us your zip code. We'll tell you where to find us.</h1>
<div id="map-form">
<form id="lookup-form" action="http://dev.visioncourse.com/customers/baldguy/index.php" method="post">
<p>Within
<select id="distance" name="distance">
<option value="10">10</option>
<option selected="selected" value="25">25</option>
<option value="50">50</option>
<option value="100">100</option>
</select>
miles of
<input id="zipcode" type="text" name="postalcode" value="" size="8" />
<input id="lookup" type="submit" value="Look Up" />
</p>
</form>
</div>
</div>
<div class="map-results"> </div>
updated JS:
<script type="text/javascript">// <![CDATA[
//submit form
$('#lookup-form').submit(function(event) {
event.preventDefault();
var formdata = $(this);
var link = formdata.attr('action');
var distance = $('#distance').val();
var zipcode = $('#zipcode').val();
console.log('.\n..\n...\n....\nSubmitting Form\n....\n...\n..\n.');
$.ajax({
crossDomain: true,
type: 'POST',
url: link,
data: {
'distance': distance,
'postalcode': zipcode
},
dataType: 'jsonp',
error: function(data) {
console.log('error: ' + data);
},
success: function(data) {
console.log('success: ' + data);
},
xhrFields: {
withCredentials: true
}
});
});
// ]]>
updated php file:
<?php
$arr = array();
$distance = $_POST['distance']
$zip = $_POST['postalcode'];
if(isset($distance) && isset($zip)) {
array_push($arrr, {'d': $distance, 'z': $zip});
}
echo json_encode($arr);
?>
error i'm receiving from console:
GET http://dev.visioncourse.com/customers/baldguy/index.php?callback=jQuery17203092896034941077_1451698154204&distance=25&postalcode=85251 jquery.min.js:4
EDIT:
The php file will get the distance and zip code from the form and connect to a mysql database for a google maps store locator. so when a person submits the radius and the zip code it will display results. but all of this will be on the php file.
The file doing the form submission will submit the form, wait for the php to do it's work, then display the php file with the results
Try it with data: {"distance": distance, "zipcode": zipcode},.
In your code you insert the value of the variables twice instead of a name and a value.
Also, you need to send the zipcode with the name of 'postalcode'. Otherwise your phpscript wouldn't find it.
you can try this way:
javascript:
<script>
var formdata = $(this);
var link = formdata.attr('action');
var distance = $('#distance').val();
var zipcode = $('#zipcode').val();
$.ajax({
type: 'GET',
url: link,
data: {"distance": distance,"postalcode": zipcode},
async: false,
jsonpCallback: 'jsonp_callback',//name of function returned from php
contentType: "application/json",
dataType: 'jsonp',
success: function(r) {
console.log(r);
},
error: function(e) {
alert(e.message);
}
});
</script>
php:
<?php
$arr = array();
$distance = $_GET['distance'];//sample 123
$zip = $_GET['postalcode'];//sample 65455
if(isset($distance) && isset($zip)) {
$arr = array('d'=> $distance, 'z'=> $zip);
}
$json = 'jsonp_callback(';
$json .= json_encode($arr);
$json .= ');';
echo $json;
?>
response:
jsonp_callback({"d":123,"z":65455});