Can't send data with AJAX to Laravel Controller - javascript

I'm trying to do detach some data from my database. I'm trying to send 2 different data to my controller with Ajax but couldn't make it. I need the domain_id and the tag_id.
Thats how it looks right now:
#foreach($domains as $domain)
<tr>
<td>
#foreach($domain->tags as $tag)
<span><a href="#" data-tag-id="{{ $tag->id }}"
data-domain-id="{{ $domain->id }}">{{ $tag->name }}</a></span>
#endforeach
</td>
</tr>
#endforeach
Now I have the domain_id and the tag_id in the <a> tag. I'm trying to send both of them to my controller with Ajax, To detach them from my pivot table and thats it.
JS code:
$('a[data-tag-id]').click(function () {
var tag_id = $(this).attr('data-tag-id');
var domain_id = $(this).attr('data-domain-id');
$.ajax({
url: 'detaching',
type: 'GET',
data: {tag_id: tag_id, domain_id: domain_id},
dataType: 'json',
success: function (data) {
console.log('worked!');
}
});
});
Route Code:
Route::get('detaching', 'DomainController#detach2');
Controller Code:
public function detach2()
{
$input = Input::get('all');
$domain = Domains::findOrFail($input['domain_id']);
$domain->tags()->detach($input['tag_id']);
}
This don't work and I don't even know if the gets Ajax code called. I'm trying to console.log() some things out but I don't get anything back. I don't even know if the code reaches the controller function. I don't have much knowledge about Ajax or JS at all. Can someone maybe help me there?
LITTLE UPDATE
I've tried an easy:
$('a[data-tag-id]').click(function () {
console.log('YES');
});
But this haven't worked either, So it doesn't jumps in the click function all I guess.

Try This,
Give a class to your anchor tag like.
{{ $tag->name }}
Change your route to
Route::get('detaching/{tag_id}/{domain_id}', 'DomainController#detach2');
Chnage your controller function to
public function detach2($tag_id, $domain_id)
{
//$input = Input::get('all');
$domain = Domains::findOrFail($domain_id);
$domain->tags()->detach($tag_id);
}
Change your JS file to
(function ($) {
$(document).ready(function () {
$(document).off('click', '.get-link');
$(document).on('click', '.get-link', function () {
var domain_id = $(this).data('domain-id');
var tag_id = $(this).data('tag-id');
$.ajax({
type: 'GET',
url: 'detaching'+ '/' + tag_id + '/' + domain_id + '/',
success: function (data) {
console.log('worked!');
},
error: function (data) {
console.log('Error:', data);
}
});
});
});
})(jQuery);

Related

Can´t send post wirth javascript to another page

I´m trying to send the variable idValue to a class called cambio_prenda.php with the following code
function reply_click(clicked_id)
{
var idValue = clicked_id;
$.ajax({
type: "POST",
url: 'cambio_prenda.php',
data:{"cambio" :idValue},
success: function(response)
{
alert("exito");
}
});
}
This code works when i use it in the same class, but when I try to call it from the another class with this code it doesn´t work
<?php
if(isset($_POST['cambio'])){
$item = $POST['cambio'];
echo($item);
}
?>

Redirect to another page after Ajax call?

