Меню

Ошибка expected expression got

I got SyntaxError: expected expression, got '<' error in the console when i’m executing following node code

var express = require('express');
var app = express();
app.all('*', function (req, res) {
  res.sendFile(__dirname+'/index.html') /* <= Where my ng-view is located */
})
var server = app.listen(3000, function () {
  var host = server.address().address
  var port = server.address().port
})

Error :enter image description here

I’m using Angular Js and it’s folder structure like bellow

enter image description here

What’s I’m missing here ?

asked Mar 6, 2015 at 7:30

underscore's user avatar

This code:

app.all('*', function (req, res) {
  res.sendFile(__dirname+'/index.html') /* <= Where my ng-view is located */
})

tells Express that no matter what the browser requests, your server should return index.html. So when the browser requests JavaScript files like jquery-x.y.z.main.js or angular.min.js, your server is returning the contents of index.html, which start with <!DOCTYPE html>, which causes the JavaScript error.

Your code inside the callback should be looking at the request to determine which file to send back, and/or you should be using a different path pattern with app.all. See the routing guide for details.

answered Mar 6, 2015 at 7:33

T.J. Crowder's user avatar

T.J. CrowderT.J. Crowder

1.0m184 gold badges1866 silver badges1835 bronze badges

4

Try this, usually works for me:

app.set('appPath', 'public');
app.use(express.static(__dirname +'/public'));

app.route('/*')
  .get(function(req, res) {
    res.sendfile(app.get('appPath') + '/index.html');
  });

Where the directory public contains my index.html and references all my angular files in the folder bower_components.

The express.static portion I believe serves the static files correctly (.js and css files as referenced by your index.html). Judging by your code, you will probably need to use this line instead:

app.use(express.static(__dirname));

as it seems all your JS files, index.html and your JS server file are in the same directory.

I think what @T.J. Crowder was trying to say was use app.route to send different files other than index.html, as just using index.html will have your program just look for .html files and cause the JS error.

Hope this works!

answered May 14, 2015 at 23:55

devonj's user avatar

devonjdevonj

1,1281 gold badge12 silver badges23 bronze badges

The main idea is that somehow HTML has been returned instead of Javascript.

The reason may be:

  • wrong paths
  • assets itself

It may be caused by wrong assets precompilation. In my case, I caught this error because of wrong encoding.

When I opened my application.js I saw
application error Encoding::UndefinedConversionError at /assets/application.js

There was full backtrace of error formatted as HTML instead of Javasript.

Make sure that assets had been successfully precompiled.

answered Sep 18, 2015 at 10:12

Nick Roz's user avatar

Nick RozNick Roz

3,6692 gold badges35 silver badges55 bronze badges

2

I had same error. And in my case

REASON: There was restriction to that resources on server and server was sending login page instead of javascript pages.

SOLUTION: give access to user for resourses or remove restriction at all.

answered Sep 2, 2015 at 11:27

Erlan's user avatar

ErlanErlan

1,9711 gold badge22 silver badges31 bronze badges

You can also get this error message when you place an inline tag in your html but make the (common for me) typo that you forget to add the slash to the closing-script tag like this:

<script>
  alert("I ran!");
<script> <!-- OOPS opened script tag again instead of closing it -->

The JS interpreter tries to «execute» the tag, which looks like an expression beginning with a less-than sign, hence the error: SyntaxError: expected expression, got '<'

answered Nov 3, 2015 at 15:00

gigawatt's user avatar

gigawattgigawatt

871 silver badge4 bronze badges

2

Just simply add:

app.use(express.static(__dirname +'/app'));

where '/app' is the directory where your index.html resides or your Webapp.

Pang's user avatar

Pang

9,335146 gold badges85 silver badges121 bronze badges

answered May 26, 2017 at 7:12

Moolshankar Tyagi's user avatar

2

I had this same error when I migrated a WordPress site to another server.
The URL in the header for my js scripts was still pointing to the old server and domain name.

