how to set href attribute in javascript with value to call route - laravel

i am trying to set url in jquery ajax, as
$.ajax({
url : "{{url('addtocart')}}",
type : "POST",
data : {_token: CSRF_TOKEN, username:username, userType:userType,
table_no:table_no, order_no:order_no, cname:cname,
tname:tname, dname:dname, dish_qty:dish_qty,
chefnote:chefnote
},
success : function(data){
//console.log(data);
$('#cartOrder').empty();
for (var i = 0; i < data.length; i++) {
drawRow(data[i]);
}
function drawRow(rowData) {
var row = $("<tr />")
row.empty();
$("#cartOrder").append(row);
row.append($("<td contenteditable='true'>" + rowData.dish + "</td>"));
row.append($("<td contenteditable='true'>" + rowData.dish_qty + "</td>"));
row.append($("<td contenteditable='true'>" + rowData.chefnote + "</td>"));
row.append($("<td>" +"<a href='"<?php echo 'Edit';?>"' value='"+rowData.ord_id+"'>" +"Edit | "+"</a>" +"<a href='' value='"+rowData.ord_id+"'>" +"Delete"+"</a>" + "</td>"));
}
}
as there u can see at last line href="Edit", i want to call route on click of that link with value as
<a href="<?php echo 'Editcat/'.RowData->ord_id; ?>"
i know this not the way, how can i do that ?? thank you.

There are many options of achieving this:
First:
You can keep the call url in any of the tag's data attributes, suppose this is your container related to the ajax functionality:
<div class="_cart" data-edit-url="{{route('cart.edit',['id'=>$cartItem->id])}}">
</div>
and access it using the following code:
$('._cart').data('edit-url');
but before executing this line http://stackoverflow.com/users/6285124/rohit-khatri
Define a name for your route, like:
Route::get('Edit/{id}','Controller#function')->name('cart.edit');

Based on your route you just have to change it like this -
Route
Route::get('/Edit/{id}',[
'uses' => 'Controller#function',
'as' => 'Edit',
]);
and than you can use it in your view like this -
Edit
//this is your route ^ here will be your Id ^
than in your Controller for edit you can use this Id -
public function yourEditFunction($id){
//use $id here
}

Related

Laravel - How to send data from a checkbox button to a controller using Ajax

I am trying to have a toggle button (checkbox) changing some data in my MySQL database. I essentially want to to have a nice admin site in which I can unlock users to certain features on the site with a nice on/off switch.
Everything seems to be set up correctly, but my controller doesn't react or get triggered at all.
Right now, I have a working toggle button in my view triggering a javascript function. In that javascript function, I have already set up data that I want to transmit over to my controller.
I have also set up Ajax in my Javascript. Apparently Ajax has this part in its code (see my code if you need to know what I mean) where it says "success" or "error". Before entering the {{csrf_token()}} token, I always ended up in the error section. However, now I always enter the "success" section when toggling my button.
Now to my problem:
Although Ajax confirms a success, literally nothing happens within my controller. I have no idea how to change this as there is no error code whatsoever, either.
This is my button
<input id = "company_{{$company->id}}" data-id="{{$company->id}}" onchange=myFunction({{$company->id}}) value = {{$company->permissionlevel}} class="toggle-class" type="checkbox" data-onstyle="success" data-offstyle="danger" data-toggle="toggle" data-on="Active" data-off="InActive" {{ $company->permissionlevel ? 'checked' : '' }}>
This is my javascript (the relevant part)
var test = 12; // A random variable for this example
$.ajax({
method: 'POST', // Type of response and matches what we said in the route
url: 'home/update', // This is the url we gave in the route
data: {'test' : test, _token: '{{csrf_token()}}'}, // a JSON object to send back
success: function(response){ // What to do if we succeed
console.log(response);
//alert("Ajax success");
},
error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
//alert("Ajax error");
}
});
This is my controller function (just to see what happens)
public function update (Request $request)
{
//echo "This is a test";
$data = $request->all(); // This will get all the request data.
dd($data); // This will dump and die
return $data;
}
Route
Route::post('/home/update', 'HomeController#update');
Expected result:
Controller throws something at me. Currently all I want is to see if my controller reacts to the button press or if I can request the data Ajax is supposed to send over.
Actual result:
Nothing happens on my controller's side
I have found a solution by myself. I essentially added this code to my controller:
public function update (Request $request, $id, User $user)
{
$newPermLevel = $request->input('value');
$override = (int) $newPermLevel;
\DB::table('users')->where('id',$id)->update(array(
'permissionlevel'=>$override,
));
}
However, I need to add these small lines at the beginning of my controller right behind the namespace:
use Illuminate\Http\Request;
use App\User;
Just for completion, I will leave the other necessary code here as well for anybody in the need to update his database with a toggle / switch button
Here's my route
Route::post('/home/update/{id}', 'HomeController#update');
Here's my HTML
based on the current state of a button, I make an if statement (using blade engine) either creating a turned off or turned on switch. The button has a value, which essentially is the current database entry (in my case it is either 1 or 0 that I want to jump up and forth with)
#if ($company->permissionlevel == 0)
<div class="col-sm-5">
<label class="switch">
<input id = "company_{{$company->id}}" data-id="{{$company->id}}" onchange=myFunction({{$company->id}}) value = {{$company->permissionlevel}} class="toggle-class" type="checkbox" data-onstyle="success" data-offstyle="danger" data-toggle="toggle" data-on="Active" data-off="InActive" {{ $company->permissionlevel ? 'checked' : '' }}>
<span class="slider round"></span>
</label>
</div>
#endif #if ($company->permissionlevel == 1)
<div class="col-sm-5">
<label class="switch">
<input id = "company_{{$company->id}}" data-id="{{$company->id}}" onchange=myFunction({{$company->id}}) value = {{$company->permissionlevel}} class="toggle-class" type="checkbox" data-onstyle="success" data-offstyle="danger" data-toggle="toggle" data-on="Active" data-off="InActive" {{ $company->permissionlevel ? 'checked' : '' }}>
<span class="slider round"></span>
</label>
</div>
#endif
At last, my Javascript making use of Ajax. The code essentially check if the value of out switch is currently on 0 (then switch it to 1) or on 1 (then switch it to 0). Additionally, I define a variable to grab the current user's (company's ID), so that the controller later on knows to which user I refer.
<script>
function myFunction(id) {
var value = document.getElementById("company_" + id).value;
if (value == 1){
document.getElementById("company_" + id).value = 0;
//alert(document.getElementById("company_" + id).value);
}
if (value == 0){
document.getElementById("company_" + id).value = 1;
//alert(document.getElementById("company_" + id).value);
}
var company_id = id;
var newPermLevel = document.getElementById("company_" + id).value;
$.ajax({
method: 'POST', // Type of response and matches what we said in the route
url: 'home/update/'+company_id, // This is the url we gave in the route
data: {
'company_id' : company_id,
'value' : newPermLevel,
_token: '{{csrf_token()}}',
},
// a JSON object to send back
success: function(response){ // What to do if we succeed
console.log(response);
//alert("Ajax success");
},
error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
//alert("Ajax error");
}
});
}
</script>
Consider this question closed, but thanks for reading along. I hope anybody googling desperately for a similar solution can make use of my code. Not all heroes wear capes :)