so this is a hard one for me to try and explain. I have a razor page that when a button is clicked it calls a javascript function which makes an ajax call to a handler in the back end. The handler does some stuff and gets a id that I want to pass to another page. I am trying to use the RedirectToPage function in the back end but the screen never opens. It successfully calls the handler but when the handler does its return, nothing happens. Is there a way to do this?
Here is the javascript/ajax code that gets called from a button being clicked.
#section scripts{
<script>
// Get the account ID Data from the row selected and return that to the program.
function getIDData(el) {
var ID = $(el).closest('tr').children('td:first').text();
var iddata = {
'ID': ID
}
console.log(iddata);
return iddata;
}
// Submit the data to a function in the .cs portion of this razor page.
$('.copybtn').click(function () {
var accountid = JSON.stringify(getIDData(this));
$.ajax({
url: '/Copy_Old_Account?handler=CopyData',
beforeSend: function (xhr) {
            xhr.setRequestHeader("XSRF-TOKEN",
                $('input:hidden[name="__RequestVerificationToken"]').val());
        },
type: 'POST',
dataType: 'json',
data: { offenderid: offenderid },
success: function (result) {
},
});
});
</script>
}
For my code behind code that I am calling from the ajax call, that's below here:
public ActionResult OnPostCopyData (string accountid)
{
// Do my other stuff here
return RedirectToPage("Account_Information", new { id = account.Account_ID });
}
Any help would be appreciated and if doesn't make sense, I can try and clear up any questions.
I think this is what you want, I did something similar in an MVC 5 project and I haven't tested it in Razor Pages yet:
This would be your method, note that you should add your Controller to the Url.Action, and I personally haven't tried passing a parameter along with the url but I image it'll work just fine
[HttpPost]
public ActionResult SubmitSomething()
{
return Json(new { redirectUrl = Url.Action("Account_Information", "YOUR_CONTROLLER_NAME", new { id = account.Account_ID }) });
}
And then this would be your Ajax request, I updated the success portion
// Submit the data to a function in the .cs portion of this razor page.
$('.copybtn').click(function () {
var accountid = JSON.stringify(getIDData(this));
$.ajax({
url: '/Copy_Old_Account?handler=CopyData',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
type: 'POST',
dataType: 'json',
data: { offenderid: offenderid },
success: function (result) {
if (result.redirectUrl !== undefined) {
window.location.replace(result.redirectUrl);
} else {
// No redirect found, do something else
}
},
});
});
This isn't tested, so I can only hope that it works for you right now
Edit: Updated the Url.Action to use OP's view names and parameters
Redirect to page returns a 301 response, which will be in the format:
HTTP/1.1 301 Moved Permanently
Location: http://www.example.org/index.asp
To redirect after the ajax call you can redirect to the requested url by:
success: function (result) {
window.location = result.getResponseHeader('Location');
}

Changing data-tooltip with AJAX isn't working

I have a button in my html template:
<a class="tooltipped" id="stash_recipe_tooltip" data-position="bottom" data-delay="50"
data-tooltip="{{ stash_tooltip }}">
<div id="stash_recipe_btn" class="detail_footer_btn btn-floating col2 center"> + </div>
</a>
later, in the html file, I have:
<script>
function add_recipe_to_stash() {
var stash_plus_or_minus = document.getElementById("stash_recipe_btn").innerHTML
$.ajax({
url: '/ajax/add_recipe_to_stash/',
type: 'GET',
data: {
# this goes to a django view that, in essence, returns a new 'stash_tooltip' var and 'stash_plus_or_minus' var
'stash_plus_or_minus': stash_plus_or_minus,
},
dataType: 'json',
success: function (data) {
document.getElementById("stash_recipe_btn").innerHTML = data.stash_plus_or_minus;
$("#stash_recipe_tooltip").attr('data-tooltip', data.stash_tooltip);
}
});
}
function addClickHandlers() {
$("#stash_recipe_btn").click( add_recipe_to_stash );
}
</script>
It seems like
$("#stash_recipe_tooltip").attr('data-tooltip', data.stash_tooltip);
should be changing my tooltip, but nothing happens. Any idea how to successfully update the data-tooltip without refreshing the page? I've tried different variations of the above line but I can't get it to update.
You can use the tooltip function for that:
success: function (data) {
document.getElementById("stash_recipe_btn").innerHTML = data.stash_plus_or_minus;
$("#stash_recipe_tooltip").tooltip('tooltip', data.stash_tooltip);
}
Try this:
$('#someElement').prop('tooltipText', 'new title');

javascript ajax and post value is working all together why

