How Can i Define A javascript Variable in My Ajax url - ajax

I want Define url Like this
var id = $('#id').val();
url: "category/(my difined id varibale here)/edit"
How can I do something like this?
I am creating project using Laravel 5.4
here I use resource controller that why I need this kind of URL to get my controller function
This is the script part where I use ajax to insert data to database
<script>
$(document).ready(function(){
$(document).on('click','#edit',function(){
$('#modelTile').text('Edit Category');
$('#addItem').val($(this).data('name'));
$('#id').val($(this).data('id'));
$('#yesdelete').hide();
});
$('.modal-footer').on('click','#saveChange',function(){
var name = $('#addItem').val();
var id = $('#id').val();
var token ='{{csrf_field()}}';
$.ajax({
method : 'post',
url : "category/{'id'}/edit",
});
conlose.log (url);
});
});
</script>

Replace your code to
$.ajax({
method : 'post',
url : "category/"+id+"/edit",
});

Related

Django: correct way to pass AJAX

I've a view that recives parameters from the frontend via AJAX.
I've passing AJAX parameters in a maner, but this time my way didn't work.
I've asked a friend for help, and he send me another way of sending AJAX data. To my untrained eyes they both work equal. So I don't know why mine does not work:
Why?
My friend's AJAX:
<script>
$("#id_shipping_province").change(function () {
var val_d = $("#id_shipping_department").val()
var val_p = $("#id_shipping_province").val()
$.ajax({
url: "/district/?d_name=" + val_d + "&p_name=" + val_p
}).done(function (result) {
$("#id_shipping_district").html(result);
});
});
</script>
My AJAX:
<script>
$("#id_shipping_province").change(function () {
var val_d = $("#id_shipping_department").val()
var val_p = $("#id_shipping_province").val()
$.ajax({
url: "/district/",
d_name: val_d,
p_name: val_p
}).done(function (result) {
$("#id_shipping_district").html(result);
});
});
});
</script>
View
def get_district(request):
d_name = request.GET.get("d_name")
p_name = request.GET.get("p_name")
data = Peru.objects.filter(departamento=d_name, provincia=p_name).values_list("distrito", flat=True)
# data = Peru.objects.filter(provincia=p_name).values_list("provincia", flat=True)
return render(request, "accounts/district_dropdown.html", {
"districts": set(list(data))
})
You need to pass the the d_name and p_name properties in a separate object specified by data. Currently you're passing them as top level properties of the ajax settings object, which won't have any effect.
var val_d = $("#id_shipping_department").val()
var val_p = $("#id_shipping_province").val()
$.ajax({
url: "/district/",
data: { // Pass parameters in separate object
d_name: val_d,
p_name: val_p
},
}).done(function (result) {
$("#id_shipping_district").html(result);
});
The data object is converted into a query string and appended to the URL.
In your friend's case, they are building up the query string manually when they create the URL - hence their version works.

Issue with passing id from Laravel api to Select2 script