Once I updated the domain name, the error went away.

answered Mar 20, 2015 at 21:11

Birdie Golden's user avatar

I had a similar problem using Angular js. i had a rewrite all to index.html in my .htaccess.
The solution was to add the correct path slashes in .
Each situation is unique, but hope this helps someone.

answered Aug 4, 2015 at 16:58

phil's user avatar

philphil

8089 silver badges15 bronze badges

This problem occurs when your are including file with wrong path and server gives some 404 error in loading file.

answered Aug 7, 2015 at 12:06

Muhammad Khalid's user avatar

0

This should work for you. If you are using SPA.

app.use('/', express.static(path.join(__dirname, 'your folder')));
// Send all other requests to the SPA
app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, 'your folder/index.html'));
});

answered Oct 23, 2017 at 8:07

tigercosmos's user avatar

tigercosmostigercosmos

3253 silver badges15 bronze badges

I was getting this error when trying to access an angular SPA via ASP.NET Core. Turns out the environment variables were not being loaded correctly, and the following line was not being called:

app.UseSpaStaticFiles();

After I ensured the line was getting called, the app started working again.

answered Jan 21, 2022 at 17:46

Eternal21's user avatar

Eternal21Eternal21

3,8522 gold badges43 silver badges58 bronze badges

I got this type question on Django, and My issue is forget to add static to the <script> tag.

Such as in my template:

<script  type="text/javascript"  src="css/layer.js"></script>

I should add the static to it like this:

<script type="text/javascript" src="{% static 'css/layer.js' %}" ></script>

answered Oct 19, 2017 at 6:34

aircraft's user avatar

aircraftaircraft

23.1k24 gold badges87 silver badges161 bronze badges

May be this helps someone. The error I was getting was

SyntaxError: expected expression, got ‘<‘

What I did clicked on view source in chrome and there I found this error

Notice: Undefined variable: string in
D:Projectsdemoge.php on line 66

The issue was this snippet of code,

$string= ''; <---- this should be declared outside the loop

while($row = mysql_fetch_assoc($result))
    {
        $string .= '{ id:'.$row['menu_id'].', pId:'.$row['parent_id'].', name:"'.$row['menu_name'].'"},';
    }

which fixed the problem.

answered Nov 9, 2018 at 12:52

Hammad Khan's user avatar

Hammad KhanHammad Khan

16k16 gold badges111 silver badges134 bronze badges

The JavaScript exceptions «unexpected token» occur when a specific language construct
was expected, but something else was provided. This might be a simple typo.

Message

SyntaxError: expected expression, got "x"
SyntaxError: expected property name, got "x"
SyntaxError: expected target, got "x"
SyntaxError: expected rest argument name, got "x"
SyntaxError: expected closing parenthesis, got "x"
SyntaxError: expected '=>' after argument list, got "x"

Error type

What went wrong?

A specific language construct was expected, but something else was provided. This might
be a simple typo.

Examples

Expression expected

For example, when chaining expressions, trailing commas are not allowed.

for (let i = 0; i < 5,; ++i) {
  console.log(i);
}
// Uncaught SyntaxError: expected expression, got ';'

Correct would be omitting the comma or adding another expression:

for (let i = 0; i < 5; ++i) {
  console.log(i);
}

Not enough brackets

Sometimes, you leave out brackets around if statements:

function round(n, upperBound, lowerBound) {
  if (n > upperBound) || (n < lowerBound) { // Not enough brackets here!
    throw new Error(`Number ${n} is more than ${upperBound} or less than ${lowerBound}`);
  } else if (n < (upperBound + lowerBound) / 2) {
    return lowerBound;
  } else {
    return upperBound;
  }
} // SyntaxError: expected expression, got '||'

The brackets may look correct at first, but note how the || is outside the
brackets. Correct would be putting brackets around the ||:

function round(n, upperBound, lowerBound) {
  if ((n > upperBound) || (n < lowerBound)) {
    throw new Error(`Number ${n} is more than ${upperBound} or less than ${lowerBound}`);
  } else if (n < (upperBound + lowerBound) / 2) {
    return lowerBound;
  } else {
    return upperBound;
  }
}

See also

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
//forms
;(function($){
    $.fn.forms=function(o){
        return this.each(function(){
            var th=$(this)
                ,_=th.data('forms')||{
                    errorCl:'error',
                    emptyCl:'empty',
                    invalidCl:'invalid',
                    notRequiredCl:'notRequired',
                    successCl:'success',
                    successShow:'4000',
                    mailHandlerURL:'bat/MailHandler.php',
                    ownerEmail:'support@template-help.com',
                    stripHTML:true,
                    smtpMailServer:'localhost',
                    targets:'input,textarea',
                    controls:'a[data-type=reset],a[data-type=submit]',
                    validate:true,
                    rx:{
                        ".name":{rx:/^[a-zA-Z'][a-zA-Z-' ]+[a-zA-Z']?$/,target:'input'},
                        ".state":{rx:/^[a-zA-Z'][a-zA-Z-' ]+[a-zA-Z']?$/,target:'input'},
                        ".email":{rx:/^(("[w-s]+")|([w-]+(?:.[w-]+)*)|("[w-s]+")([w-]+(?:.[w-]+)*))(@((?:[w-]+.)*w[w-]{0,66}).([a-z]{2,6}(?:.[a-z]{2})?)$)|(@[?((25[0-5].|2[0-4][0-9].|1[0-9]{2}.|[0-9]{1,2}.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2}).){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})]?$)/i,target:'input'},
                        ".phone":{rx:/^+?(d[d-+() ]{5,}d$)/,target:'input'},
                        ".fax":{rx:/^+?(d[d-+() ]{5,}d$)/,target:'input'},
                        ".message":{rx:/.{20}/,target:'textarea'}
                    },
                    preFu:function(){
                        _.labels.each(function(){
                            var label=$(this),
                                inp=$(_.targets,this),
                                defVal=inp.val(),
                                trueVal=(function(){
                                            var tmp=inp.is('input')?(tmp=label.html().match(/value=['"](.+?)['"].+/),!!tmp&&!!tmp[1]&&tmp[1]):inp.html()
                                            return defVal==''?defVal:tmp
                                        })()
                            trueVal!=defVal
                                &&inp.val(defVal=trueVal||defVal)
                            label.data({defVal:defVal})                             
                            inp
                                .bind('focus',function(){
                                    inp.val()==defVal
                                        &&(inp.val(''),_.hideEmptyFu(label),label.removeClass(_.invalidCl))
                                })
                                .bind('blur',function(){
                                    _.validateFu(label)
                                    if(_.isEmpty(label))
                                        inp.val(defVal)
                                        ,_.hideErrorFu(label.removeClass(_.invalidCl))                                          
                                })
                                .bind('keyup',function(){
                                    label.hasClass(_.invalidCl)
                                        &&_.validateFu(label)
                                })
                            label.find('.'+_.errorCl+',.'+_.emptyCl).css({display:'block'}).hide()
                        })
                        _.success=$('.'+_.successCl,_.form).hide()
                    },
                    isRequired:function(el){                            
                        return !el.hasClass(_.notRequiredCl)
                    },
                    isValid:function(el){                           
                        var ret=true
                        $.each(_.rx,function(k,d){
                            if(el.is(k))
                                ret=d.rx.test(el.find(d.target).val())                                      
                        })
                        return ret                          
                    },
                    isEmpty:function(el){
                        var tmp
                        return (tmp=el.find(_.targets).val())==''||tmp==el.data('defVal')
                    },
                    validateFu:function(el){                            
                        el.each(function(){
                            var th=$(this)
                                ,req=_.isRequired(th)
                                ,empty=_.isEmpty(th)
                                ,valid=_.isValid(th)                                
                            
                            if(empty&&req)
                                _.showEmptyFu(th.addClass(_.invalidCl))
                            else
                                _.hideEmptyFu(th.removeClass(_.invalidCl))
                            
                            if(!empty)
                                if(valid)
                                    _.hideErrorFu(th.removeClass(_.invalidCl))
                                else
                                    _.showErrorFu(th.addClass(_.invalidCl))                             
                        })
                    },
                    getValFromLabel:function(label){
                        var val=$('input,textarea',label).val()
                            ,defVal=label.data('defVal')                                
                        return label.length?val==defVal?'nope':val:'nope'
                    }
                    ,submitFu:function(){
                        _.validateFu(_.labels)                          
                        if(!_.form.has('.'+_.invalidCl).length)
                            $.ajax({
                                type: "POST",
                                url:_.mailHandlerURL,
                                data:{
                                    name:_.getValFromLabel($('.name',_.form)),
                                    email:_.getValFromLabel($('.email',_.form)),
                                    phone:_.getValFromLabel($('.phone',_.form)),
                                    fax:_.getValFromLabel($('.fax',_.form)),
                                    state:_.getValFromLabel($('.state',_.form)),
                                    message:_.getValFromLabel($('.message',_.form)),
                                    owner_email:_.ownerEmail,
                                    stripHTML:_.stripHTML
                                },
                                success: function(){
                                    _.showFu()
                                }
                            })          
                    },
                    showFu:function(){
                        _.success.slideDown(function(){
                            setTimeout(function(){
                                _.success.slideUp()
                                _.form.trigger('reset')
                            },_.successShow)
                        })
                    },
                    controlsFu:function(){
                        $(_.controls,_.form).each(function(){
                            var th=$(this)
                            th
                                .bind('click',function(){
                                    _.form.trigger(th.data('type'))
                                    return false
                                })
                        })
                    },
                    showErrorFu:function(label){
                        label.find('.'+_.errorCl).slideDown()
                    },
                    hideErrorFu:function(label){
                        label.find('.'+_.errorCl).slideUp()
                    },
                    showEmptyFu:function(label){
                        label.find('.'+_.emptyCl).slideDown()
                        _.hideErrorFu(label)
                    },
                    hideEmptyFu:function(label){
                        label.find('.'+_.emptyCl).slideUp()
                    },
                    init:function(){
                        _.form=_.me                     
                        _.labels=$('label',_.form)
 
                        _.preFu()
                        
                        _.controlsFu()
                                                        
                        _.form
                            .bind('submit',function(){
                                if(_.validate)
                                    _.submitFu()
                                else
                                    _.form[0].submit()
                                return false
                            })
                            .bind('reset',function(){
                                _.labels.removeClass(_.invalidCl)                                   
                                _.labels.each(function(){
                                    var th=$(this)
                                    _.hideErrorFu(th)
                                    _.hideEmptyFu(th)
                                })
                            })
                        _.form.trigger('reset')
                    }
                }
            _.me||_.init(_.me=th.data({forms:_}))
            typeof o=='object'
                &&$.extend(_,o)
        })
    }
})(jQuery)

Have been dealing with the evil SyntaxError: expected expression, got '<' on Firefox in the last couple of days and had totally no idea what had been gone wrong. Everything worked fine and great on Chrome 55, Opera 41, Safari 10 but not FF 50+.

***Update: This error SyntaxError: expected expression, got '<' is most likely to happen when Service Workers is enabled and working fine on the browser. Since Service Worker in SPA will re-route basically anything that is not found to /index.html (according to default configuration) and so it does the same for .js. That’s why when app-indexeddb-mirror is looking for its .js files Service Worker couldn’t find it and just routed it to /index.html which then caused SyntaxError. In order to resolve that, we have to deliberately tell Service Worker to cache all the .js files within app-indexeddb-mirror like the following:

// sw-precache-config.js

module.exports = {
  staticFileGlobs: [
    '/index.html',
    '/manifest.json',
    '/bower_components/webcomponentsjs/webcomponents-lite.min.js',
    '/bower_components/app-storage/app-indexeddb-mirror/app-indexeddb-mirror-worker.js', // Ask sw to cache `app-indexeddb-mirror`'s .js files
    '/bower_components/app-storage/app-indexeddb-mirror/common-worker-scope.js' // Ask sw to cache `app-indexeddb-mirror`'s .js files
  ],
  navigateFallback: '/index.html',
  navigateFallbackWhitelist: [ /^/[^_]+/?/ ] // Firebase Auth's exception route.
};

***Additional step for Firefox: Head over to about:debugging#workers in Firefox and unregister all service workers. Clear your offline storage in FF. Do a page refresh and boom!!! Everything works as expected without throwing SyntaxError anymore. Hope this will help those struggling with the evil SyntaxError. 😄

app-indexeddb-mirror caches all JSONs from Firebase for offline use on all modern browsers.

FF50+ suffers from SyntaxError: expected expression, got '<'.

async function fastOrder($product_id) {
    let overlay = document.createElement("section");
$(overlay).addClass("fastorder-custf");
    $('body').prepend(overlay);
    let loading = document.createElement("div")
    overlay.prepend(loading)
    loading.innerHTML += "<i class='fa fa-spinner fa-pulse overlay__icon ' aria-hidden='true'></i>";
  //  $(".mfp-close").trigger('click');
    let response = await fetch('index.php?route=order/getForm', {
        method: 'POST',
        headers: {
           // 'Content-Type': 'application/json;charset=utf-8'
        },
        body: JSON.stringify($product_id),
    }).then(response => {
        return response.json();
    }).then(html => {
        $(loading).after(html);
    });
}

PHP

$data = json_decode(file_get_contents("php://input"), true);


  • Вопрос задан

    более года назад

  • 88 просмотров

Пригласить эксперта

Перепишите код свой, у вас jQuery в вперемешку с обычным кодом идет, обычно так не делают.

function fastOrder(product_id) {
	
	$('body').prepend(`<section class="fastorder-custf">
		<div class="ajax_result">
			<i class="fa fa-spinner fa-pulse overlay__icon" aria-hidden="true"></i>
		</div>
	</section>`);
	
	$('.mfp-close').trigger('click');
	
	$.ajax({
		url: 'index.php?route=order/getForm',
		type: 'POST',
		contentType: 'application/json; charset=UTF-8',
		data: product_id,
		dataType: 'html',
		success: function(response) {
			$('.ajax_result').html('Ответ сервера: ' + response);
		},
		error: function(xhr, status) {
			$('.ajax_result').html('При отправке запроса произошла ошибка, детали см. в консоли');
			console.log('При отправке запроса произошла ошибка:');
			console.dir(xhr);
		}
	});
	
}


  • Показать ещё
    Загружается…

30 янв. 2023, в 04:49

1500 руб./за проект

30 янв. 2023, в 04:49

1500 руб./за проект

30 янв. 2023, в 03:43

10000 руб./за проект

Минуточку внимания

The JavaScript exceptions «unexpected token» occur when a specific language construct was expected, but something else was provided. This might be a simple typo.

Message

SyntaxError: expected expression, got "x"
SyntaxError: expected property name, got "x"
SyntaxError: expected target, got "x"
SyntaxError: expected rest argument name, got "x"
SyntaxError: expected closing parenthesis, got "x"
SyntaxError: expected '=>' after argument list, got "x"

Error type

What went wrong?

A specific language construct was expected, but something else was provided. This might be a simple typo.

Examples

Expression expected

For example, when chaining expressions, trailing commas are not allowed.

for (let i = 0; i < 5,; ++i) {
  console.log(i);
}

Correct would be omitting the comma or adding another expression:

for (let i = 0; i < 5; ++i) {
  console.log(i);
}

Not enough brackets

Sometimes, you leave out brackets around if statements:

function round(n, upperBound, lowerBound) {
  if (n > upperBound) || (n < lowerBound) { 
    throw new Error(`Number ${n} is more than ${upperBound} or less than ${lowerBound}`);
  } else if (n < (upperBound + lowerBound) / 2) {
    return lowerBound;
  } else {
    return upperBound;
  }
} 

The brackets may look correct at first, but note how the || is outside the brackets. Correct would be putting brackets around the ||:

function round(n, upperBound, lowerBound) {
  if ((n > upperBound) || (n < lowerBound)) {
    throw new Error(`Number ${n} is more than ${upperBound} or less than ${lowerBound}`);
  } else if (n < (upperBound + lowerBound) / 2) {
    return lowerBound;
  } else {
    return upperBound;
  }
}

See also

  • SyntaxError


JavaScript

ReferenceError: assignment to undeclared variable «x»
The JavaScript strict mode-only exception «Assignment to undeclared variable» occurs when value has been assigned an ReferenceError in strict mode only.
ReferenceError: reference to undefined property «x»
The JavaScript warning «reference to undefined property» occurs when attempted access an object which doesn’t exist.
TypeError: «x» is (not) «y»
The JavaScript exception is (not) y» occurs when there was an unexpected type.
SyntaxError: function statement requires a name
The JavaScript exception «function statement requires name» occurs when there is in code that There is a function statement in code that requires name.

good.good

Сообщения: 80
Зарегистрирован: 2014.12.06, 16:25

SyntaxError: expected expression, got ‘<‘

Добрый день. Всех представительниц прекрасной половины с праздником!
Приступим к сути проблемы, в форме создания/редактирования я заметил что у меня не работает аякс валидация формы. Полез в модельку там все в порядке. Затем открыл консоль, а там вот такая вот ошибка:
SyntaxError: expected expression, got ‘<‘
<br />

Что за ошибка я так и не понял. Может кто сталкивался с такой проблемой.

good.good

Сообщения: 80
Зарегистрирован: 2014.12.06, 16:25

Re: SyntaxError: expected expression, got ‘<‘

Сообщение

good.good » 2015.03.08, 19:09

Экшен:

Код: Выделить всё

public function actionUpdate($id = null)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post())) {

            $model->file = UploadedFile::getInstance($model, 'image');
            if ($model->validate()) {
                switch ($model->file->type) {
                    case 'image/gif':
                        $temp = $model->id . '.gif';
                        $model->image = $temp;

                        break;
                    case 'image/jpeg':
                        $temp = $model->id . '.jpg';
                        $model->image = $temp;
                        break;
                    case 'image/png':
                        $temp = $model->id . '.png';
                        $model->image = $temp;
                        break;
                }
                $model->save();

                $model->file->saveAs(Yii::getAlias('@statics/web/offers/') . $temp);
                return $this->redirect(['view', 'id' => $model->id]);

            } else {
                return $this->render('update', [
                    'model' => $model,
                ]);
            }

        } else {

            return $this->render('update', [
                'model' => $model,
            ]);
        }
    } 

Вьюха (_form.php):

Код: Выделить всё

<?php $form = ActiveForm::begin([
    'options' => ['enctype' => 'multipart/form-data']
]); ?>

<?= $form->field($model, 'tarif_id')->dropDownList(Offer::getTarifsArray(), ['prompt' => '']) ?>
<?= $form->field($model, 'selector')->dropDownList(Offer::getSelectorArray(), ['prompt' => '']) ?>

<?= $form->field($model, 'kind')->dropDownList(Offer::getKindArray(), ['prompt' => '']) ?>

<?php
echo FileInput::widget([
    'name' => 'Offer[image]',
    'pluginOptions' => [
        'showCaption' => false,
        'showRemove' => false,
        'showUpload' => false,
        'browseClass' => 'btn btn-primary btn-block',
        'browseIcon' => '<i class="glyphicon glyphicon-camera"></i> ',
        'browseLabel' => 'Select Photo'
    ],
    'options' => ['accept' => 'image/*']
]);

?>
<?= $form->field($model, 'summary')->textarea(['rows' => 6]) ?>

<?= $form->field($model, 'type')->textInput() ?>

<?= $form->field($model, 'keywords')->textarea(['rows' => 6]) ?>

<?= $form->field($model, 'url')->textInput(['maxlength' => 255]) ?>


<?= $form->field($model, 'read_only_ad_kind')->dropDownList(Offer::getReadOnlyKindArray(), ['prompt' => '']) ?>

<?= $form->field($model, 'ad_active_kind')->dropDownList(Offer::getActiveKindArray(), ['prompt' => '']) ?>

<?= $form->field($model, 'url_type')->dropDownList(Offer::getUrl_typeArray(), ['prompt' => '']) ?>

<?= $form->field($model, 'wallet')->dropDownList(['test1' => 'test1', 'test2' => 'test2',], ['prompt' => '']) ?>

<div class="form-group">
    <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>

<?php ActiveForm::end(); ?>

Аватара пользователя

ElisDN

Сообщения: 5822
Зарегистрирован: 2012.10.07, 10:24
Контактная информация:

Re: SyntaxError: expected expression, got ‘<‘

Сообщение

ElisDN » 2015.03.08, 20:16

Добавьте саму валидацию:

Код: Выделить всё

public function actionUpdate($id = null)
{
    $model = $this->findModel($id);

    if ($model->load(Yii::$app->request->post())) {

        if (Yii::$app->request->isAjax) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }

    ...
} 

zelenin

Сообщения: 10596
Зарегистрирован: 2013.04.20, 11:30

Re: SyntaxError: expected expression, got ‘<‘

Сообщение

zelenin » 2015.03.08, 22:48

не пойму о чем речь вообще. Автор говорит, что у него не работает аякс-валидация, скидывает код, в котором не включена сама валидация в форме и в котором нет именно самой валиадции в экшне. Возникает вопрос: а с чего вы взяли что она вообще должна работать?

good.good

Сообщения: 80
Зарегистрирован: 2014.12.06, 16:25

Re: SyntaxError: expected expression, got ‘<‘

Сообщение

good.good » 2015.03.09, 07:45

zelenin писал(а):не пойму о чем речь вообще. Автор говорит, что у него не работает аякс-валидация, скидывает код, в котором не включена сама валидация в форме и в котором нет именно самой валиадции в экшне. Возникает вопрос: а с чего вы взяли что она вообще должна работать?

Начну с того, что данный код был сгенерен в gii и как бы оно работало и без всего этого. На сколько я понял по ответам, проблема заключается в том, что на запрос валидации возвращается html код вместо json.
Признаюсь я еще не полностью освоил фреймворк но все же, я написал для того чтобы получить ясность в этой неловкой ситуации.

zelenin

Сообщения: 10596
Зарегистрирован: 2013.04.20, 11:30

Re: SyntaxError: expected expression, got ‘<‘

Сообщение

zelenin » 2015.03.09, 10:48

good.good писал(а):

zelenin писал(а):не пойму о чем речь вообще. Автор говорит, что у него не работает аякс-валидация, скидывает код, в котором не включена сама валидация в форме и в котором нет именно самой валиадции в экшне. Возникает вопрос: а с чего вы взяли что она вообще должна работать?

Начну с того, что данный код был сгенерен в gii и как бы оно работало и без всего этого. На сколько я понял по ответам, проблема заключается в том, что на запрос валидации возвращается html код вместо json.
Признаюсь я еще не полностью освоил фреймворк но все же, я написал для того чтобы получить ясность в этой неловкой ситуации.

как оно могло работать, если оно не включено? у вас работала обычная клиентская валидация. А ошибка вообще не связана с темой.

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Ошибка esp мерседес что значит
  • Ошибка expected declaration specifiers or before string constant