I am having a some problem in my java script and to get the request.
This is the HTML
<form method="post" id="searchform">
<div align="center" class="col-md-10">
<input type="text" id= "contentSearch" name="contentSearch" >
</div>
<div class="form-group"><button type="submit" class="btn btn-default" id="submitSearch">
<i class="fa fa-search"></i> Search
</button></div>
</form>
<----Scenario 1 ---->
This script works fine and post the value and as ajax it never reload the page
<script>
$(document).ready(function () {
$("#submitSearch").on('click', function (e) {
e.preventDefault();
e.stopPropagation();
var data = {};
data['contentSearch'] = $('#contentSearch').val();
// Submit data via AJAX§
$.ajax({
url: '/home',
type: 'post',
data: data,
success: function (data) {
// do i need to do something here !!
}
});
});
});
</script>
When i check the POST value i can see the value is been POST.
The Problem is when i try to get the request data from controller like ---
$post_value = $request->request->get('contentSearch');
print_r($post_value);
OUTPUT : empty
<----Scenario 2 ---->
This script have a problem i think, because it reload the page for returning the result and displaying the value ---
<script>
$(document).ready(function () {
$("#searchform").on('submit', function (e) {
e.preventDefault();
var data = {};
data['contentSearch'] = $('#contentSearch').val();
$.ajax({
url: '/home',
type: 'post',
data: data,
success: function (data) {
}),
return false;
});
});
</script>
than i am able to get the post value like so--
$post_value = $request->request->get('contentSearch');
But the problem is in the second script the page is always loading when return the request which is not a ajax behave.
And in the first script i think because of the **e.preventDefault();** i am not getting the POST value in my controller.
Expected result ---
Option 1 : Do something so i can get the POST value in my controller
Option 2 : Fix this script so the page do not load to return the result and display
I am working on symfony framework .
Can someone please help me to fix this problem, i am really getting sick of to solve this problem.
Thanks a lot on advanced.
Like I mentioned in the comments, you need to be targeting the submit on the form. Not a click event. When targeting the click you are firing both the click and submit events, hence the reload.
$(document).ready(function () {
$("#searchform").on('submit', function (e) {
var data = {};
data['contentSearch'] = $('#contentSearch').val();
$.ajax({
url: '/home',
type: 'post',
data: data,
success: function (data) {
}
});
return false;
});
});

laravel ajax post issue

I have been working on this all weekend and cant get it to work. I can get it working using get but not post. Im using Laravel 4 and jquery.
My JS looks like this:
$('.status').on('click', function(){
var $modal = $('#ajax-modal');
var id = $(this).attr("id");
setTimeout(function(){
$modal.load('../status/'+id, '', function(){
$modal.modal();
});
});
});
which opens a bootstrap modal just fine and loads the status page. On that page, I set a button with an id of the user, and when that is clicked, I call another JS snippet:
$modal.on('click', '.update', function(){
$modal
.find('.modal-body')
.html('<div class="progress progress-striped active"><div class="bar" style="width: 100%;">Processing ...</div></div>');
var PostData = 'UserId='+$(this).attr("id");
$.ajax({
type: "POST",
url: "",
data:PostData,
success: function(msg){
$('.update').prop('disabled', true);
setTimeout(function(){
$modal
.find('.modal-body')
.html('<div class="alert-show-success"><img src="../../../public/assets/img/icons/accept.png" />This user was successfully de-activated!</div>');}, 1500);
},
error: function(){
//alert("failure");
setTimeout(function(){
$modal
.find('.modal-body')
.html('<div class="alert-show-failed"><img src="../../../public/assets/img/icons/failed.fw.png" />There was an error processing this request!</div>');}, 1500);
}
});
});
The modal loads fine, and it finds the status page fine, but nothing actually happens in the controller: (I hard coded the 2 in there to test it.
public function postStatus()
{
DB::table('users')
->where('id', 2)
->update(array('activated' => 0));
}
Not sure what I am missing. Any help is greatly appreciated.
I'd recommend making the changes suggested by #Arda, but I believe your jquery is incorrect. You are setting the key to be unique, and the value to be data.
Try this:
$("a.delete").click(function () {
var id = $(this).attr("id");
$.ajax({
type: 'post',
url: "{{URL::route('user_status')}}",
data: {'id' : id}
});
This requires using a blade template, but that's pretty good practice anyway.
Try like this:
First, make your route named for URLs to be more dynamic:
Route::post('users/status', array('as'='user_status', 'uses'=>'Controllers\UsersController#postStatus');
Then, alter your post jQuery (which I think is the error's source)
$("a.delete").click(function () {
var $id = $(this).attr("id");
$.post('{{URL::route('user_status')}}',
{
id: $id
}
);
});
And your controller method:
public function postStatus()
{
if(Request::ajax()) {
$thisID = Input::get('id');
DB::table('users')
->where('id', $thisID)
->update(array('activated' => 0));
}
}
Didn't try, but should work.

Categories

Resources