I have strange problem because previously in my app this code was working but now isn't.
I take data from Laravel api via url address:
/api/customer/{id}/products
to select2 script
$('.js-data-example-ajax').select2({
ajax: {
url: '/api/customer/{id}/products',
dataType: 'json',
data: function (params) {
var query = {
q: params.term,
}
return query;
}
but Laravel make url address i that way:
api/customer/%7Bid%7D/products
so, I have %7Bid%7D instead of {id} and I'm looking for solution in google without success.
The character "7B" is { converter to asci, before the ajax request create a var call "url"
i call the route with his name, for give it the name just attach
->name('your_name') in the route file
and after in url variable i use the route name instead the full url
url = '{{ route("your_route_name", ":id") }}';
then replace the id placeholder with the id of select
url = url.replace(':id', id);
finally in ajax request
ajax: {
url: url,
//the rest of ajax request
}

how to access a controller function from outside of controller in codeigniter

I have a folder (suppose it's name is "test") outside of controller folder which contains a file name "error404.php" and my controller name is "test_controller.php" which has a method name "tst()". error404.php is a view page in where i want to access data from test_controller.php via ajax.
<script>
$(document).ready(function(e) {
$('#search_items_err').keyup(function(e) {
if($('#search_items_err').val().trim()==''){$('#sugglist').html(''); return false;}
search_key=$(this).val().trim();
var data = {
search_key: search_key
};
alert(search_key);
$.ajax({
data: data,
type: "post",
url: "test_controller/tst",
success: function(response) {
var options = JSON.parse(response);
alert(options);
}
});
});
});
</script>
My tst function is:
public function tst(){
$search_key = $_POST['search_key'];
echo "success";
}
But my ajax doesn't work. I suspect that it may contain some problems in the (url: "test_controller/tst",). So how can i solve it? What is the syntax of accessing test_controller's method from error404.php page?How do i access base url?
Take a look at this ajax concept
in your ajax function :
url : baseURL+'test_controller/search', //Make sure this url is working properly
data : {'search_key' : search_key},
in you test_controller/search
public function search()
{
//generate data and load your view
$data = "Generated Data array";
$this->load->view('test_folder/search', $data); //Load your view from application/view/ not from outside the controller
}

Ajax post request from Backbone to Laravel

I'm trying to send a Backbone collection to Laravel with an Ajax Request.
I don't need to save it or update the database I just need to process the data with the Omnypay php Api. Unfortunately the Laravel Controller variable $input=Input::all() contain an empty string.
var url = 'index.php/pay';
var items = this.collection.toJSON;
$.ajax({
url:url,
type:'POST',
dataType:"json",
data: items,
success:function (data) {
if(data.error) { // If there is an error, show the error messages
$('.alert-error').text(data.error.text).show();
}
}
});
This is the Laravel Route:
Route::post('pay','PaypalController#doPay');
And finally the Laravel Controller:
class PaypalController extends BaseController {
public function doPay() {
$input=Input::all();
}
}
Your route doesn't match, it's
Route::post('pay','PaypalController#doPay');
So the url should be
var url = 'pay';
instead of
var url = 'index.php/pay';
BTW, not sure if anything else (backnone) is wrong.
Update : toJSON is a method, so it should be (you missed ())
var items = this.collection.toJSON();
The hack solution I found to transfer a backbone collection to Laravel was to convert the collection to JSON and then wrapping it in a plain object, suitable for the jQuery Ajax POST. Here is the Code:
var url = 'index.php/pay';
var items = this.collection.toJSON();
var plainObject= {'obj': items};
$.ajax({
url:url,
type:'POST',
dataType:"json",
data: plainObject,
success:function (data) {
if(data.error) { // If there is an error, show the error messages
$('.alert-error').text(data.error.text).show();
}
}
});
Now the $input variable of my "doPay" controller function contain an array of Backbone models.

how to get codeigniter url parameters in jquery ajax function

I have the following url in codeigniter.
Add to wishlist
and I have the following jquery function
<script>
$(document).ready(function(){
$('body').on('click', 'a.wishlist_item', function(e){
$.ajax({
url:"../add-item-to-wishlist",
data : "the query string",
success: function(result){
// success code.
}
});
e.preventDefault();
});
});
</script>
how do I get the query string value and pass to the above url ? the add-to-wishlist route redirect to a controller function which take exactly two parameters.
function add_to_wishlist($itemID,$wishlistID = NULL)
What I want to do is call this function using ajax but I dont know how do I call this using ajax
change your anchor URL to the controller method
href = "add_to_wishlist/5/21"
Then you can do a get request with the full URL
<script>
$(document).ready(function(){
$('body').on('click', 'a.wishlist_item', function(e){
e.preventDefault();
var obj = $(this);
$.ajax({
type:'get',
url:obj.attr('href'),
success: function(result){
// success code.
}
});
});
});
</script>

Resources