codeigniter Click button to call a view

I am having a view with 2 buttons in my codeigniter view:
<div class="btn-main col-md-3 col-md-offset-3">
<button id="simu-mono" type="button" class="btn btn-default">SIMULATION MONO SITE</button>
</div>
<div class="btn-main col-md-3">
<button id="simu-multi" type="button" class="btn btn-default">SIMULATION MULTI SITE</button>
</div>
I would like to call another a controller to launch then a view when the button is clicked
I tried out to call the controller simu_mono by javascript, putted on /controller/simu_mono.php but doesn' t work
$(document).ready(function(){
$("#simu-mono").click(function(){
type:'GET',
url:'simu_mono'
});
$("#simu-multi").click(function(){
});
});
simu_mono.php:
<?php
class simu_mono extends CI_Controller {
public function index()
{
$this->load->view('simu_mono');
echo 'Hello World!';
}
}
?>
Thanks for your helps
Cheers
Please, if u want to redirect only use following code:
$(document).ready(function(){
$("#simu-mono").click(function(){
window.location = base_url + "/simu_mono";
});
$("#simu-multi").click(function(){
window.location = base_url + "/simu_multi";
});
});
Note that you might need base_url, use this snippet to load base_url in JavaScript variable
<script>
base_url = <?= base_url()?>
</script>
put code above in some kind of view that is loaded always (before any other JavaScript code is executed)
Additional step would be to set up routes that take care of ugly underscore symbol (_)
something like:
routes.php
$route['simu-mono'] = "simu_mono";
$route['simu-multi'] = "simu_multi";
this way you go to your page and controller following way: yourserver.ufo/simu-mono and yourserver.ufo/simu-multi
You're not doing any class of AJAX call within your javascript. I assume you're using jQuery, so, your call should be something like:
$("#simu-mono").click(function(){
$.ajax({
url: "http://your-url.com/controller/method",
type: 'post', // <- Or get option, whatever you prefer
dataType: 'json', // <- This is important to manage the answer in the success function
//data: { param1: "value1", param2: "value2"}, <- You could add here any POST params you wanted
success: function(data){
if (data.view) {
$('#here_view').html(data.view); // <- '#here_view' would be the id of the container
}
if (data.error){
console.log(data.error);
}
}
});
});
This will call your method, where you will have to indicate you want to pass the view:
<?php
class simu_mono extends CI_Controller {
public function index()
{
$return = array(
'view' => $this->load->view('simu_mono')
);
echo json_encode( $return );
}
}
?>
json_encode will allow you easily pass vars and data from PHP to your javascript, and manage them in the client view. As you see in the javascript, I added data.error, this is just in case you'll have more logic, maybe change the view you're sending, send an error if you sent data and want to control them, etc.
Of course, in your javascript you could take the url from the clicked button, and in data.view parat of the success function, you may print in the screen a modal, send the view to a container, whatever you wanted, XD

