select 2 not calling ajax function in Laravel - ajax

view:
<select class="js-data-example-ajax" id="tag_list">
<option value="3620194" selected="selected">select customer</option>
</select>
ajax:
$('#tag_list').select2({
placeholder: 'Enter a tag',
ajax: {
dataType: 'json',
url: '{{ url("api/tags") }}',
delay: 400,
data: function(params) {
return {
term: params.term
}
},
processResults: function (data, page) {
return {
results: data
};
},
}
});
I am using select 2 in Laravel. The ajax function is not calling in the view page. I have placed the ajax code at the bottom of the page. But the ajax function is not calling. But I have checked the data from controller using postman.The data is returning in the controller.

Related

ID received from post - send via ajax

I would like to read the post id from html and send it via AJAX to the controller. How can I get the post ID ($post->id) and transfer it via AJAX? Or is there a better solution to save the post seen by the user?
#foreach ($posts as $post)
<div id="post_container_{{$post->id}}" class="row waypoint">
</div>
#endforeach
This is my AJAX code:
$('.waypoint').waypoint(function() {
$.ajax({
url: '/posts/view',
type: "post",
data:
success: function(request){
console.log(request);
},
error: function(response){
console.log(response);
},
headers:{
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
}, {
offset: '100%'
});
Get the id from the focused waypoint.
let waypoint_id = this.getAttribute('id'); // something like 'post_container_1'
Get only the string after the _
let post_id = waypoint_id.split("_").pop(); // something like '1'
in ajax() function
data: {
post_id: post_id
}
You could add a data-id attribute like so:
#foreach ($posts as $post)
<div id="post_container_{{$post->id}}" data-id="{{$post->id}}" class="row waypoint">
</div>
#endforeach
And then access it using the attr()
$('.waypoint').waypoint(function() {
let post_id = $(this).attr('data-id'); //this specifies the particular post row in focus.
$.ajax({
url: '/posts/view',
type: "post",
data: {post_id: post_id}
//and so on.
});
}, {
offset: '100%'
});

Delete\Add Row with AJAX (Secure way)

i am new to Laravel and trying to find way to delete or add row with AJAX request.
Let's say i have PostController and i want to delete one of my post.
So in the PostController there will be destroy function :
public function destroy($id)
{
Posts::find($id)->delete();
}
Now, how i can send from a view AJAX Request to Controller and use this destroy method in secure way.
This works for me,
But the question is if this secure ?
AJAX Function
function removeRow(id){
token = $('#rmv').data("token");
console.log(id);
$.ajax(
{
url: "/posts/"+id,
type: 'POST',
data: {
"id": id,
"_method": 'DELETE',
"_token": token,
},
success: function ()
{
console.log("it Work");
$('#post'+id).remove();
}
});
}
VIEW
<a id="rmv" onclick="javascript:removeRow({{$post->id}})" data-token="{{ csrf_token() }}" class="btn btn-primary" >Delete</a>
OK, This works for me.
But the question is if this secure ?
AJAX Function
function removeRow(id){
token = $('#rmv').data("token");
console.log(id);
$.ajax(
{
url: "/posts/"+id,
type: 'POST',
data: {
"id": id,
"_method": 'DELETE',
"_token": token,
},
success: function ()
{
console.log("it Work");
$('#post'+id).remove();
}
});
}
VIEW
<a id="rmv" onclick="javascript:removeRow({{$post->id}})" data-token="{{ csrf_token() }}" class="btn btn-primary" >Delete</a>

MVC Razor Ajax call from button click

I'm struggling to get a button click to invoke an Ajax function which then posts to a controller action. Cannot even get a simple message to work (nothing happens when button is clicked). Clearly, I'm missing something fundamental. What is it?
The Ajax script in my Razor form:
<script type="text/javascript">
$('#UseShipAddr').click(function () {
$.ajax({
url: "#(Url.Action("UseShippingAddress", "Checkout"))",
type: "POST",
data: { id: 50 },
cache: false,
async: true,
success: function (data) {
alert(data);
}
});
});
</script>
The button that I want to use to invoke the Ajax function:
<input type="button" value="Use Shipping Address" id="UseShipAddr" />
The action in CheckoutController:
// Ajax POST: /Checkout/UseShippingAddress/5
[HttpPost]
public ActionResult UseShippingAddress(int id)
{
return Content("It worked!");
}
Please try this code.
$(document).ready(function(){
$('#UseShipAddr').click(function () {
$.ajax({
url: "Checkout/UseShippingAddress",
type: "POST",
data: { id: 50 },
cache: false,
async: true,
success: function (data) {
alert(data);
}
});
});

Getting textbox value from X-editable

How do you get the value of the textbox field and send as data inside of ajaxOptions? I tested my view and it prints out the test variable successfully from my Django views. I am using X-editable for Jquery. Heres what textbox input looks like:
http://jsfiddle.net/xBB5x/197/
views.py
def create_post(request):
print request.POST.get("test", "");
return HttpResponse(json,content_type="application/json")
HTML
<a id="other1" data-pk="First Name" data-name="test">First Name</a>
AJAX
$(document).ready(function() {
$('#other1').editable({
type: 'text',
pk: 1,
url: '/create_post/',
ajaxOptions: {
data: {
csrfmiddlewaretoken: '{{ csrf_token }}',
test: "hi",
},
},
placement: 'top',
title: 'New Expense',
success: function(response, newValue) {
if(response.status == 'error') return response.msg; //ms
},
});
});
Instead of ajaxOptions, use params. If I remember correctly, test and its value will be included in your POST request by x-editable. Try something like this:
Html
<a id="other1" data-pk="1" data-name="test">First Name</a>
AJAX
$(document).ready(function() {
$('#other1').editable({
type: 'text',
url: '/create_post/',
params : function(params) {
params.csrfmiddlewaretoken = '{{ csrf_token }}';
return params;
},
placement: 'top',
title: 'New Expense',
success: function(response, newValue) {
if(response.status == 'error') return response.msg; //ms
},
});
});

Jquery .ajax() function not returning values from codeigniter controller

I have a site i'm working on and i'm trying to make an ajax request to a controller (codeigniter framework). I see in firebug that my controller is receiving my post value just fine but for some reason it is not sending back a response. I've set it up to be VERY simple without a database call at this point just for testing and its still not working. Any ideas?
Here is my form in my view:
<div class="purchaseState">
<input type="text" name="city" id="city" class="grayGrad"/>
</div>
<div>
<ul id="cityResults">
<!-- AJAX results here -->
</ul>
</div>
Here is my controller returning the value:
function citySearch() {
echo '<li>test</li>';
}
Here is my Jquery ajax
//New City Search
$('#city').keyup( function() {
var city = $('#city').val();
$.ajax({
type: "POST",
url: "page/citySearch",
data: { city: city },
}).done(function( data ) {
$('ul#cityResults').append(data);
});
});
you should use ajax success callback:
$('#city').keyup(function() {
var city = $('#city').val();
$.ajax({
type: "POST",
url: "page/citySearch",
data: { city: city },
success: function(data) {
$('ul#cityResults').append(data);
}
});
});
Please change the url in the AJAX function in the following way.
$('#city').keyup(function() {
var city = $('#city').val();
$.ajax({
type: "POST",
url: "<?php echo base_url; ?>page/citySearch",
data: { city: city },
success: function(data) {
$('ul#cityResults').append(data);
}
});
});

Resources