Javascript noob. I have a forced directed graph from spring.js and I want to trigger ajax from it when the user selects a node but I keep getting an error
Uncaught SyntaxError: Unexpected token . this focusses on the line
function GetSpringyNode(node.data.label){
. I have managed to get it to trigger an alert but firing the ajax is tricky. Can anyone tell me how? I think the crux of the matter is how I pass the node.data.label to the ajax. Here is the jsfiddle and below is the code I am trying:
var graphJSON = <%=raw #users.to_json %>;
var graph = new Springy.Graph();
graph.loadJSON(graphJSON);
var springy = jQuery('#springydemo').springy({graph: graph});
jQuery('#springydemo').springy({ graph: graph, nodeSelected: function(GetSpringyNode) {
alert(node.data.label);
} });
function GetSpringyNode(node.data.label){
$.ajax({
url: "/users/show",
type: "GET",
dataType: 'html',
data: {name: d.name},
success: function(result) {
//$('#NodeProfile').html(result);
//$('.bchart-content').html(result);
//Need to parse into html here before included in .bchart-content
addGraph(result);
}
});
}
Change your code to this:
jQuery('#springydemo').springy({ graph: graph, nodeSelected: function() {
GetSpringyNode(node.data.label);
} });
and the GetSpringyNode function to this:
function GetSpringyNode(label){
$.ajax({
url: "/users/show",
type: "GET",
dataType: 'html',
data: {name: label},
success: function(result) {
//$('#NodeProfile').html(result);
//$('.bchart-content').html(result);
//Need to parse into html here before included in .bchart-content
addGraph(result);
}
});
}
Related
In school we use ASP.NET but normally I am a RoR developer.
I get my data from a WCF service.
I have created this ASP.NET MVC 5 project. I created a controller that looks like this:
[HttpGet]
public ActionResult GetMovies()
{
return Json(client.RetrieveAllFilms(), JsonRequestBehavior.AllowGet);
}
And a on load jquery script that looks like this at the following moment:
<script>
$(document).ready(function () {
console.log("document ready");
$.ajax(
{
type: "GET",
dataType: 'json',
url: "http://localhost:5348/movies/getmovies",
data: "",
success: function(data)
{
alert(data.d);
var list = JSON.stringify(data.d);
alert(list);
for (var i = 0; i < list.length; i++) {
alert(list[i].Description);
}
},
error: function(data)
{
alert("ERROR");
}
});
});
</script>
The problem:
The problem is that when i say http://localhost:5348/movies/getmovies in the postman app then it gives me a lot of JSON but when I use the jquery script then I get an empty array which it my variable list.
Hope someone can help here.
Up front thanks ;)
Assuming your client.RetrieveAllFilms() method is returning a collection of objects that contain a property named Description then the script should be
$.ajax(
{
type: "GET",
dataType: 'json',
url: '#Url.Action("getmovies", "movies")', // Do not hard code!
data: "",
success: function(data) {
// data contains the collection as json, so iterate through data
$.each(data, function(index, item) {
// access properties of each item
console.log(item.Description);
});
I have seen several examples and can't seem to get the hang of passing more than one variable to mysql using jquery. Here is my situation:
I have a page with 2 cascading drop downs,( they work great using jquery to update second drop down based on the first drop down.)
when the first drop down is selected jquery updates the second drop down AND passes the customer id to a php script that creates a new record in the tblinvoice table (this also works great no problems.)
when the second drop down is selected I need to pass that value along with the invoice number to my php script so I can update the record with the instid.(this is the part that don't work)
If I only pass the instid and manually put the invoice number in the where clause of the query all works fine. If I omit the where clause all records are updated as expected. I need to know what I am doing wrong or what is missing.
I will try to post the code here
jquery code
$(document).ready(function() {
$("select#cust").change(function() {
var cust_id = $("select#cust option:selected").attr(
'value');
var test = $("#test").val();
var din = $("#idate").val();
$("#inst").html("");
if (cust_id.length > 0) {
$.ajax({
type: "POST",
url: "fetch_inst.php",
data: "cust_id=" + cust_id,
cache: false,
beforeSend: function() {
$('#inst').html(
'<img src="loader.gif" alt="" width="24" height="24">'
);
},
success: function(html) {
$("#inst").html(html);
}
});
if (test == 0) {
$.ajax({
type: "POST",
url: "wo_start.php",
data: "cust_id=" + cust_id,
cache: false,
beforeSend: function() {
},
success: function(html) {
$("#invoice").html(html);
$("#test").val(1);
var inum = $("#inv").val();
$("#invnum").val(din +
"-" + inum);
}
});
}
}
});
$("select#inst").change(function() {
var inst_id = $("select#inst option:selected").attr(
'value');
var custid = $("select#cust option:selected").attr(
'value');
var invid = # ("#inv").val()
if (inst_id.length > 0) {
$.ajax({
type: "POST",
url: "wo_start.php",
data: {
inst_id: inst_id,
}
cache: false,
beforeSend: function() {
},
success: function() {
}
});
}
});
});
I have tried using data: {inst_id:inst_id,custid:custid,invid:invid,} (no update to the table like this)
I also tried data: "inst_id="+inst_id+"&custid="+custid+"&invid="+invid,(this also gives no results.)
Can someone PLEASE look at this jquery and see if I am making a simple error?
Try this format:
data: { inst_id: inst_id, custid: custid, invid: invid },
You can post a JSON object to the server so long as you serialize it and then let the server know the data type.
First you need to define your JSON object:
var postData = { inst_id: inst_id, custid: custid, invid: invid };
Then update your ajax to use the serialized version of that object and let the server know the data type:
$.ajax({
type: "POST",
url: "fetch_inst.php",
data: JSON.stringify(postData),
contentType: "application/json",
..continue the rest of your ajax....
I'm using jQuery ajax call to post process a form.
I want to display a loading message or image while the form is processed and when the action is completed to display a complete message.
How can I do it?
This is my jQuery code.
$s('body').on('click', '#group-update', function() {
var formInputs = $s('input').serializeArray();
var groupId = $s(this).data('group');
var error = $s('#modal .info');
var tr = $s('#dataT-attrgroup').find('tr.on_update');
formInputs.push({
name: 'id',
value: groupId
});
$s.ajax({
type: 'post',
url: 'index.php?controller=attribute&method=updateGroup',
data: formInputs,
dataType: 'JSON',
success: function(data) {
if(data.response === false){
error.addClass('info-error');
error.html(data.message);
}else{
oTable.row(tr).data(data).draw();
$s('#modal').modal('hide');
tr.removeClass('on_update');
$s.growl.notice({
title: 'Success',
message: 'Grupul de atribute a fost actualizat'
});
}
}
});
});
Before ajax function display your loader and inside the success function from your ajax hide it.
As you can see in my example i inserted $('.loader').show(); and $('.loader').hide();
$('.loader').show();
$s.ajax({
type: 'post',
url: 'index.php?controller=attribute&method=updateGroup',
data: formInputs,
dataType: 'JSON',
success: function(data) {
if(data.response === false){
error.addClass('info-error');
error.html(data.message);
}else{
oTable.row(tr).data(data).draw();
$s('#modal').modal('hide');
tr.removeClass('on_update');
$s.growl.notice({
title: 'Success',
message: 'Grupul de atribute a fost actualizat'
});
}
$('.loader').hide();
}
});
According to the PHP docs:
The upload progress will be available in the $_SESSION superglobal when an upload is in progress, and when POSTing a variable of the same name as the session.upload_progress.name INI setting is set to. When PHP detects such POST requests, it will populate an array in the $_SESSION, where the index is a concatenated value of the session.upload_progress.prefix and session.upload_progress.name INI options. The key is typically retrieved by reading these INI settings, i.e.
You should take a look at : https://github.com/blueimp/jQuery-File-Upload/wiki/PHP-Session-Upload-Progress
I think this will definitely help you out!
Display your message just before launching $.ajax();
And close it in the success (and error) callback functions.
example :
$s('body').on('click', '#group-update', function() {
var formInputs = $s('input').serializeArray();
var groupId = $s(this).data('group');
var error = $s('#modal .info');
var tr = $s('#dataT-attrgroup').find('tr.on_update');
formInputs.push({
name: 'id',
value: groupId
});
var dlg = $s('<div/>').text('your message').dialog();
$s.ajax({
type: 'post',
url: 'index.php?controller=attribute&method=updateGroup',
data: formInputs,
dataType: 'JSON',
error:function() {
dlg.dialog('close');
},
success: function(data) {
dlg.dialog('close');
if(data.response === false){
error.addClass('info-error');
error.html(data.message);
}else{
oTable.row(tr).data(data).draw();
$s('#modal').modal('hide');
tr.removeClass('on_update');
$s.growl.notice({
title: 'Success',
message: 'Grupul de atribute a fost actualizat'
});
}
}
});
});
If you go through ajax section of jquery documentation you will notice some more method like success ie error, beforesend, complete etc. Here is the code snippet.
$s.ajax({
type: 'post',
url: 'index.php?controller=attribute&method=updateGroup',
data: formInputs,
dataType: 'JSON',
beforeSend : function(){
// load message or image
},
success: function(data) {
// write code as per requirement
},
complete : function(){
// load complete message where you previously added the message or image, as a result previous one will be overwritten
}
});
I have a link:
<a class="tag" wi_id="3042" wl_id="3693" for_user_id="441" href="#a">
which triggers an ajax call
$(".tag").click(function() {
var for_user_id = $(this).attr("for_user_id");
var wl_id = $(this).attr("wl_id");
var wi_id = $(this).attr("wi_id");
$.ajax({
type: "POST",
url: "/ajax/actions/tag.php",
data: {
'for_user_id': 'for_user_id',
'wl_id': 'wl_id',
'wi_id': 'wi_id'
},
success: function(data){
$(this).text("You've tagged this");
$(this).closest('.gl_buttons_holder').toggleClass('gl_buttons_holder gl_buttons_holder_tagged');
$(this).closest('.gl_buttons').addClass('tagged');
}
});
return false;
});
But in the console I see the following:
TypeError: e is undefined
The ajax file gets processed but the POST data is blank, and the success actions do not happen, so it gets posted with zeros and classes are not changed
I have stared and stared... anything obvious?
this is not passed automatically to the AJAX callback function. You can use the context: parameter to tell jQuery to pass it:
$.ajax({
type: "POST",
url: "/ajax/actions/tag.php",
data: {
'for_user_id': for_user_id,
'wl_id': wl_id,
'wi_id': wi_id
},
context: this,
success: function(data){
$(this).text("You've tagged this");
$(this).closest('.gl_buttons_holder').toggleClass('gl_buttons_holder gl_buttons_holder_tagged');
$(this).closest('.gl_buttons').addClass('tagged');
}
});
You're sending your data wrong, don't call your variables inside single quotes.
$(".tag").click(function() {
var for_user_id = $(this).attr("for_user_id");
var wl_id = $(this).attr("wl_id");
var wi_id = $(this).attr("wi_id");
$.ajax({
type: "POST",
url: "/ajax/actions/tag.php",
data: {
'for_user_id': for_user_id,
'wl_id': wl_id,
'wi_id': wi_id
},
success: function(data){
$(this).text("You've tagged this");
$(this).closest('.gl_buttons_holder').toggleClass('gl_buttons_holder gl_buttons_holder_tagged');
$(this).closest('.gl_buttons').addClass('tagged');
}
});
return false;
});
I have an MVC application with a controller named Angular (I use AngularJS as well), which has an action called GetQuestion. That action returns a JsonResult which looks like this (grabbed from Chrome):
{"game":{"Title":"Diablo III","ImgPaths":["d31.jpg","d32.jpg"]},"Answers":["Diablo III","World of Tanks","Need for Speed"]}
My JS function is like this:
var request = $.ajax({
url: "/Angular/GetQuestion",
dataType: "json",
type: "post",
success: (function (data) { alert(data); })
});
But instead of the Json I wrote above, alert window only says [object Object]
Update
Ok, that was fixed, thaks. However as you may suspect, my goal is not to present this data in alert box, but use it somehow. So here's my controller in Angular
function QuestionCtrl($scope) {
var request = $.ajax({
url: "/Angular/GetQuestion",
dataType: "json",
type: "post",
success: function (data) {
$scope.answers = JSON.stringify(data.Answers);
$scope.imgPath = JSON.stringify(data.game.ImgPaths[0]);
}
});
}
And then the view:
<div ng-controller="QuestionCtrl">
<img class="quizImage" src="~/Gallery/{{imgPath}}"/>
#using (Html.BeginForm("Answer", "Angular", FormMethod.Post))
{
<p ng-repeat="answer in answers"><input type="radio" name="game" value="{{answer}}"/> {{answer}}</p>
<p><input type="submit" value="Answer"/></p>
}
</div>
And I don't have neither image or the questions. If I hardcode them in controller then it's ok.
An alert will show that, i would suggest using console.log(data)
var request = $.ajax({
url: "/Angular/GetQuestion",
dataType: "json",
type: "post",
success: (function (data) { console.log(data); })
});
or as the comments states:
var request = $.ajax({
url: "/Angular/GetQuestion",
dataType: "json",
type: "post",
success: (function (data) { alert(JSON.stringify(data)); })
});
I resolved my second problem like this:
function QuestionCtrl($scope, $http) {
$http.post('/Angular/GetQuestion',null).success(function(data) {
$scope.answers = data.Answers;
$scope.imgPath = data.game.ImgPaths[0];
//console.log($scope.answers);
//console.log($scope.imgPath);
});
}
Note that it's AngularJS.
The reason it's happening is because JSON is an Object in JavaScript. When you type
alert(data);
It will attempt to cast the object to a string which in this case will only output that fact that it's an Object.
To view the contents of an object you can write a simple function to use with an alert or console.log.
function outputProperties(anObject) {
var props = '';
for (var prop in anObject) {
props += '\n' + prop + ' value: ' + anObject[prop];
}
return props;
}
And use it like this
alert(outputProperties(data));
For starters... when ever you are dynamically building the src url for an image (using the {{expression}} syntax from Angular) you need to not use the "src" attribute and use the "ng-src" angular directive. It allows angular time to process your url before the image is loaded.