Jquery returning all to much data I only want the table

Hi im attempting to use jquerys ajax to update a form after a GET request, I simply want the table to update but it send through the page headers as well.
First Here is my script, its small so i will include it all,
var wishorder = {
init: function(config){
this.config = config;
this.bindEvents();
},
bindEvents: function(){
this.config.itemSelection.on('click',this.addWish);
},
addWish: function(e){
console.log('working');
var self = wishorder;
$.ajax({
url: $(this).attr('href'),
type: 'GET',
data: {
sku: $(this).data('sku'),
action: $(this).data('action'),
qty: $(this).data('qty')
},
success: function(results){
//here is where is would like to repopulate the div
//but its outputting the whole page
console.log(results);
}
});
e.preventDefault();
}
};
wishorder.init({
itemSelection: $('#carttable a'),
form: $('#cartfrm')
});
I can see that it is returning the results i want but it wraps it in html as in page header.
Here are the php function its calling.
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_GET['action'] == 'move'){
list($sp_type, $pid) = $this->parse_sku($_GET['sku']);
$qty = (filter_var($_GET['qty'], FILTER_VALIDATE_INT, array('min_range' >= 1)))?$_GET['qty']:1;
$q = "CALL add_to_wish_list('$this->uid', '$sp_type', $pid, $qty)";
$this->query($q);
$q = "CALL remove_from_cart('$this->uid', '$sp_type', $pid)";
$this->query($q);
$q = "CALL get_shopping_cart_contents('$this->uid')";
$this->query($q);
$this->read();
$this->outcart();
exit();
}
and the outcart function wich generates the html for the div
function outcart(){
echo "<div id=\"cartcont\" class=\"cartitems\"><form action=\"/cart.php\" method=\"post\"><table id=\"carttable\"><tr class=\"theads\"> <th class=\"titm\" >Item</th> <th >Quantity</th> <th >Price</th> <th>Subtotal</th> <th class=\"topt\" >Options</th>";
$total = 0;
while($row = $this->_result->fetch_object()){
$price = $this->get_just_price($row->price, $row->sale_price);
$subtotal = $price * $row->quantity;
$total += $subtotal;
echo "<tr class=\"tdata\">
<td>".$row->category." :: ".$row->name."</td>
<td><input type=\"text\" name=\"quantity[".$row->sku."]\" value=\"$row->quantity\" size=\"2\">
<td>$".$price."</td>
<td>$".number_format($subtotal, 2)."</td>
<td> Move To Wishlist <br> Remove From Cart </td>";
}
echo "</tr><tr class=\"ttotals\"><td colspan=\"3\" ><strong id=\"carttotal\">TOTAL:</strong></td>
<td colspan=\"2\" > $".number_format($total,2) ." </td>
</tr>";
echo "</table>";
echo "<div id=\"cartmnbtns\"><p><input type=\"submit\" value=\"UPDATE QUANTITIES\" class=\"buttoncart1 green\"><br>Checkout</p> </div></form>";
}
So i just want to repopulate the table really or the cartcont div with the results, where am missing the point?
The page you're calling is url: $(this).attr('href') and that's a web-page you're just on with all headers and stuff... You have to put your functions in a separate .php file that doesn't contain a whole web-page frame and only outputs the text you want.
If that's not possible then create in your success callback function with document.createDocumentFragment(), pass the whole response inside the fragment and pull out your stuff you need with something like myHTML = docFrag.getElementsByTagName('div')[0] and then pass this with append to your form.
You might also want to set something like contentType: "text/plain; charset=utf-8" in your ajax call.
By the way: If you're not using the convenience of parsing variables inside strings you might want to use a different way (the other quotes) of writing your strings, as it's then faster, so:
echo '<tr class="tdata">...'

