Menu
  • HOME
  • TAGS

Click actionlink on view, controller checks condition, returns JSON, jQuery Ajax doesn't work

Tag: ajax,json,controller,asp.net-mvc-5,actionlink

Click ActionLink on view, controller checks condition, returns JSON, JQuery Ajax doesn't work.

Click the "Delete" ActionLink, "Delete" controller if customer's "Orders" property is null, if not null, a message will be popped up. If null, process to "Delete" view.

Here are the codes:

1, on the view, the @Html and <script> are together in a loop which goes through all the customers.

@Html.ActionLink("Delete", "Delete", new { id = item.CustomerId }, htmlAttributes: new { @class = "mergo-actionlink", id = "customer-delete-ajax" })

<script type="text/javascript">
$('#customer-delete-ajax').click(
    function doSomething() {
        $.ajax({
            dataType: "json",
            url: '@Url.Action("Delete", "Controllers", new { id = item.CustomerId })',
            success: function (data) {
                alert(data.message);
            },
            async: false
        });
    }
);
</script>

2, the "Delete" controller

public ActionResult Delete(Guid? id)
{
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Customer customer = db.Customers.Find(id);
        if (customer == null)
        {
            return HttpNotFound();
        }

        if (customer.Orders.ToList().Count() != 0)
        {
            return Json(new { message = "This customer has order(s) attached." }, "text/plain", JsonRequestBehavior.AllowGet);
        }
        return View(customer);
}

Best How To :

Your question is anything but easy to interpret, but as for "Ajax doesn't work":

  1. You state that "the @Html and <script> are together in a loop which goes through all the customers". This will be the first error, since this would create a lot of elements using the same Id, and Id's must be unique. Try with class name as trigger instead (example below).

  2. The JavaScript should not be a part of that loop. There is no need to loop this script - if anything it will be damaging. Move it outside of the loop, and try with class as trigger instead like mentioned above (example below).

  3. Both your ActionLink and click event will call the same Action, at the same time, with the same parameter. I'm not sure I understand what your expectation of this is, but I'll assume that the ActionLink is not supposed to call the Action at all.

To solve the above issues, follow those steps and try with this code instead:

// loop begins
@Html.ActionLink("Delete", "Delete", new { id = item.CustomerId }, htmlAttributes: new { @class = "mergo-actionlink", data_value = item.CustomerId })
// loop ends

<script type="text/javascript">
$('.mergo-actionlink').click(function() {
    var clickedId = $(this).attr('data-value');
    $.ajax({
        dataType: "json",
        url: '@Url.Action("Delete", "Controllers")',
        data: { id: clickedId },
        success: function (data) {
            alert(data.message);
        },
        async: false
    });
    return false;
}); 
</script>
  1. And in your controller, comment out the return View(customer);. Actually the only thing that Action should return is json, since that's the only thing your Ajax will accept. You can change your return type to JsonResult to be explicit.

Getting a collection via Ajax to show in view

jquery,ruby-on-rails,ajax

Your partial (currently named: _followup.html.erb in your example) should just be the code to produce a single row, Rails will iterate over it for you, and you should name it after the model it represents, ie. # app/views/assessments/_assessment.html.erb <%= assessment.name %> Then in your app/views/assessments/followups.html.erb view you'd use that partial...

How to send current page number in Ajax request

javascript,jquery,ajax,spring-mvc,datatables

