how to pass $(this).data() in ajax request - javascript

i need to pass $(this).data into success func in ajax. here is my code
var product_id = $(this).data("product_id");
var url = "{{ route('client.add_wishlist')}}";
$.ajax({
url: url,
type: "POST",
dataType: "json",
data: {
product_id: product_id,
_token: "{{ csrf_token() }}",
},
success: function (data) {
$(this).addClass("wishlist-comp-saved");
},
});
But $(this).addClass('wishlist-comp-saved'); is not working inside success: function(data) {}

$(this) will change context when called. When inside of the success: function (data), $(this) is not the same as it was inside of whatever is calling this $.ajax() request.
For your issue, you simply have to set $(this) as a variable before your $.ajax() request, and reference it in the success: function():
var product_id = $(this).data("product_id");
var url = "{{ route('client.add_wishlist')}}";
var that = $(this);
$.ajax({
url: url,
type: 'POST',
dataType: "json",
data: {
'product_id': product_id
'_token': "{{ csrf_token() }}"
},
success: function(data) {
that.addClass('wishlist-comp-saved');
}
});

Related

Problem on passing array to ajax request in laravel

I am trying to pass array through ajax request
<input type="text" name="item_name[]">
<input type="text" name="address">
$(document).on('click', '#save_info', function () {
var address = $("#address").val();
var item_name = $("[name^='item_name']");
$.ajax({
url: '/save_information',
dataType: "json",
type: 'POST',
data: {
_token: '{{ csrf_token() }}',
address: address,
item_name: item_name,
}
});
});
In my controller
$item_name = $request->item_name;
$array_count = count($item_name);
It makes error. How can i save array value using loop. Thanks in advance
#Mujahidur Rahman Mithun IUB you can write this more shortly by using serializeArray.
$(document).on('click', '#save_info', function () {
var serializeData = $("[name^='item_name']").serializeArray();
serializeData.push(
{
name: "address", value: $("#address").val()
},
{
name: "_token", value: '{{ csrf_token() }}'
},
);
$.ajax({
url: '/save_information',
dataType: "json",
type: 'POST',
data: serializeData
});
});
Or if you use <form>, then you can use with very few line code :
$(document).on('click', '#save_info', function () {
$.ajax({
url: '/save_information',
dataType: "json",
type: 'POST',
data: $('form#myform').serialize(),
});
});
`
The variable item_name holds DOM Node instead of input values. You'd have to make it either var item_name = $("[name^='item_name']").val() or var item_name = $("[name^='item_name']").value

Laravel - Returning 405 GET Method Not Allowed on the server

I'm using Laravel and I want to change status enable and disable with ajax request
it works on localhost but when I want to use it on the server it gives me this error
:
405 GET Method Not Allowed
this is my ajax :
<script>
$(".change").click(function(){
var id = $(this).data("id");
$.ajax(
{
url: "vouchers/change-status/"+id,
type: 'put',
dataType: "JSON",
data: {
"id": id,
"_method": 'put',
"_token": "{{ csrf_token() }}",
}
});
});
</script>
here is contorller
public function changeStatus(Request $request){
$voucher = Voucher::find($request->id);
if($voucher->status == 0)
$voucher->status = 1;
else
$voucher->status = 0;
$voucher->save();
}
and web
Route::put('vouchers/change-status/{id}', 'VoucherController#changeStatus')->name('change.status.voucher');
try this:
$.ajax(
{
url: "vouchers/change-status/"+id,
type: POST,
dataType: "JSON",
data: {
"id": id,
"_method": 'PUT',
"_token": "{{ csrf_token() }}",
}
}
);
The dataType attribute is only used when you're getting data from the server. You should be setting contentType to application/json when sending data to the server.
$(".change").on("click", function() {
var id = $(this).data("id");
$.ajax({
type: 'POST',
contentType: 'application/json',
dataType: 'json',
url: "vouchers/change-status/"+id
headers: {"X-HTTP-Method-Override": "PUT"},
data: {
"id": id,
"_method": 'put',
"_token": "{{ csrf_token() }}",
}
});
});

how to pass named route parameter with ajax

I need to pass route parameter with ajax but I am using named route method in ajax code.
route I want to go
Route
Route::post('/edit/{id}', 'ArticleController#updateArticle')->name('updateArticle');
Ajax
var id= $("input[name=editId]").val();
$.ajax({
type:'POST',
enctype: 'multipart/form-data',
url:"{{ route('updateArticle',"id") }}",
data: formdata,
contentType: false,
processData: false,
success:function(data){
$('.alert-success').html(data.success).fadeIn('slow');
$('.alert-success').delay(3000).fadeOut('slow');
}
});
I want to use variable id in ajax URL.
Try to use replace function:
var id = $("input[name=editId]").val();
var url = "{{ route('updateArticle', ":id") }}";
url = url.replace(':id', id);
$.ajax({
type:'POST',
enctype: 'multipart/form-data',
url: url,
data: formdata,
contentType: false,
processData: false,
success:function(data){
$('.alert-success').html(data.success).fadeIn('slow');
$('.alert-success').delay(3000).fadeOut('slow');
}
});
I had the same problem, just change your ajax url with this one.
var id= $("input[name=editId]").val();
$.ajax({
type:'POST',
enctype: 'multipart/form-data',
url:"{{ route('updateArticle') }}" + '/' + id,
data: formdata,
contentType: false,
processData: false,
success:function(data){
$('.alert-success').html(data.success).fadeIn('slow');
$('.alert-success').delay(3000).fadeOut('slow');
}
});
Put + around id variable and make sure you are passing X-CSRF-Token via formdata variable or try sending manualy :
replace this line :
url:"{{ route('updateArticle',"id") }}",
with this :
url:"{{ route('updateArticle',"+id+") }}",
var id= $("input[name=editId]").val();
$.ajax({
type:'POST',
enctype: 'multipart/form-data',
url:"{{ route('updateArticle',"+id+") }}",
data: formdata,
contentType: false,
processData: false,
success:function(data){
$('.alert-success').html(data.success).fadeIn('slow');
$('.alert-success').delay(3000).fadeOut('slow');
}
});
Try this:
$(document).on("click", ".delete", function() {
var $ele = $(this).parent().parent();
var id= $(this).val();
var url = '{{ route("student.destroy_academic_qualifications", ":id") }}';
url = url.replace(':id', id);
$.ajax({
url: url,
type: "GET",
cache: false,
data:{
_token:'{{ csrf_token() }}'
},
success: function(dataResult){
var dataResult = JSON.parse(dataResult);
if(dataResult.statusCode==200){
$ele.fadeOut().remove();
}
}
});
});
You can do it like this.
In your blade file
<script>
window.your_route = "{{ route('updateArticle',['id'=>$id]) }}";
</script>
In you JavaScript you can use created variable.
$.ajax({
type:'POST',
enctype: 'multipart/form-data',
url:window.your_route,
data: formdata,
contentType: false,
processData: false,
success:function(data){
$('.alert-success').html(data.success).fadeIn('slow');
$('.alert-success').delay(3000).fadeOut('slow');
}
});
You can do it like this below, just hardcode the url and id
var id= $("input[name=editId]").val();
$.ajax({
type:'POST',
enctype: 'multipart/form-data',
url:"edit/1",
data: formdata,
contentType: false,
processData: false,
success:function(data){
$('.alert-success').html(data.success).fadeIn('slow');
$('.alert-success').delay(3000).fadeOut('slow');
}
});
in form
<form id="form-create-role" action="{{route('role-create')}}" >
in file role-create.js
$(function(){
$('#form-create-role').submit(function (event) {
event.preventDefault();
$.ajax({
type: "post",
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: "json",
success: function (response) {
}
});
});
});
I do this by two ways
By using full url
$(document).on('click', '.view', function(){
let contactId = $(this).attr('data-id');
$.ajax({
type: "GET",
url: window.location.origin + "/view-contact-details/" + contactId,
success: function (response) {
console.log(response);
}
});
});
By using named route parameter
$(document).on('click', '.view', function(){
let contactId = $(this).attr('data-id');
let url = "{{ route('view.contact', ['id' => ":contactId"]) }}";
url = url.replace(":contactId", contactId);
$.ajax({
type: "GET",
url: url,
success: function (response) {
console.log(response);
}
});
});
You can use any of these :)

Get ID of element in jQuery autocomplete source function

I have a webservice method that takes the id of an element to determine the source for autocompletes.
In a nutshell, I'm doing this:
$("input[type='text']").autocomplete({
source: function(request, response) {
var id = $(this).attr('id');
var params = {'id': id, 'term': request.term};
var jsonParams = JSON.stringify(params);
$.ajax({
type: "POST",
url: "Page.aspx/GetAutoCompleteList",
data: jsonParams,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
response(JSON.parse(msg.d));
},
error: function() {
response([]);
}
});
}
});
But id isn't referring to the original selector.
What can I do to get the id of the selected input element? Or what is a better strategy for this?
You'd need to maintain a context of each input element, something like this:
$("input[type='text']").each(function (i, ele) {
ele = $(ele);
ele.autocomplete({
source: function (request, response) {
var id = ele.attr('id');
var params = {'id': id, 'term': request.term};
var jsonParams = JSON.stringify(params);
$.ajax({
type: "POST",
url: "Page.aspx/GetAutoCompleteList",
data: jsonParams,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// ...
},
error: function () {
// ...
},
async: false
});
}
});
});
Try
$(this.element).prop("id");
this.element[0].id;
$(this.element.get(0)).attr('id');
JSFIDDLE
$("input[type='text']").autocomplete({
source: function(request, response) {
var id = $(this.element).prop("id");
var id2=this.element[0].id;
var id3=$(this.element.get(0)).attr('id');
console.log(id);
console.log(id2);
console.log(id3);
var params = {'id': id, 'term': request.term};
var jsonParams = JSON.stringify(params);
$.ajax({
type: "POST",
url: "Page.aspx/GetAutoCompleteList",
data: jsonParams,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
response(JSON.parse(msg.d));
},
error: function() {
response([]);
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<input type="text" id="asd"></input>

Dynamically get URL for JQuery Ajax request from Data Attribute

I have a JQuery Autocomplete function that I need to be able to pass a url into. I'm trying to pull the url from the html data-url attribute, however I'm currently getting a variable is undefined message in the JavaScript console, so I know I'm not getting the values I expect. I've included my code below. Any help would be greatly appreciated.
JQuery Function:
$(function () {
$(".autocomplete").autocomplete({
delay: 0,
source: function (request, response) {
var baseURL = $(this).data("url");
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: baseURL + request.term,
dataType: "json",
success: function (data) {
response(data)
}
});
},
minLength: 1,
});
HTML Element:
<td style="width: 90%">
<label for="tag_Name" class="inline">Server Tags: </label>
<input class="fixed autocomplete" type="text" id="tag_Name" placeholder="Type tags to add..." data-url="/RequestFieldValues/GetLikeResourceTags/?prefix=" />
</td>
Try this instead...
$(function () {
$(".autocomplete").each(function() {
var baseURL = $(this).data("url");
$(this).autocomplete({
delay: 0,
source: function (request, response) {
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: baseURL + request.term,
dataType: "json",
success: function (data) {
response(data)
}
});
},
minLength: 1,
});
});
});
I've put the .autocomplete() inside an each() function so you can refer to this to get the base url from the data attribute. You can then pass that into the source function.
Incidentally, if there is more than 1 input then you need to make each one have a unique ID. You shouldn't have elements with the same ID :)
Another way to change the URL in a ajax request
$.ajax({
url: "http://static.url/",
beforeSend: function (xhr) {
this.url = "http://dyn.url/" + "here"
}
});
i think what you should be doing is :
$(function () {
var baseURL = $(".autocomplete").data('url');
$(".autocomplete").autocomplete({
delay: 0,
source: function (request, response) {
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: baseURL + request.term,
dataType: "json",
success: function (data) {
response(data)
}
});
},
minLength: 1,
});

Categories