add submit to delete comment using ajax , php

Hi, I use a php code to view the all comments to any post from my sql and I want to add a submit button to every comment in order to delete it without refreshing the page, I mean using AJAX i don't know how to write that codes and connect it with html codes i want add submit like this :
<form>
<input type="submit" id="deletecomment">
</form>
and connected it with AJAX and delete.php page to delete the comment (ajax,delete.php)???????
this is my codes
$result = mysql_query ("select * from post_comments WHERE link ='$getlink' order by link asc");
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$link = $row['link'];
$time = $row['time'];
$content = nl2br($row['content']);
$name = ($row['link'] != '') ? '<h3 style="color:blue">'.$row['name'].'</h3>' : $row['name'];
$imge = $row['imge'];
echo '
<div class="commentuserbackground">
<img src="'.$imge.'" width="30px" height="30px">
<div id="comment-'.$id.'" class="username1">'.$name.'</div>
<div class="username2">'.$content.'</div><div class="commenttime"><h4 style="color:#5a5a5a">'.$time.'</h4>
</div></div>';
}
If you already have the jquery lib included in your html, you could do something like this:
# html page
<button data-id="1" class="delete_comment" /> # no need to wrap in form
# At the bottom of the body tag
$(".delete_comment").click(function(e){
e.preventDefault();
var $button = $(this), $comment = $button.parent(), id = $button.data("id");
$.ajax({
type: 'DELETE',
url: "/path/to/comment/" + id,
success: function(){ $comment.remove(); }
});
});

how to pass parameters using auto redirect droplist in codeigniter

Hi guys Im trying to make a drop-down list of countries and when the user select a country that redirect to a specific page created dynamically actually i manage to make the redirection work using javascript, but i need to take more parameters to the method inside the controler like the county "id" with out exposing it on the uri, so is that possible using $_post also i should not use button submit.
this is my code
view page
<?php echo form_open('site/country');
$options = array();
$js = 'id="country" onChange="window.location.href= this.form.CTRY.options[this.form.CTRY.selectedIndex].value"';
$options['#'] = "(please select a country)" ;
foreach ($list as $row):
$value= site_url()."/site/country/".url_title($row->name);
$options[$value] = $row->name ;
endforeach;
echo form_dropdown('CTRY', $options,'',$js);
//$test =array ('number' => 10)
//echo form_hidden($test);
echo form_close();?>
this is my method in controller
function country($data)
{
echo 'this is taking you to county= '.$data;
}
Why don't you do something like #Joseph Silber described.
Use jQuery to perform an ajax request when the drop-down list is changed, also managing the redirect?
Something like;
$('#my-drop-down').change(function() {
$.ajax({
url: '/site/country',
type: 'post',
data: $("#my-form").serialize(),
success: function( response.redirect ) {
window.location.href = response.redirect;
},
error: function( response ) {
alert('Oops');
}
});
});
By using serilaize(), you can post all data from the form, or just add the parameters you want to pass.
E.g data: 'id='+$('#id').val()+'&country='+$('#country').val()

Resources