Where to find angular-xeditable and ajax together work simple example - ajax

Now, I am using angular-xeditable.I want to send edit data to server.
<div ng-controller="Ctrl">
{{ user.name || "empty" }}
</div>
and js code is
<script type="text/javascript">
var app = angular.module("app", ["xeditable"]);
app.controller('Ctrl', function($scope,$http) {
$scope.user = {
name: 'awesome user'
};
$http.post("<?php echo base_url(); ?>index.php/welcome/test", {"name":name})
.success(function(data, status, headers, config) {
$scope.data = data;
})
.error(function(data, status, headers, config) {
$scope.status = status;
});
});
</script>
I received name variable is empty value.
This code doesn't work.I can't find error.

You need to invoke your code that posts to the server on the onaftersave event, which is documented here: http://vitalets.github.io/angular-xeditable/#onaftersave
This event is called after the changes in the inputbox have been set on the model.
In your HTML put the function call in the onaftersave attribute like this:
<div ng-controller="Ctrl">
{{ user.name || "empty" }}
</div>
In your controller create the postName function which actually posts the data to the server. Your code would look like this:
<script type="text/javascript">
var app = angular.module("app", ["xeditable"]);
app.controller('Ctrl', function ($scope, $http) {
$scope.user = {
name: 'awesome user'
};
// Called on the onaftersave event of xeditable
$scope.postName = function () {
$http.post("<?php echo base_url(); ?>index.php/welcome/test", {"name": $scope.user.name})
.success(function (data, status, headers, config) {
$scope.data = data;
})
.error(function (data, status, headers, config) {
$scope.status = status;
});
}
});
</script>

Related

JQuery autocomplete search using typeahead in laravel

I'm getting this error:
GET http://auto.test/autocomplete?query= 500 (Internal Server Error)
My Route (web.php):
Route::get('search', 'SearchController#index')->name('search');
Route::get('autocomplete', 'SearchController#autocomplete')->name('autocomplete');
My SearchController:
use App\Item;
use Input;
use Responce;
public function index()
{
return view('search');
}
public function autocomplete(Request $request)
{
$data = Item::select("name")->where("name", "LIKE", "%{$request->input('name')}%")->get();
return responce()->json($data);
}
And in my main view (search.blade.php):
<body>
<div class="container">
<h1>Search Name by Auto Complete</h1>
<input type="text" class="typeahead form-control" name="" id="">
</div>
<script type="text/javascript">
var path = "{{ route('autocomplete') }}";
$("input.typeahead").typeahead({
source:function(query, process) {
return $.get(path, {query:name}, function(data) {
return process(data);
})
}
});
</script>
</body>
Included are the latest JQuery files and the bootstrap3-typeahead.js from cloudflare. Am I doing something wrong. Any help or suggestion is highly appreciated.
You are passing ajax request parameters wrongly. But in your code you expected to receive input parameter 'name' so it could be as follows
<script type="text/javascript">
var path = "{{ route('autocomplete') }}";
$("input.typeahead").typeahead({
source:function(query, process) {
return $.get(path, {name:query}, function(data) {
return process(data);
})
}
});
</script>
I starting using this function today. And I still learning. So... I think you forgot the name and id of your input.

Issue with ajax call csfr token

