Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SyntaxError: invalid regular expression flag ajax, Javascript

Tags:

This is my controller,

public ActionResult ReturnMethodTest(int id) 
{
    string name = "John";
    return Json( new {data=name});       
}

I am trying to get data from this controller by using code below but I am getting Syntax error .

Can you please tell me what am I doing wrong?

$.ajax({
        url: @Url.Action("ReturnMethodTest", "HomeController"),
        data: {
            id: 5,
        },
        success: function (data) {
            console.log(data);
        }
    });
like image 708
Da Artagnan Avatar asked Jul 13 '15 06:07

Da Artagnan


1 Answers

@Url.Action only returns the action url's string, without quotes around it.

You'll need to wrap that url in quotes.

Replace:

url: @Url.Action("ReturnMethodTest", "HomeController"),

With:

url: '@Url.Action("ReturnMethodTest", "HomeController")',
//   ^                                                 ^

Otherwise, the file returned to the client will contain:

url: /HomeController/ReturnMethodTest,

Which isn't valid JS, nor what you want. The replacement gives the following result:

url: '/HomeController/ReturnMethodTest',

Which is a perfectly valid JavaScript string.

like image 156
Cerbrus Avatar answered Sep 24 '22 05:09

Cerbrus