DataTables already sends parameters start and length in the request that you can use to calculate page number, see Server-side processing. If you still need to have the URL structure with the page number, you can use the code below: "ajax": { "data": function(){ var info = $('#propertyTable').DataTable().page.info(); $('#propertyTable').DataTable().ajax.url( "${contextPath}/admin/getNextPageData/"+(info.page...

Deserializing Json data to c# for use in GridView - Error Data source is an invalid type

c#,json,gridview,serialization,.net-4.5

You're binding the container object, not the list itself. Change it to: GridView1.DataSource = personDetail.PersonDetails; And it should work....

Create n:m objects using json and sequelize?

javascript,json,node.js,sequelize.js

Have a look at nested creation (the feature is not documented yet) Store.create({ name:'corner store', address: '123 Main Street', products: [ { name: 'string beans' }, { name: 'coffee' }, { name: 'milk' } ] }, { include: [Product] }); This will create both stores and products and associate the...

Modal won't close on ajax success

jquery,ajax

You're using the wrong method to hide the element. Change this: $('#modal-container').modal('hide'); To this: $('#modal-container').hide(); Or if you want to completely remove it from the page, change it to this: $('#modal-container').remove(); ...

how to use geocoder class to retrieve latitude and longitude through ajax

javascript,ajax,google-maps

Because of it's scope, your codeAddress javascript function is not visible for outer caller myLoop, as it is enclosed within myFunction, therefore you get the codeAddress is not defined. Try to rewrite your code similar to this (I have not tested, so it might not work right away, but you...

JQuery mutiple post in the same time

javascript,php,jquery,json

You can use the jQuery when function (https://api.jquery.com/jquery.when/) to wait for all three promises to resolve. You only need to make sure you also return the promise in your nb1, nb2, nb3 functions. function nb1() { return $.post("p1.php", { action: 1 }, function(data) { console.log(data); }, "json") .fail(function(data) { console.log("error");...

Why i get can not resolve method error in class android?

android,json

You didn't create setName() method in Person class. public class Person { private String name; private String country; private String twitter; //getters & setters.... public void setName(String pName) { this.name = pName; } public void getName() { return this.name; } } ...

Can't save json data to variable (or cache) with angularjs $http.get

json,angularjs,web-services,rest

$http.get is asynchronous. When cache.get or return result are executed, HTTP request has not completed yet. How are you going to use that data? Display in UI? E.g. try the following: // Some View <div>{{myData}}</div> // Controller app.controller('MyController', function ($scope) { $http.get('yoururl').success(function (data) { $scope.myData = data; }); }); You...

Check for duplicates in JSON

javascript,jquery,json,duplicates

var asset = [ { value1: "1", value2: "2", value3: "3" }, { value1: "1", value2: "5", value3: "7" }, { value1: "6", value2: "9", value3: "5" }, { value1: "6", value2: "9", value3: "5" } ]; function countEqual(oo, pp) { var count = 0; oo.forEach(function (el) { var i,...

php array returns undefined but print_r shows otherwise [duplicate]

php,arrays,json,undefined

The array you're looping looks like this: Array ( [0] => Array ( [mstatus] => 1 [mhearingnum] => first [mminutes] => adakjaflafjlarjkelfkalfkd;la ) [1] => Array ( [mhearingnum] => second [mminutes] => ) [2] => Array ( [mhearingnum] => third [mminutes] => ) ) Only the sub array at the...

Use JSON file to insert data in database

javascript,json,mongodb,meteor,data

Simple use underscores _.extend function. Like this: var newProfile = _.extend( JSON.parse(Assets.getText('test.json')), {user: id} ) Profiles.insert(newProfile) ...

Disable 2 buttons after click of a button

javascript,php,jquery,html,ajax

You can achieve this by disabling the buttons before you make the AJAX request, and then enabling them again in the complete handler of the request. Try this: var onSubmit = function(e) { var txtbox = $('#txt').val(); var hiddenTxt = $('#hidden').val(); $('.botleftbtn, .botrightbtn').prop('disabled', true); // < disable the buttons $.ajax({...

Serializing a java bean into a cookie: Is it bad?

java,json,cookies

I guess the answer depends on your answer to these questions: Since you can never trust ANYTHING that comes in a client request, are there any harmful effects that could come by a hacker spoofing the pojo value? By sending the object to the client, does this expose any internal...

How to rearrange CSV / JSON keys columns? (Javascript)

javascript,json,csv,papaparse

Papa Parse allows to specify order of fields in the unparse() function: var csv = Papa.unparse({ fields: ["ID", "OrderNumber", "OrderStatus", "StartTime", "FinishTime", "canOp", "OpDesc", "UOM"], data: [{ OrderStatus: "Good", canOp: "True", OpDesc: "Good to go", ID: "100", OrderNumber: "1000101", FinishTime: "20:50", UOM: "K", StartTime: "18:10" }, // ... ] });...

How to return value in Meteor.JS from HTTP.call “GET”

javascript,ajax,http,meteor,facebook-javascript-sdk

Don't pass a callback to get the HTTP to return. You're also able to pass off URL parameters quite easily: var result = HTTP.call("GET", "https://graph.facebook.com/me", { params: { access_token : Meteor.user().services.facebook.accessToken, fields : "likes.limit(5){events{picture,cover,place,name,attending_count}}" } }); console.log(result); ...

WooCommerce seems to only orderby date and not price

php,ajax,wordpress,woocommerce

Try this: $args = array( 'post_type' => 'product', 'posts_per_page' => 100, 'product_cat' => 'beast-balls', 'orderby' => 'meta_value_num', 'meta_key' => '_price', 'order' => 'asc' ); ...

Replacing elements in an HTML file with JSON objects

javascript,json,replace

obj.roles[0] is a object {"name":"with whom"}. you cant replace string with object. you need to refer to property "name" in the object obj.roles[0].name Another problem is that var finalXML get a new value every line. you need to add a new value to the variable, not replcae it. var finalXML...

convert from json to array

javascript,php,json

First off, your associative array is flipped. You need to change array($wholeNumber['DocumentNbr'] => 'Number', $wholeNumber['DocumentRevision'] => 'Revision'); to array('Number' => $wholeNumber['DocumentNbr'], 'Revision' => $wholeNumber['DocumentRevision']); You need that in order to access the elements of the JSON. Then, in your loop, you would use wholeNumberData[i].Number to get the number and wholeNumberData[i].Revision...

Link to another resource in a REST API: by its ID, or by its URL?

json,api,rest,api-design,hateoas

DO include absolute entity URIs in your responses (such as /customers/12 or even http://www.example.com/customers/12). DO NOT include just an entity's ID (such as 12) in a response, because that way you're forcing clients to put together resource URIs themselves. In order to do that, they would need to have prior...

Uncaught error: Invalid type for google table column

javascript,json,google-maps,google-visualization

You should change your row data.addColumn('String', 'sitecode'); to data.addColumn('string', 'sitecode'); (non capital "s" in "string"), of course this applies to all of your added columns. Javascript is case-sensitive....

Parsing Google Custom Search API for Elasticsearch Documents

json,python-2.7,elasticsearch,google-search-api

here is a possible answer to your problem. def myfunk( inHole, outHole): for keys in inHole.keys(): is_list = isinstance(inHole[keys],list); is_dict = isinstance(inHole[keys],dict); if is_list: element = inHole[keys]; new_element = {keys:element}; outHole.append(new_element); if is_dict: element = inHole[keys].keys(); new_element = {keys:element}; outHole.append(new_element); myfunk(inHole[keys], outHole); if not(is_list or is_dict): new_element = {keys:inHole[keys]}; outHole.append(new_element);...

Parse JSON output from AlamoFire

json,swift,nsurlrequest

If I believe the println of aStatus, the property title is a String, not a Dictionary. Change this part in your code (cast as String instead of as NSDictionary): if let user = aStatus["title"] as? String { println( "TITLE \(user)") } ...

Sorting in Ruby on rails

ruby-on-rails,json,sorting

You're not getting the results you want because you're not assigning the sorted user_infos back into the user_infos variable. You can do the following: user_infos = user_infos.sort {|a, b| - (a['can_go'] <=> b['can_go']) } # -or- user_infos.sort! {|a, b| - (a['can_go'] <=> b['can_go']) } The first version of sort creates...

Making an alert() with PHP and ajax

javascript,php,jquery,ajax

You're trying to output javascript from the php, without outputting it in your ajax callback, won't work. The easiest way to do what you want, is to return the string with your php, and handle the outputting to your javascript. something like : if($QueueCount == 1){ Echo "You already have...

'utf8' codec can't decode byte 0xf3

python,json,character-encoding

Your file is not encoded in UTF-8, and the error occurs at the fp.read() line. You must use: import io io.open(filename, encoding='latin-1') And the correct, not platform-dependent usage for joining your paths is: os.path.join(root, f) ...

Automatically calling server side class without

javascript,html,ajax

Trigger the click event like this: $('._repLikeMore').trigger('click'); ...

Response 200 OK but Jquery shows error?

javascript,jquery,json

The code you've supplied, by itself, works fine. It breaks if you try to force the use of JSONP because the server you are making the request to doesn't support that. It does support CORS (which is the modern replacement for JSONP), and you don't need to do anything special...

Is there a way to fire an event every time an ajax call in made in AngularJS?

javascript,ajax,angularjs,express

In Angular this can be solved with an interceptor. See Angular-loading-bar as example.

cross domain ajax form post — How is this allowed?

jquery,ajax

If the server has a response header of 'Access-Control-Allow-Origin': '*' or something similar, it will return a response. In short, this has nothing to do with jQuery, and has everything to do with the server. In the case above, * is a wildcard representing all origins. But it could also...

do calculation inside JSONArray in Java

java,arrays,json

Here's what I would do. Replace <JSON STRING HERE> with the JSON String you were going to parse: ArrayList<ArrayList<Integer>> resultList = new ArrayList<ArrayList<Integer>>(); JSONArray arr = new JSONArray(<JSON STRING HERE>); for(int i = 0; i < arr.length(); i ++) { JSONObject obj = arr.getJSONObject(i); JSONArray valueArray = obj.getJSONArray("values"); ArrayList<Integer> dataList...

Nested JSON structure to build side-by-side d3.js charts

javascript,json,d3.js

No, you don't need to use .nest here. The easiest way to build the required data structure is as you suggest (d3 always wants an array to iterate over): var nestedData = [ years[0].chartOne, years[0].chartTwo ]; After that, it's as simple as cleaning up the accessor functions for your data...

Insert data in collection at Meteor's startup

javascript,json,meteor,data,startup

Ok, you'll want to check out Structuring your application. You'll have to make the file with the definition load earlier, or the one with the fixture later. Normally you have your collections inside lib/ and your fixtures inside server/fixtures.js. So if you put your insert code into server/fixtures.js it'll work....

How to calculate values of a drop down menu with PHP/ JS?

javascript,php,ajax

I am not sure by your question if you want to add it to the db on the selection... that would require a simple but different code. This will accomplish what you are asking. You do not need a form... just the selection boxes. If you notice I encased each...

Fatal error catched by register_shutdown_function and update json_encode

php,json,fatal-error

Why move one array to another array and then echo the second array. Why not just do this function shutdown(){ $error = error_get_last(); echo json_encode($error); } Or even this function shutdown(){ echo json_encode(error_get_last()); } Apart form the use of an unnecessary array, this will give you all the information available...

why i don't get return value javascript

javascript,jquery,html,json,html5

the first "A" in AJAX stands for "Asynchronous" that means, it is not executed right after it has been called. So you never get the value. Maybe you could first, get the os list and then output what you need, like this: function createCheckBoxPlatform(myDatas) { $.ajax({ url: "/QRCNew/GetOS", type: "post",...

Using $.ajaxStop() to determine when page is finished loading in CasperJS

javascript,jquery,ajax,phantomjs,casperjs

I would do something like this in include.js: (function(){ window._allAjaxRequestsHaveStopped = false; var interval; $(document).ajaxStop(function() { if (interval) { clearInterval(interval); interval = null; } interval = setTimeout(function(){ window._allAjaxRequestsHaveStopped = true; }, 500); }); $(document).ajaxStart(function() { if (interval) { clearInterval(interval); interval = null; } }); })(); This sets a (hopefully unique)...

Jquery parsley validate not working

javascript,php,jquery,ajax,parsley.js

Make sure this line: $('#remarks').parsley( 'addConstraint', { minlength: 5 }); is called before you check isValid()....

When is the cookie set by AJAX available in javascript?

javascript,ajax,cookies

Cookies are passed as HTTP headers, both in the request and in the response. When you do an ajax call and set a cookie, that cookie will only be available in the browser after a reload / redirect happens, and new headers are gotten from the server containing the newly...

KendoUI Grid - Complex JSON with inconsistent keys

javascript,json,kendo-ui,kendo-grid

You can use column templates: columns: [ { field: "id", title: "User Id" }, { field: "name", title: "User Name", }, { field: "type", title: "User Type", template: function(dataItem) { return dataItem.type ? kendo.htmlEncode(dataItem.type) : ""; } }, { field: "address", title: "Street 1", template: function(dataItem) { return dataItem.address.street1 ?...

access the json encoded object returned by php in jquery

php,jquery,ajax,json

Try: $.ajax({ url: "functions.php", dataType: "JSON", data: {id: id}, type: 'POST', success: function(json){ for(var i=0;i<json.length;i++){ alert(json[i].fname); } } }); ...

Run AJAX function on form submit button after javascript confirm() cancel

javascript,jquery,ajax,wordpress,forms

Dont use one(it will fire ajax submit or button click only once) , use here var IsBusy to check user is not repeatedly pressing the form submit, Try below code, var isBusy = false; //first time, busy state is false $('#publish').on('click', function (e) { if(isBusy == true) return ; //if...

Identifier starts immediately after numeric literal

jquery,ajax,razor

I think you have to include it with the ' mark Like this : var userID = '@User.Identity.GetUserId()';...

Deserializing JSON into c# class

c#,json,couchdb

You could create a custom JsonConverter for this: [JsonConverter(typeof(ClickConverter))] public class Click { public DateTime Date { get; set; } public string Code { get; set; } public string Url { get; set; } public int Count { get; set; } } public class ClickConverter : JsonConverter { public override...

Unable to upload file to Sharepoint @ Office 365 via REST

javascript,ajax,rest,sharepoint,office365

To me it just seems a bit light, visit this link https://msdn.microsoft.com/en-us/library/office/dn769086.aspx on technet, and compare your upload function to this: // Add the file to the file collection in the Shared Documents folder. function addFileToFolder(arrayBuffer) { // Get the file name from the file input control on the page....

Codeigniter Select JSON, Insert JSON

json,codeigniter,select,insert,routing

You want to return json object in response, so it's required to set json type in response header. As given here public function select(){ $data['query'] = $this->users->select(); $this->output ->set_content_type('application/json') ->set_output(json_encode($data['query'])); } It is required to encode part as below for insert part. so you can use this generated url to...

Call function on Server from iOS app - Objective C

ios,objective-c,json,server,backend

You just need to POST data to your server. Port could be anything you want, should be 80. Host your script with a domain url so that you can make network request publicly. You can try this function: -(NSData *)post:(NSString *)postString url:(NSString*)urlString{ //Response data object NSData *returnData = [[NSData alloc]init];...

String comparison in AngularJS

javascript,json,angularjs,ionic-framework,string-comparison

You are iterating over wrong node:) for(var i=0;i<$rootScope.items.length;i++) { alert("Inside for loop"); if (name === $rootScope.items[i].names) // you iterate over items, not names, which it an Json property inside item { alert("If condition satisfied"); } } ...

Loading external php file in a div with jquery ajax

javascript,php,jquery,ajax,mysqli

You have to add jquery js in your html code. you can use online jquery. <script src="//code.jquery.com/jquery-1.11.3.min.js"></script> <script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script> ...