I'm using ng-selectize directive to a select box using angularJS. Options to the slectbox are retrieved from an AJAX call. AJAX call response is coming in proper format.If do inspect element, select box options are populated properly. But in the UI, options are not rendered. Is there any specific reason for this behaviour? The same code is working fine in another place.
Here is my code:
HTML:
<select multiple="multiple"
ng-model="email.existing"
ng-options="obj.email for obj in emailLists track by obj.email"
placeholder="Choose from existing email address"
selectize>
Javascript
angular.module('myApp', [
'myApp.controllers',
'myApp.services',
'ngDialog',
'angular-selectize'
]);
angular.module('myApp.services', []).
factory('myAPIservice', function($http) {
var myAPI = {};
myAPI.getAllEmail = function( data ) {
return $http.post(APP_BASE_URL + "director/getallemail", data );
}
return myAPI;
});
angular.module('myApp.controllers', [])
.controller('myCntrl', function($scope, myAPIservice, ngDialog) {
myAPIservice.getAllDirectorsEmail({}).success(function (response) {
$scope.emailLists = response;
});
});
The above code retrieves email list from url. Sample response will look like this.
AJAX Response
If I change the javascript code to
angular.module('myApp.controllers', [])
.controller('myCntrl', function($scope, myAPIservice, ngDialog) {
$scope.emailLists = new Array({email:'abc#def.com'},{email:'lmn#opqr.com'})
});
and the response will be
Without AJAX call
Can anyone help me resolve this issue?
Related
i had a user list form in laravel. so i want when i click the table row, it automatically load the user details from database without redirecting. i've heard about ajax. but i have no idea how to use it in laravel..
i want to make like this
but without redirecting page..
$("tr").click(function()
{
$.ajax({
type: "GET",
url: $(this).data("href"),
dataType: "text",
success : function(data) {
$('#details-container').load(data)
}
});
});
does it supposed to be like this? but how did i get the data from database? i have no idea. please help me..
Its the same in Laravel as in "native" PHP. With your Ajax request your are able to send and asynchronous request, and refresh just a little part of your website, so you dont need to reload your whole page.
If you want to make it work with laravel, you should:
create a route for your requests
Route::get('user/{id}', function($id)
{
// So all your GET requests with any user id goes to this script (in routes.php)
// here you should load your user information, maybe with ORM
$user = User::where('id','=',$id)->get();
// Build any HTML snippet, or build JSON data (and build the information in Javascript on your page)
//return here JSON / or html
$data = array() -> containts information for the blade template
return view('users.information', $data);
});
Your AJAX request returns now JSON / or HTML, append it to your site where you would like to show it.
Your page structure will be like this:
<table>
<thead>
...
</thead>
<tbody>
<tr data-details-link="http://your-domain/user/{user-id}/details">
...
</tr>
</tbody>
</table>
The page with the table, should have this jQuery codes:
$('table tr').on('click', function (event)
{
event.preventDefault();
var $this = $(this);
// not necessary but you should show a loading here
$.ajax({
url: $this.data('details-link')
})
.success(function (response)
{
// the `response` variable is HTML code. Insert it into a modal.
});
});
Your route:
...
Route::get('user/{id}/details', [ 'uses' => 'UserController#details' ]);
...
Your UserController method:
public function details($id)
{
$user = \App\User::find($id);
if (!$user)
abort(404);
return view('user.details')->with('user', $user);
}
**Your user/details.blade.php should have the HTML that will be send as the AJAX response.
Hi I'm new in Ajax and django and I want to refresh my form. I try some code but it didn't work. I'm sure what I want to do is very basic.
Here my html:
<div class="row" style="padding-top:20px;">
<div class="col-md-12" id="testAjax">
{% load crispy_forms_tags %}
{% crispy form %}
</div>
</div>
I want to refresh my form in the div testAjax.
Here my view:
def createPin(request):
error = False
if request.method == "POST":
form = CreatePinForm(request.POST)
if form.is_valid():
pin = form.save(commit=False)
pin.customer = request.user.customer
pin.save()
msg = "pin saved"
return redirect('/pin/CreatePin', {'form': form, 'msg': msg})
else:
error = True
else:
form = CreatePinForm()
return render(request, 'createPin.html', {'form': form, 'error': error,})
My Ajax:
function refresh()
{
$form=$('#createPin');
var datastring = $form.serialize();
$.ajax({
type: "POST",
url: '/pin/CreatePin/',
dataType: 'html',
data: datastring,
success: function(result)
{
/* The div contains now the updated form */
$('#testAjax').html(result);
}
});
}
Thanks alot for your help.
When I need to do some operations and I don't want to reload the page I use a JQuery call to Ajax, I make the pertinent operations in AJAX and then receive the AJAX response in the JQuery function without leaving or reloading the page. I'll make an easy example here for you to understand the basics of this:
JQuery function, placed in the template you need
function form_post(){
//You have to get in this code the values you need to work with, for example:
var datastring = $form.serialize();
$.ajax({ //Call ajax function sending the option loaded
url: "/ajax_url/", //This is the url of the ajax view where you make the search
type: 'POST',
data: datastring,
success: function(response) {
result = JSON.parse(response); // Get the results sended from ajax to here
if (result.error) { // If the function fails
// Error
alert(result.error_text);
} else { // Success
//Here do whatever you need with the result;
}
}
}
});
}
You have to realize that I cannot finish the code without knowing what kind of results you're getting or how do you want to display them, so you need to retouch this code on your needs.
AJAX function called by JQuery
Remember you need to add an url for this Ajax function in your urls.py something like:
url(r'^/ajax_url/?$', 'your_project.ajax.ajax_view', name='ajax_view'),
Then your AJAX function, it's like a normal Django View, but add this function into ajax.py from django.core.context_processors import csrf from django.views.decorators.csrf import csrf_exempt from django.utils import simplejson
#csrf_exempt
def ajax_view(request):
response = []
#Here you have to enter code here
#to receive the data (datastring) you send here by POST
#Do the operations you need with the form information
#Add the data you need to send back to a list/dictionary like response
#And return it to the JQuery function `enter code here`(simplejson.dumps is to convert to JSON)
return HttpResponse(simplejson.dumps(response))
So, without leaving the page you receive via javascript a list of items that you sended from ajax view.
So you can update the form, or any tag you need using JQuery
I know that this can be so confusing at the beginning but once you are used to AJAX this kind of operations without leaving or reloading the page are easy to do.
The basics for understanding is something like:
JQuery function called on click or any event you need
JQuery get some values on the template and send them to AJAX via
POST
Receive that information in AJAX via POST
Do whatever you need in AJAX like a normal DJango view
Convert your result to JSON and send back to the JQuery function
JQuery function receive the results from AJAX and you can do
whatever you need
I have recently migrated from a codeigniter framework, to a nodejs with an express framework. Our codeigniter site had a lot of JS as it was, and we made a lot of AJAX calls because it is a single page app. We are messing around with node and express now, and I cannot get a simple AJAX call to function. It could be a lack of understanding of node, it could be something else. We are using openshift to host. We are using hogan-express as a template.
server.js
var express = require('express');
var fs = require('fs');
var http = require('http');
var path = require('path');
var SampleApp = function() {
var self = this;
self.initializeServer = function() {
self.app = module.exports = express();
self.app.configure(function() {
self.app.set('views', __dirname + '/views');
self.app.set('view engine', 'html');
self.app.engine('html', require('hogan-express'));
//self.app.set('layout', 'layout') # use layout.html as the default layout
self.app.use(express.favicon());
self.app.use(express.logger('dev'));
self.app.use(express.bodyParser());
self.app.use(express.methodOverride());
self.app.use(express.session());
self.app.use(self.app.router);
self.app.use(require('stylus').middleware(__dirname + '/public'));
self.app.use(express.static(path.join(__dirname, 'public')));
});
require('./routes');
}
There is more code in this file, I am only including the relevant code (I think).
Ajax.html
<div id="button">
<button id="testbutton">Push Me!</button>
</div>
<div id="populate">{{title}}</div>
<div id="null">{{>part}}</div>
<script type='text/javascript'>
$(function(){
$('#testbutton').click(function (){
$.ajax({
url:'/test',
type: 'POST',
success: function(result){
alert('success!');
},
error: function(){
alert("well this is embarassing... if the problem persists please let us know at facebook.com/stembuds");
}
});
});
});
</script>
index.js
app = require('../server');
app.get('/', function(req, res){
res.render('ajax');
});
app.post('/test', function(req, res){
console.log('get');
res.locals = {title: 'Horray'};
res.render('ajax', {partials:{part:'part'}});
});
part.html
<p> pass me in!!</p>
So basically what I am trying to do is when the button is clicked I want the ajax call to show a partial view. The way we are going to structure the site is to have one single page, and have the ajax calls render different views based on the buttons that the user clicks. So here is the interesting part: I get the success alert from the ajax call, but the {{title}} and the {{>part}} never show up. However, when I go to the console and click 'network', and then click 'test' (the url to my ajax call), the response shows the divs populated with "Horray" and "pass me in!!". Sorry for the length, and thank you for any information you can provide us.
If you are calling your resources with ajax (as you are doing) then you get the response to your ajax function. After successful call you need to render the view in your client side JS code.
What I mean is that your code works as expected, but your backend cannot update your browsers view. You need to do it client side or load the whole page again from the server.
Your success hander could be something like this:
success: function(result){
renderTheResults(result);
},
You can just send the JSON. You need to send the json via send not render. Because render is supposed to deliver the full HTML page. May be .ejs file.
For example:
res.send({partials:{part:'part'}});
res.send should be used to pass json to your page. And on your page you have to use the JSON to populate the HTML dynamically.
I want to use ajax for add data in database and i found following code in net and it is working fine.
<script language='javascript'>
reqObj=null;
function saveCust(){
document.getElementById('res').innerHTML='processing';
if(window.XMLHttpRequest){
reqObj=new XMLHttpRequest();
}else {
reqObj=new ActiveXObject('Microsoft.XMLHTTP');
}
reqObj.onreadystatechange=processSave;
reqObj.open('POST','./custSave?reqObj.open('POST','./cName?id='+document.getElementById('CustCode').value,true);,true);
reqObj.send(null);
}
function processSave(){
if(reqObj.readyState==4){
document.getElementById('res').innerHTML=reqObj.responseText;
}
}
</script>
Above code sends only one String but, i have 5 Strings in my form.
Please anybody alter the code for sending multiple data.
The problem is that you're sending a single parameter in the reqObj.open function:
reqObj.open('POST','./custSave?reqObj.open('POST','./cName?id='+document.getElementById('CustCode').value,true);,true);
Note that the only parameter you send is id.
You can add more parameters in the flavor of QueryString:
id=something&otherParameter=else //and more parameters
IMO the easiest way to handle an ajax request would be using jQuery, as shown and heavily explained by BalusC in How to use Servlets and Ajax?.
Based on the samples there and jQuery Ajax POST example with PHP, you can come with the following code:
Assuming the 5 Strings are in the form
function saveCust(){
$('#res').html('processing');
var $form = $(this);
var serializedData = $form.serialize();
$.post('./custSave', serializedData, function(responseText) {
$('#res').html(responseText);
});
}
Assuming there's data outside the form
function saveCust(){
$('#res').html('processing');
var $form = $(this);
var serializedData = $form.serialize() + "&id=" + $('#CustCode').val();
$.post('./custSave', serializedData, function(responseText) {
$('#res').html(responseText);
});
}
And you can even enhance this using more jQuery functions, but that's outside the scope of this answer.
This is a follow-up to AJAX Call Does Not Trigger Action Method When Decorated With CanvasAuthorize
So I found the following links and it seems that this is a common problem:
http://facebooksdk.codeplex.com/discussions/251878
http://facebooksdk.codeplex.com/discussions/250820
I tried to follow the advice by prabir but I couldn't get it to work...
Here's my setup:
I have the following snippet in the page where the button that triggers the whole post to facebook is located:
#if (!string.IsNullOrEmpty(Request.Params["signed_request"]))
{
<input type="hidden" id="signedReq" value="#Request.Params["signed_request"]" />
}
And then I have this snippet (inside a script tag inside the same page):
var signedRequest = $('#signedReq').val();
$('.facebookIcon').click(function () {
var thisItem = $(this).parent().parent();
var msg = thisItem.find('.compItemDescription').text();
var title = thisItem.find('.compareItemTitle').text();
var itemLink = thisItem.find('.compareItemTitle').attr('href');
var img = thisItem.find('img').first().attr('src');
postOnFacebook(msg, itemLink, img, title, signedRequest);
});
And finally, inside an external js file I have the following function:
/*Facebook post item to wall*/
function postOnFacebook(msg, itemLink, pic, itemTitle, signedReq) {
console.log(signedReq);
var siteUrl = 'http://www.localhost:2732';
$.ajax({
url: '/Facebook/PostItem',
data: {
'message': msg,
'link': siteUrl + itemLink,
'picture': siteUrl + pic,
'name' : itemTitle,
'signed_request': signedReq
},
type: 'get',
success: function(data) {
if(data.result == "success") {
alert("item was posted on facebook");
}
}
});
}
But signedReq is always undefined. And I'm not really sure I should be passing the 'signed_request' field inside the data object. Any thoughts?
Make sure you hidden input field is being populated.
Also, when you try to pull the ID of the input field via JQuery, you might not be referencing the proper element since .NET butcher's ID's of anything that's run on the server.
When I use the hidden input field trick, I set the jquery value like so:
var signedRequest = $('#<%=signedReq.ClientID %>').val();
This way, I'm getting the identifier that .NET is giving to the HTML element.
Hope that helps.
Just a guess - in your hidden field: id="signed_request" instead of id="signedReq"