I am trying to add an ajax call that changes the status of a listing, between listed and unlisted, when submitting the form I am having a 403 forbidden error in the console of the browser, I made some checking and it appears that Django is forbidding the form because of a lack of csrf token, however I am not good in javascript, so any help would be appreciated.
Here is my code in my view:
#require_POST
#ajax_required
#login_required
def unlist_ajax(request):
pk = request.POST.get('pk', None)
is_visible = request.POST.get('is_visible', None)
if pk and is_visible:
listing = get_object_or_404(Listing, pk=pk)
if is_visible == 'true':
listing.is_visible = False
listing.save()
messages.success(request, _("Listing unlisted"))
return JsonResponse({'status': 'ok'})
else:
listing.is_visible = True
listing.save()
messages.success(request, _("Listing re-listed"))
return JsonResponse({'status':'ok'})
and here is the template script:
in the top of the template, in the header:
<script>
function unlistPostAjax(listing_id, is_visible) {
var confirmation = confirm("{% trans 'are you sure you want to change the status of your listing?' %}");
if (confirmation) {
$.post("{% url 'dashboard:unlist_ajax' %}", {pk: listing_id, is_visible: is_visible}, function (response) {
console.log('sending delete query'); location.reload();
})
}
}
</script>
and in the bottom of the body:
<script src="{% static 'js/jquery.cookie.js' %}"> </script>
<script>
$(document).ready(function () {
var csrftoken = $.cookie('csrftoken');
function csrfSafeMethod (method) {
// These HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function (xhr, settings) {
if(!csrfSafeMethod(settings.type) && !this.crossDomain) {
// Set X-CSRFToken HTTP Header
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
});
</script>
You can add this to the top of your <script> or if you have a base html template you can put this in there too.
{% csrf_token %}
<script type="text/javascript">
var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val();
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
</script>
Believe you just need to add the csrf above the script you defined, but this is the whole implementation I currently use. I have no issues.

Django Ajax-jQuery

Since I am relatively new to Ajax and jQuery, and having hard time doing this, I am posting this over here.
Views.py
if request.is_ajax():
if request.method == "POST":
chatroom_id = request.POST['chatroom_id']
else:
chatroom_id =''
print chatroom_id
When I remove if request.is_ajax() condition , then it shows the error saying Key 'chatroom_id' not found in <QueryDict: {u'reply': [u''], u'csrfmiddlewaretoken': [u'yIJct9O7WfyPnWmDosW9N5TEklRwoIHP']}>
Template.html
{% for key, values in chat_data.items %}
<div class="container-fluid" alt = {{key}}>
<div class="row-fluid">
<div class="span2">
{{values.from}} <br/> {{values.init_query}}
</div>
<div class="span10 well">
{% for k in values.chat %}
<label> Text : {{k.text}} </label>
<label> {{k.date_time}} </label>
{% endfor %}
<form action = "#" method = "POST" id = {{key}} class="chatroom">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value = "Sent" class="btn btn-primary">
</form>
</div>
</div>
</div>
{% endfor %}
Since, there will be many chats and correspondingly reply submit button and its key, I want that when I reply to a specific chat, it carries the key with itself and process the chat accordingly.
How can I achieve this using Django, jQuery and Ajax? Replies to be being sent should give via Ajax using jquery
I have written these jQuery lines of code, but they seem not to work. Where I am going wrog
<script type="text/javascript">
var form = $('#'+'{{key}}');
form.submit(function (event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "/dashboard",
data : form.serialize(),
success: function( response ) {
console.log( response );
}
});
return false;
});
I believe that the best free resource on the matter is Mike Hibbert's video on using django with jquery to implement ajax.
For the jQuery, you have a few mistakes, the post should look like this:
var form = $('#'+'{{key}}');
form.submit(function (event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "/dashboard",
data : form.serialize(),
success: function( response ) {
console.log( response );
}
});
return false;
});
Try that and tell me how it goes.
When you make an Ajax request with jQuery and Django with csrf you need to pass the token, this uses the jQuery cookie plugin from Django's docs https://raw.github.com/carhartl/jquery-cookie/v1.3.1/jquery.cookie.js :
/** Django's csrftoken ajax security & server failures */
App.ajax = (function () {
var csrftoken = $.cookie('csrftoken'),
host = document.location.host,
protocol = document.location.protocol,
sr_origin = '//' + host,
origin = protocol + sr_origin;
return {
'csrfSafeMethod': function (method) {
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
},
'sameOrigin': function (url) {
return (url === origin || url.slice(0, origin.length + 1) === origin + '/') || (url === sr_origin || url.slice(0, sr_origin.length + 1) === sr_origin + '/') || !(/^(\/\/|http:|https:).*/.test(url));
},
'$setup': function () {
var scope = this;
// TODO: create server failure pages and alert mechanism
$.ajaxSetup({
statusCode: {
401: function () {
},
403: function () {
}
},
beforeSend: function (xhr, settings) {
if (!(scope.csrfSafeMethod(settings.type) && scope.sameOrigin(settings.url))) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
return this;
}
}());
$(document).ready(function(){
App.ajax.$setup()
var $form = $('form');
$form.on('submit' function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: '/dashboard',
data: $form.serialize(),
success: function (response) {
window.alert(response);
}
});
});
});
Personally I would prefer to pass JSON, also what browser are you testing in? Look into these libraries:
https://raw.github.com/marioizquierdo/jquery.serializeJSON/1.0.0/jquery.serializeJSON.js
https://raw.github.com/MoonScript/jQuery-ajaxTransport-XDomainRequest/master/jQuery.XDomainRequest.js

How to associate an event to Html.ActionLink in MVC3

I have made an Ajax function but i am getting a big prolem in that.
I was displaying the contents on click of the link..
The links are fetched from the database and also the url of the links are fetched from the datbase.
I have wriiten ajax to call the contents dynamically on click of the link
<script type="text/javascript">
$(document).ready(function () {
$('a').click(function (e) {
e.preventDefault();
var filename = $(this).text();
var Hobbyurl = '#Url.Action("FetchUrlByHobbyName")';
$.ajax({
type: "POST",
url: Hobbyurl,
data: { data: filename },
success: function (returndata) {
$('iframe').attr('src', returndata);
}
});
});
});
</script>
Now FetchUrlByHobbyName is the function called from the Controller thart returns the url
//Ajax routine to fetch the hobbyinfo by hobbyname
[HttpPost]
public ActionResult FetchUrlByHobbyName(string data)
{
HobbyMasters hobbymaster = new HobbyHomeService().FetchHobbyMasterByHobbyName(data);
string url = hobbymaster.InformationUrl;
if (HttpContext.Request.IsAjaxRequest())
return Json(url);
return View();
}
And in my View i have written the link like this:
#foreach (var item in Model)
{
<li >#Html.ActionLink(item.HobbyName, "Hobbies")
</li>
}
i tried this :
#Html.ActionLink(item.HobbyName, "Hobbies", null, new { id = "alink" })
and then calling Ajax on click of 'alink' but with this my ajax function doesnot get called.
Now the problem is the ajax function is getting called on click of every link on the page..
I want to assign a unique Id to it but i am not understanding how to do that
please Help me...
For that specific link, assign an id. E.g
<a id="someID" href="url">Link</a>
and than bind the click only with that link.
$('#someID').click(function (e)) ....
If I understood you correctly this helps you
The text of the link
<script type="text/javascript">
function myAjaxFunction(){
e.preventDefault();
var filename = $(this).text();
var Hobbyurl = '#Url.Action("FetchUrlByHobbyName")';
$.ajax({
type: "POST",
url: Hobbyurl,
data: { data: filename },
success: function (returndata) {
$('iframe').attr('src', returndata);
}
});
</script>
Try to give a css class selector to you action link like this...
#Html.ActionLink("some link", "Create", "Some_Controller", new { }, new { #class = "test" })
then User jquery for it..
<script type="text/javascript">
$(document).ready(function () {
$('.test').click(function (e) {
e.preventDefault();
var filename = $(this).text();
var Hobbyurl = '#Url.Action("FetchUrlByHobbyName")';
$.ajax({
type: "POST",
url: Hobbyurl,
data: { data: filename },
success: function (returndata) {
$('iframe').attr('src', returndata);
}
});
});
});
</script>

Ajax with Zendframework

Friends,
How I integrate Ajax with zendframework.I need some good tutorials.
Put this in your controller
public function init()
{
$contextSwitch = $this->_helper->getHelper('contextSwitch');
$contextSwitch->addActionContext('test', 'json')
->initContext();
}
create a test action
public function testAction()
{
$this->view->var1 = "I'm testing";
}
Then use jquery to perform the request in your view
<script type="text/javascript">
$(document).ready(function(){
$('#display').ajaxStart(function(){
$(this).html('Loading...');
});
str = $('#test').val();
$('#link').bind('click',function(event){
event.preventDefault();
$.post(
this.href,
{ var1: str, format: 'json' },
function(data){
$('#display').html(data.var1);
},
"json"
);
});
});
</script>
<input type="text" name="test" id="test" value="just testing" />
<p>
Testar
</p>
<div id="display">...</div>
You can use something like this in your controller:
public function testAction() {
// Remove all of your HTML stuff
$this->_helper->layout->disableLayout();
// PHP to create an array form database or something
// This will return the info as json. It takes care of the header and everything else!
return $this->_helper->json->sendJson( array('test') );
}

Resources