ajax,json,controller,asp.net-mvc-5,actionlink , Click actionlink on view, controller checks condition, returns JSON, jQuery Ajax doesn't work

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">
    function doSomething() {
            dataType: "json",
            url: '@Url.Action("Delete", "Controllers", new { id = item.CustomerId })',
            success: function (data) {
            async: false

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);


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');
        dataType: "json",
        url: '@Url.Action("Delete", "Controllers")',
        data: { id: clickedId },
        success: function (data) {
        async: false
    return false;
  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.


Automatically calling server side class without

I have an anchor which calls a server side class when clicked, but I want to modify it so that the class is called as soon as the page loads, without having to click an anchor. <a href="#" class="_repLikeMore" data-id="1234" data-type="pid" data-app="forums"> ...

Getting a collection via Ajax to show in view

All I'm trying to do is have a collection populate in the view when a user clicks a button. But I feel like I'm making this way too complicated and it's not working. See my code - where am I going wrong? Click handler: $('#filterrific_results').find('.followup-injury').on('click', function(e){ e.preventDefault(); $.ajax({ url: "/assessments/followups",...

JQuery mutiple post in the same time

I have three functions ,and every function post to special php page to get data.. and every function need some time because every php script need some time .. function nb1() { $.post("p1.php", { action: 1 }, function(data) { console.log(data); }, "json") .fail(function(data) { console.log("error"); }); } function nb2() {...

Disable 2 buttons after click of a button

I have a submit button on page index.php When i click this button another script (call.php) is called through ajax that holds some response. Now i want that time between the click of submit button and response displayed/received under a div through the call of ajax script the buttons option1...

When is the cookie set by AJAX available in javascript?

I'm doing an AJAX call and setting a cookie in the user browser in the response (the server code sets the cookie). I noticed in the success callback from the ajax, the cookie is not available. When I look in document.cookie the new cookie is not there. My question, when...

cross domain ajax form post — How is this allowed?

I am using jQuery and jQuery form plugin There is a method in jQuery form plugin ajaxSubmit. You pass a form and then it submits it via ajax and you get a response. I am wondering how this is possible since the form is on a different server than the...

String comparison in AngularJS

I'm trying to compare two strings in AngularJS, and I've seen examples online. As I understand it, you can use angular.equals(str1, str2), you can use ===, you can use == if you're sure that both are strings... I've tried all three, but I don't get the result. Something must be...

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

the json array which contains the list of addresses [ { "id": 0, "title": "Coop.Sociale Prassi e Ricerca Onlus", "latitude": 0, "longitude": 0, "address": "Viale Eleonora D'Arborea 12, Roma, IT" }, { "id": 0, "title": "San Lorenzo", "latitude": 0, "longitude": 0, "address": "Viale della Primavera 330, Roma, IT" },...

Call function on Server from iOS app - Objective C

If you are familiar with Parse.com's Javascript SDK, this is what I am trying to do for my own server for my iOS app (Objective-c). I want to be able to send some a string to the function that is on my server, have the server run its function and...

WooCommerce seems to only orderby date and not price

I am loading in variable products via a custom WP_Query $args = array( 'post_type' => 'product', 'posts_per_page' => 100, 'product_cat' => 'beast-balls', 'orderby' => 'date', 'order' => 'desc' ); $loop = new WP_Query( $args ); if ( $loop->have_posts() ) { while ( $loop->have_posts() ) : $loop->the_post(); ?> <div class="product-node cat-beast-balls">...

Response 200 OK but Jquery shows error?

I am stuck in kind of a weird problem where I am trying to make a JSONP request to the Open Weather history API to get the weather information for the previous years on the a particular date. fetchHistoryUrl = ''; $.ajax({ method: 'get', url: fetchHistoryUrl, success: function(response){ console.log(response); },...

Parsing Google Custom Search API for Elasticsearch Documents

After retrieving results from the Google Custom Search API and writing it to JSON, I want to parse that JSON to make valid Elasticsearch documents. You can configure a parent - child relationship for nested results. However, this relationship seems to not be inferred by the data structure itself. I've...

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

I use this tutorial: JSON and part of code to this: protected String doInBackground(String... urls) { TextView lbl=(TextView) findViewById(R.id.provCODE); person = new Person(); person.setName(lbl.getText().toString()); //person.setCountry("1853"); //person.setTwitter("1892"); return POST(urls[0],person); } but in the this line: person.setName(lbl.getText().toString()); i get this error: Can not resolve method. How can i solve that?what happen? my...

Fatal error catched by register_shutdown_function and update json_encode

I can catch a fatal error with register_shutdown_function('shutdown') function shutdown(){ $error = error_get_last(); $result['message'] = $error['message']; } and I have an echo json_encode($result); Unfortunately this echo json_encode shows nothing because json is not updated with the message of the fatal error. What can I do to fix this?...

why i don't get return value javascript

When i debug my code i can see i have value but i don't get value to createCheckBoxPlatform FN function createCheckBoxPlatform(data) { var platform = ""; $.each(data, function (i, item) { platform += '<label><input type="checkbox" name="' + item.PlatformName + ' value="' + item.PlatformSK + '">' + item.PlatformName + '</label>' +...

convert from json to array

I am trying to get data to display in a table. I don't know what I am doing wrong, but when I get the data from my page it is an array of single characters. I could parse this myself but would prefer to know what I am doing wrong....

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

In the organization that i work for, there was a serious debate about the following. Scenario: There is a POJO with 6 different properties all are of type Strings. These values need to be persisted as cookies so that it can be picked back when someone does a booking on...

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

I am creating some APIs using apiary, so the language used is JSON. Let's assume I need to represent this resource: { "id" : 9, "name" : "test", "customer_id" : 12, "user_id" : 1, "store_id" : 3, "notes" : "Lorem ipsum example long text" } Is it correct to refer...

Sorting in Ruby on rails

I'm very new to Ruby on rails. I try to edit the following api. I want to sorting "can_go" which is true are shown at the top of list. I added this row before sending data, but the result is still order by "user_id". user_infos.sort { |a, b| - (a['can_go']<=>b['can_go'])...

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

I am converting a JSON object array to CSV using Papa Parse JavaScript Library. Is there a way to have the CSV columns arranged in a certain way. For e.g; I get the column as: OrderStatus, canOp, OpDesc, ID, OrderNumber, FinishTime, UOM, StartTime but would like to be arranged as:...

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

I have weird angularjs problem. I'm trying to fetch data from Rest Webservice. It works fine, but I can't save json data to object. My code looks like: services.service('customerService', [ '$http', '$cacheFactory', function($http, $cacheFactory) { var cache = $cacheFactory('dataCache'); var result = cache.get('user'); this.getById = function(id){ $http.get(urlList.getCustomer + id).success(function(data, status,...

Loading external php file in a div with jquery ajax

i am making a simple project..and i need to load data from other page in an index.php..and i have set time of 20sec. but its not working.. could u please tell me what is wrong with the query..Thanks already.. index.php <?php include 'connection.php'; ?> <html> <head> <title> My First Chat...

Insert data in collection at Meteor's startup

I would like to insert data at Meteor's startup. (And after from a JSON file) At startup, I create a new account and I would like to insert data and link it to this account once this one created. This is the code that creates the new account at startup:...

Jquery parsley validate not working

if($("#dataform").parsley().isValid()){ $.ajax({ url : '<?php echo base_url();?>index.php/company/final_review?id=<?php echo $this->input->get('id'); ?>', type : 'POST', data : $("#dataform").serialize(), dataType:"json", beforeSend: function(){ $('#remarks').parsley( 'addConstraint', { minlength: 5 }); }, success : function(data){ console.log(data); } }); } This is my ajax part. The plugin is not validating the field it's submitting the form. The...

php array returns undefined but print_r shows otherwise [duplicate]

This question already has an answer here: PHP: “Notice: Undefined variable” and “Notice: Undefined index” 11 answers foreach($jsonmediationinfo as $value1) { echo $value1['mstatus']; print_r($jsonmediationinfo); } Output: 1Array ( [0] => Array ( [mstatus] => 1 [mhearingnum] => first [mminutes] => adakjaflafjlarjkelfkalfkd;la ) [1] => Array ( [mhearingnum] => second...

Replacing elements in an HTML file with JSON objects

I am writing some Javascript to: Read in and Parse a JSON file Read in an HTML file (created as a template file) Replace elements in the HTML file with elements from the JSON file. It is only replacing the first element obj.verb. Can someone please help me figure out...

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

So far in my tests written in CasperJS, I've been using waitForSelector() on page-specific elements to determine if a page has fully loaded (including all the async ajax requests). I was hoping to come up with a more standard way of waiting for page load and was wondering if the...

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

I'm writing a meteor method, which should return a Facebook response for HTTP.call on graph api, but HTTP.call has only a callback function to show error/response, so I can't take this data outside, and Method can not return any value. Here's my method code: loadUserFBEvents: function () { var accessToken...

Deserializing JSON into c# class

I have a JSON in the following format (from couchDB view) {"rows":[ {"key":["2015-04-01","524","http://www.sampleurl.com/"],"value":1}, {"key":["2015-04-01","524","http://www.sampleurl2.com/"],"value":2}, {"key":["2015-04-01","524","http://www.sampleurl3.com"],"value":1} ]} I need to create a "service" to get this data from couchDB and insert it on SQL Server (for generating reports..) in a efficient way. My first bet was to bulk insert this json...

do calculation inside JSONArray in Java

I have a simple issue but cannot solve it as I am not very good at algorithm! I have an JSONArray in this form: [{"values":[{"time":1434976493,"value":"50"}, {"time":1434976494,"value":"100"}],"counter":"counter1"}, {"values":[{"time":1434976493,"value":"200"}, {"time":1434976494,"value":"300"}],"counter":"counter2"}, {"values":[{"time":1434976493,"value":"400"}, {"time":1434976494,"value":"600"}],"counter":"total"}] What I want to do is to get the integer value for counter 1 and counter 2 and then divide...

Codeigniter Select JSON, Insert JSON

I have very simple users database: user_id, user_name, user_email My model this: class Users extends CI_Model { private $table; private $table_fields; private $table_fields_join; function __construct() { parent::__construct(); $this->table = 'users'; $this->table_fields = array( $this->table.'.user_id', $this->table.'.user_name', $this->table.'.user_email' ); $this->table_fields_join = array(); } function select(){ $this->db->select(implode(', ', array_merge($this->table_fields, $this->table_fields_join)));...

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

I'm currently stuck on how to traverse a JSON structure (I created) in order to create side-by-side donut charts. I think I've created a bad structure, but would appreciate any advice. I'm working from Mike Bostock's example here: http://bl.ocks.org/mbostock/1305337 which uses a .csv file for source data. In that example...

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

I have a form where and AJAX function runs on form submission to make sure that the data in the form doesn't conflict with data in the database. If a conflict is found, the AJAX function pops up a confirm() box. If the user clicks "OK", the form is submitted....

Modal won't close on ajax success

I'm loading in the content of a modal with ajax. I have a button that submits the modal form and is suppose to close the modal when it's done processing the ajax submit so it can update a table at the bottom of the page. It's not closing the modal...

Unable to upload file to Sharepoint @ Office 365 via REST

I'm having trouble creating/uploading files via Microsoft's REST API (or at least that's what they call it) for Sharepoint running on Office 365. It looks like I'm able to authenticate all right, but I'm getting 403 Forbidden when I try to create a file. The same user can upload a...

Create n:m objects using json and sequelize?

I am trying to learn sequelize, but am having trouble getting a n:m object created. So far I have my 2 models that create 3 tables (Store, Product, StoreProducts) and the models below: models/Store.js module.exports = (sequelize, DataTypes) => { return Store = sequelize.define('Store', { name: { type: DataTypes.STRING, },...

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

I am relatively new to working with C# (v5.0) and Json data (Newtonsoft.Json v6.0) and am seeking assistance in resolving an error when attempting to populate a .Net 4.5 GridView control. My sample Json data as returned by a web service is: { PersonDetails: [ { Book: "10 ", FirstName:...

KendoUI Grid - Complex JSON with inconsistent keys

I know this is probably been asked before, but having tried to find an answer - I am guessing either I am not comprehending some of the answers right, or I am looking at the problem all wrong. I am using a complex SLC loopback query - and the api...

'utf8' codec can't decode byte 0xf3

I am using python 2.7 to read the json file. my code is import json from json import JSONDecoder import os path=os.path.dirname(os.path.abspath(__file__))+'/json' print path for root, dirs, files in os.walk(os.path.dirname(path+'/json')): for f in files: if f.lower().endswith((".json")): fp=open(root + '/'+f) data = fp.read() print data.decode('utf-8') But I got the following error....

Making an alert() with PHP and ajax

I have an ajax function that submits some data to my PHP file. In my PHP file I have some checks that it does with that data, I then try to make an alert to come up to say something. I can't get any alerts to come up though. All...

How to send current page number in Ajax request

I am using jQuery DataTable to display huge amount of data in a table. I am getting data page wise on Ajax request like this: var pageNo = 1; $('#propertyTable').dataTable( { "processing": true, "serverSide": true, "ajax": "${contextPath}/admin/getNextPageData/"+pageNo+"/"+10, "columns": [ { "data": "propertyId" }, { "data": "propertyname" }, { "data": "propertyType"...

Check for duplicates in JSON

I have a json object: var object1 = [{ "value1": "1", "value2": "2", "value3": "3", }, { "value1": "1", "value2": "5", "value3": "7", }, { "value1": "6", "value2": "9", "value3": "5", }, { "value1": "6", "value2": "9", "value3": "5", }] Now I want to take each record out of that...

Parse JSON output from AlamoFire

I am using the latest Alamofire to manage a GET http request to my server. I am using the following to GET and parse the JSON: Alamofire.request(.GET, "*******") .responseJSON {(request, response, JSON, error) in if let statusesArray = JSON as? NSArray{ if let aStatus = statusesArray[0] as? NSDictionary{ //OUTPUT SHOWN...

Identifier starts immediately after numeric literal

I'm trying to get the current logged in usersID in my jquery function var userID = @User.Identity.GetUserId(); Many answers on this page say that I have to do something like \"@User.Identity.GetUserId()\" But it dont seem to work, can someone tell me how to fix it. Its for my ajax post....

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

Hi I have been very puzzled how to do this and cannot find any relevant tutorial that could help me so I thought I would ask here and hope to find the help. I have a form with 2 drop down menus, each of them having a value attribute. What...

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

What I'm trying to do is every time a call to the backend is made, I want a spinner to load up with a dark overlay. I know I can do this by simply running the spinner before the call is made, but I'm working with multiple developers and I...

Uncaught error: Invalid type for google table column

I recently started using google visualization due to its simplicity. But while implementing in my recent project i seem to have run into a bit of trouble. The program shown is used to pull data from a JSON object and utilize it to display data in the google tables. Now...

access the json encoded object returned by php in jquery

I want to post some data to php function by ajax, then get the encoded json object that the php function will return, then I want to get the information (keys and values) from this object, but I don't know how, here is my code: $.ajax({ url: "functions.php", dataType: "JSON",...

Use JSON file to insert data in database

I'm using my JSON file like this to insert data in my collection : var content = JSON.parse(Assets.getText('test.json')); console.log('inserting...'); Profiles.insert({ user: id, data:content }; But I would like to have a "data's tree" like that : [ user: "rtegert23423131", firstname:"test", surname:"test2", // ... ] Not like that : [ user:...