Ajax parse error syntax error

The following is the HTML containing the call to the JavaScript function responsible for issuing the AJAX call. I understand that anchor tags are not supposed to have a value attribute but I'm usin...

The following is the HTML containing the call to the JavaScript function responsible for issuing the AJAX call. I understand that anchor tags are not supposed to have a value attribute but I’m using it with jQuery’s .attr(«value») method.

<a href="javascript:;" onclick="ajaxTest();" title="Execute AJAX" value="executeAJAX">Execute AJAX</a>

The following is the JavaScript function. If it is of any significance, it is contained in a .js file all by itself.

function ajaxTest() {
    $.ajax({
        type: "POST",
        url: "doAJAX",
        data: {"selectedScope": "5",
               "selectedView": "6"},
        dataType: "text",
        success: function(responseData) {
            $("#replaceThis").append(responseData);
        }
    });
}

Everytime the link is clicked, a «syntax error» message appears in Firefox’s web console. The JavaScript seems to be working as intended, however.

I just want to understand why I am getting the error.

I should add that I’m using jQuery 1.7.1.

I’ve performed a search and the only resolution I’ve found was that the keys for the «data» option should be enclosed in double quotes so I’ve implemented that but I’m still getting the syntax.

Thanks.

EDIT:

Looking at the Firebug console, the code above doesn’t trigger an
error like it did in Firefox’s console, however, I saw the following
in the XML part of the POST Request:

XML Parsing Error: syntax error Location:
moz-nullprincipal:{1d13df07-25fb-4058-9f82-ce1bef3c8949} Line Number
1, Column 1:
alskdfjlaksjdfjasdfl
^

The «alskdfjlaksjdfjasdfl» is simply what I’ve set up my servlet to return as I test this stuff out.

This is somewhat weird because it seems like jQuery is trying to parse
the response as XML although I’ve explicitly stated it to be text.

I can’t say for sure what the problem is. Could be some bad character, could be the spaces you have left at the beginning and at the end, no idea.

Anyway, you shouldn’t hardcode your JSON as strings as you have done. Instead the proper way to send JSON data to the server is to use a JSON serializer:

data: JSON.stringify({ name : "AA" }),

Now on the server also make sure that you have the proper view model expecting to receive this input:

public class UserViewModel
{
    public string Name { get; set; }
}

and the corresponding action:

[HttpPost]
public ActionResult SaveProduct(UserViewModel model)
{
    ...
}

Now there’s one more thing. You have specified dataType: 'json'. This means that you expect that the server will return a JSON result. The controller action must return JSON. If your controller action returns a view this could explain the error you are getting. It’s when jQuery attempts to parse the response from the server:

[HttpPost]
public ActionResult SaveProduct(UserViewModel model)
{
    ...
    return Json(new { Foo = "bar" });
}

This being said, in most cases, usually you don’t need to set the dataType property when making AJAX request to an ASP.NET MVC controller action. The reason for this is because when you return some specific ActionResult (such as a ViewResult or a JsonResult), the framework will automatically set the correct Content-Type response HTTP header. jQuery will then use this header to parse the response and feed it as parameter to the success callback already parsed.

I suspect that the problem you are having here is that your server didn’t return valid JSON. It either returned some ViewResult or a PartialViewResult, or you tried to manually craft some broken JSON in your controller action (which obviously you should never be doing but using the JsonResult instead).

One more thing that I just noticed:

async: false,

Please, avoid setting this attribute to false. If you set this attribute to false you are are freezing the client browser during the entire execution of the request. You could just make a normal request in this case. If you want to use AJAX, start thinking in terms of asynchronous events and callbacks.

Write bug, find bug

If you write WordPress plugins and make AJAX requests, you may be familiar the dreaded Javascript error: SyntaxError: JSON Parse Error: Unrecognized token '>'

SyntaxError: JSON Parse Error: Unrecognized token '<'

Why? Why!?!

What it means is that the response your code expected is screwed up because a plugin barfed PHP warnings into the admin-ajax.php ventilation system.

When WP_DEBUG is on, admin-ajax.php responses can include junk HTML output from PHP warnings, like:

<br />
<b>Notice</b>:  Undefined offset: 0 in
<b>/wp-content/plugins/im-gonna-break-ur-ajax.php</b> on line
<b>666</b><br />

The fix? Catch exceptions, then exceed expectations

The way to fix this is to wrap the jQuery.parseJSON() function in try/catch. That will make sure that the code doesn’t fully blow up.

try {
  jQuery.parseJSON( response );
} catch( exception ) {
  console.log( exception );
}

That will prevent your code from breaking, but it won’t make your code work.

The cause of the code breaking is the junk HTML at the beginning on the AJAX response. So, what we want to do is:

  1. Check for a valid JSON response
  2. If the JSON is invalid, strips all characters until finding a JSON-style opening of {".
  3. Check the newly stripped string to see if that is valid JSON
  4. If valid, return the JSON. If not, return an error message.

Here’s the code to achieve that:

Let me know what you think, and please fork the Gist if you have any improvements!

Странные вещи происходят.
Например в структуре сайт есть некий скрипт в котором есть строка

$output = curl_exec($ch);

так вот если убрать первую скобку, то сохраняется без проблем.
При ошибке, в консоле показывает то что в первом посте писал.

Такая же ситуация в шаблоне

Core_Page::instance()->execute();

если первую скобку убрать то сохраняется.
В этой ситуации в консоле показывает:

POST http://***САЙТ***/admin/template/index.php?hostcms[checked][1][13]=1 424 (Failed Dependency)
CodeMirror.fromTextArea.form.submit @ codemirror.js?345740267:5024
CodeMirror.fromTextArea.form.submit @ codemirror.js?345740267:5024
doSubmit @ jquery.form.js?345740267:349

Цитата:

Если в консоли открыть этот запрос сошибкой, что пишет в ответе от сервера?


Ошибка 424: заблокировано правилами безопасности
Если Вы владелец сайта, информацию о причинах возникновения и методах решения данной ошибки можно найти в разделе FAQ (

https://www.ukraine.com.ua/faq/error-424.html#!8

).

Попробую отключить ModSecurity как рекомендует хостинг…

  1. Home

  2. parsing — PHP parse/syntax errors; and how to solve them

670 votes

6 answers

Get the solution ↓↓↓

Everyone runs into syntax errors. Even experienced programmers make typos. For newcomers, it’s just part of the learning process. However, it’s often easy to interpret error messages such as:

PHP Parse error: syntax error, unexpected ‘{-code-1}’ in index.php on line 20

The unexpected symbol isn’t always the real culprit. But the line number gives a rough idea of where to start looking.

Always look at the code context. The syntax mistake often hides in the mentioned or in previous code lines. Compare your code against syntax examples from the manual.

While not every case matches the other. Yet there are some general steps to .
This references summarized the common pitfalls:

  • Unexpected T_STRING

  • Unexpected T_VARIABLE

  • Unexpected T_CONSTANT_ENCAPSED_STRING

  • Unexpected $end

  • Unexpected T_FUNCTION…

  • Unexpected

  • Unexpected

  • Unexpected T_IF

  • Unexpected T_LNUMBER

  • Unexpected ?

  • Unexpected continue (T_CONTINUE)

  • Unexpected ‘=’

  • Unexpected T_INLINE_HTML…

  • Unexpected T_PAAMAYIM_NEKUDOTAYIM…

  • Unexpected T_OBJECT_OPERATOR…

  • Unexpected T_DOUBLE_ARROW…

  • Unexpected T_SL…

  • Unexpected T_BOOLEAN_OR…

    Unexpected T_BOOLEAN_AND…

  • Unexpected T_IS_EQUAL

  • Unexpected T_NS_SEPARATOR…

  • Unexpected character in input: ‘

  • Unexpected ‘public’ (T_PUBLIC) …

  • Unexpected T_STATIC…

  • Unexpected T_CLASS…

  • Unexpected ‘use’ (T_USE)

  • Unexpected T_DNUMBER

  • Unexpected (comma)

  • Unpexected (period)

  • Unexpected (semicolon)

  • Unexpected (asterisk)

  • Unexpected (colon)

  • Unexpected ‘:’, expecting ‘,’ or ‘)’

  • Unexpected (call-time pass-by-reference)

  • Unexpected

Closely related references:

  • What does this error mean in PHP? (runtime errors)
    • Parse error: syntax error, unexpected T_XXX
    • Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE
    • Parse error: syntax error, unexpected T_VARIABLE
  • What does this symbol mean in PHP? (language tokens)
  • Those

And:

  • The PHP manual on php.net and its various language tokens
  • Or Wikipedia’s syntax introduction on PHP.
  • And lastly our of course.

While Stack Overflow is also welcoming rookie coders, it’s mostly targetted at professional programming questions.

  • Answering everyone’s coding mistakes and narrow typos is considered mostly off-topic.
  • So please take the time to follow the basic steps, before posting syntax fixing requests.
  • If you still have to, please show your own solving initiative, attempted fixes, and your thought process on what looks or might be wrong.

If your browser displays error messages such as «SyntaxError: illegal character», then it’s not actually php-related, but a javascript-syntax error.


Syntax errors raised on vendor code: Finally, consider that if the syntax error was not raised by editing your codebase, but after an external vendor package install or upgrade, it could be due to PHP version incompatibility, so check the vendor’s requirements against your platform setup.

2021-12-15

Write your answer


850

votes

Answer

Solution:

What are the syntax errors?

PHP belongs to the C-style and imperative programming languages. It has rigid grammar rules, which it cannot recover from when encountering misplaced symbols or ident{-code-18}-code-11}iers. It can{-code-18}-code-8}t guess your coding intentions.

{-code-18}-code-7}Function

Most important tips

There are a few basic precautions you can always take:

  • Use proper code indentation, or adopt any lofty coding style.
    Readability prevents irregularities.

  • Use an with syntax highlighting.
    Which also help with parentheses/bracket balancing.

    {-code-18}-code-7}Expected:

  • Read the language reference and examples in the manual.
    Twice, to become somewhat proficient.

How to interpret parser errors

A typical syntax error message reads:

Parse error: syntax error, unexpected {-code-18}-code-4{-code-18}-code-5}-code-2{-code-18}-code-5}, expecting {-code-18}-code-8}{-code-18}-code-4{-code-18}-code-5}-code-1{-code-18}-code-5}{-code-18}-code-8} in file.php on line 217

Which lists the possible location of a syntax mistake. See the mentioned file name and line number.

A moniker such as{-code-18}-code-4{-code-18}-code-5}-code-2{-code-18}-code-5} explains which symbol the parser/tokenizer couldn{-code-18}-code-8}t process finally. This isn{-code-18}-code-8}t necessarily the cause of the syntax mistake, however.

It{-code-18}-code-8}s important to look into previous code lines as well. Often syntax errors are just mishaps that happened earlier. The error line number is just where the parser conclusively gave up to process it all.

Solving syntax errors

There are many approaches to narrow down and fix syntax hiccups.

  • Open the mentioned source file. Look at the mentioned code line.

    • For runaway strings and misplaced operators, this is usually where you find the culprit.

    • Read the line left to right and imagine what each symbol does.

  • More regularly you need to look at preceding lines as well.

    • In particular, missing{-code-18}-code-4{-code-18}-code-5}-code-1{-code-18}-code-5} semicolons are missing at the previous line ends/statement. (At least from the stylistic viewpoint. )

    • If{-code-18}-code-4{-code-18}-code-5} code blocks{-code-18}-code-5} are incorrectly closed or nested, you may need to investigate even further up the source code. Use proper code indentation to simpl{-code-18}-code-11}y that.

  • Look at the syntax colorization!

    • Strings and variables and constants should all have d{-code-18}-code-11}ferent colors.

    • Operators{-code-18}-code-6} should be tinted distinct as well. Else they might be in the wrong context.

    • If you see string colorization extend too far or too short, then you have found an unescaped or missing closing{-code-18}-code-7} or{-code-18}-code-8} string marker.

    • Having two same-colored punctuation characters next to each other can also mean trouble. Usually, operators are lone {-code-18}-code-11} it{-code-18}-code-8}s not{-code-18}-code-9},{-code-18}-code-10}, or parentheses following an operator. Two strings/ident{-code-18}-code-11}iers directly following each other are incorrect in most contexts.

  • Whitespace is your friend.
    Follow any coding style.

  • Break up long lines temporarily.

    • You can freely add newlines between operators or constants and strings. The parser will then concretize the line number for parsing errors. Instead of looking at the very lengthy code, you can isolate the missing or misplaced syntax symbol.

    • Split up complex{-code-18}-code-11} statements into distinct or nested{-code-18}-code-11} conditions.

    • Instead of lengthy math formulas or logic chains, use temporary variables to simpl{-code-18}-code-11}y the code. (More readable = fewer errors.)

    • Add newlines between:

      1. The code you can easily ident{-code-18}-code-11}y as correct,
      2. The parts you{-code-18}-code-8}re unsure about,
      3. And the lines which the parser complains about.

      Partitioning up long code blocks really helps to locate the origin of syntax errors.

  • Comment out offending code.

    • If you can{-code-18}-code-8}t isolate the problem source, start to comment out (and thus temporarily remove) blocks of code.

    • As soon as you got rid of the parsing error, you have found the problem source. Look more closely there.

    • Sometimes you want to temporarily remove complete function/method blocks. (In case of unmatched curly braces and wrongly indented code.)

    • When you can{-code-18}-code-8}t resolve the syntax issue, try to rewrite the commented out sections from scratch.

  • As a newcomer, avoid some of the confusing syntax constructs.

    • The ternary{-code-18}-code-13} condition operator can compact code and is useful indeed. But it doesn{-code-18}-code-8}t aid readability in all cases. Prefer plain{-code-18}-code-11} statements while unversed.

    • PHP{-code-18}-code-8}s alternative syntax ({-code-18}-code-11}:/else{-code-18}-code-11}:/end{-code-18}-code-11}{-code-18}-code-4{-code-18}-code-5}-code-1{-code-18}-code-5}) is common for templates, but arguably less easy to follow than normal{-code-18}-code-4{-code-18}-code-5} code{-code-18}-code-5} blocks.

  • The most prevalent newcomer mistakes are:

    • Missing semicolons{-code-18}-code-4{-code-18}-code-5}-code-1{-code-18}-code-5} for terminating statements/lines.

    • Mismatched string quotes for{-code-18}-code-7} or{-code-18}-code-8} and unescaped quotes within.

    • Forgotten operators, in particular for the string. concatenation.

    • Unbalanced( parentheses). Count them in the reported line. Are there an equal number of them?

  • Don{-code-18}-code-8}t forget that solving one syntax problem can uncover the next.

    • If you make one issue go away, but other crops up in some code below, you{-code-18}-code-8}re mostly on the right path.

    • If after editing a new syntax error crops up in the same line, then your attempted change was possibly a failure. (Not always though.)

  • Restore a backup of previously working code, {-code-18}-code-11} you can{-code-18}-code-8}t fix it.

    • Adopt a source code versioning system. You can always view ad{-code-18}-code-11}f of the broken and last working version. Which might be enlightening as to what the syntax problem is.
  • Invisible stray Unicode characters: In some cases, you need to use a hexeditor or d{-code-18}-code-11}ferent editor/viewer on your source. Some problems cannot be found just from looking at your code.

    • Try as the first measure to find non-ASCII symbols.

    • In particular BOMs, zero-width spaces, or non-breaking spaces, and smart quotes regularly can find their way into the source code.

  • Take care of which type of linebreaks are saved in files.

    • PHP just honors n newlines, not r carriage returns.

    • Which is occasionally an issue for MacOS users (even on OS {-code-18}-code-4{-code-18}-code-5}-code-1{-code-18}-code-5} X for misconfigured editors).

    • It often only surfaces as an issue when single-line// or# comments are used. Multiline/*...*/ comments do seldom disturb the parser when linebreaks get ignored.

  • If your syntax error does not transmit over the web:
    It happens that you have a syntax error on your machine. But posting the very same file online does not exhibit it anymore. Which can only mean one of two things:

    • You are looking at the wrong file!

    • Or your code contained invisible stray Unicode (see above).
      You can easily find out: Just copy your code back from the web form into your text editor.

  • Check your PHP version. Not all syntax constructs are available on every server.

    • php -v for the command line interpreter

    • <{-code-18}-code-4{-code-18}-code-5}-code-1{-code-18}-code-5}?php phpinfo(){-code-18}-code-4{-code-18}-code-5}-code-1{-code-18}-code-5} for the one invoked through the webserver.

    Those aren{-code-18}-code-8}t necessarily the same. In particular when working with frameworks, you will them to match up.

  • Don{-code-18}-code-8}t use PHP{-code-18}-code-8}s reserved keywords as ident{-code-18}-code-11}iers for functions/methods, classes or constants.

  • Trial-and-error is your last resort.

If all else fails, you can always google your error message. Syntax symbols aren{-code-18}-code-8}t as easy to search for (Stack Overflow itself is indexed by SymbolHound though). Therefore it may take looking through a few more pages before you find something relevant.

Further guides:

  • PHP Debugging Basics by David Sklar
  • Fixing PHP Errors by Jason McCreary
  • PHP Errors – 10 Common Mistakes by Mario Lurig
  • Common PHP Errors and Solutions
  • How to Troubleshoot and Fix your WordPress Website
  • A Guide To PHP Error Messages For Designers — Smashing Magazine

White screen of death

If your website is just blank, then typically a syntax error is the cause.
Enable their display with:

  • error_reporting = E_ALL
  • display_errors = 1

In your generally, or via for mod_php,
or even with FastCGI setups.

Enabling it within the broken script is too late because PHP can{-code-18}-code-8}t even interpret/run the first line. A quick workaround is crafting a wrapper script, saytest.php:

<{-code-18}-code-4{-code-18}-code-5}-code-1{-code-18}-code-5}?php
   error_reporting(E_ALL){-code-18}-code-4{-code-18}-code-5}-code-1{-code-18}-code-5}
   ini_set({-code-18}-code-7}display_errors{-code-18}-code-7}, 1){-code-18}-code-4{-code-18}-code-5}-code-1{-code-18}-code-5}
   include({-code-18}-code-7}./broken-script.php{-code-18}-code-7}){-code-18}-code-4{-code-18}-code-5}-code-1{-code-18}-code-5}

Then invoke the failing code by accessing this wrapper script.

It also helps to enable PHP{-code-18}-code-8}serror_log and look into your webserver{-code-18}-code-8}s when a script crashes with HTTP 500 responses.


334

votes

Answer

Solution:

I think this topic is totally overdiscussed/overcomplicated. Using an IDE is THE way to go to completely avoid any syntax errors. I would even say that working without an IDE is kind of unprofessional. Why? Because modern IDEs check your syntax after every character you type. When you code and your entire line turns red, and a big warning notice shows you the exact type and the exact position of the syntax error, then there’s absolutely no need to search for another solution.

Using a syntax-checking IDE means:

You’ll (effectively) never run into syntax errors again, simply because you see them right as you type. Seriously.

Excellent IDEs with syntax check (all of them are available for Linux, Windows and Mac):

  1. NetBeans [free]
  2. PHPStorm [$199 USD]
  3. Eclipse with PHP Plugin [free]
  4. Sublime [$80 USD] (mainly a text editor, but expandable with plugins, like PHP Syntax Parser)


912

votes

Answer

Solution:

Unexpected{-code-11}-code-1}

These days, the unexpected{-code-11}-code-1} array bracket is commonly seen on outdated PHP versions. The short array syntax is available since PHP >= 5.4. Older installations only support{-code-11}-code-3}.

{-code-17}php53 = array{-code-12}1, 2, 3{-code-23};
{-code-17}php54 = {-code-11}-code-1}1, 2, 3{-code-21};
         ⇑

Array function result dereferencing is likewise not available for older PHP versions:

{-code-17}result = get_whatever{-code-12}{-code-23}{-code-11}-code-1}"key"{-code-21};
                      ⇑

Reference — What does this error mean in PHP? — «Syntax error, unexpected shows the most common and practical workarounds.

Though, you’re always better off just upgrading your PHP installation. For shared webhosting plans, first research if e.g.{-code-11}-code-7} can be used to enable a newer runtime.

See also:

  • PHP syntax for dereferencing function result в†’ possible as of PHP 5.4
  • PHP syntax error, unexpected ‘{-code-11}-code-1}’
  • Shorthand for arrays: is there a literal syntax like {-code-11}} or {-code-11}-code-1}{-code-21}?
  • PHP 5.3.10 vs PHP 5.5.3 syntax error unexpected ‘{-code-11}-code-1}’
  • PHP Difference between {-code-11}-code-3} and {-code-11}-code-1}{-code-21}
  • PHP Array Syntax Parse Error Left Square Bracket «{-code-11}-code-1}»

BTW, there are also preprocessors and PHP 5.4 syntax down-converters if you’re really clingy with older + slower PHP versions.

Other causes for Unexpected{-code-11}-code-1} syntax errors

If it’s not the PHP version mismatch, then it’s oftentimes a plain typo or newcomer syntax mistake:

  • You can’t use array property declarations/expressions in classes, not even in PHP 7.

    protected {-code-17}var{-code-11}-code-1}"x"{-code-21} = "Nope";
                  ⇑
    
  • Confusing{-code-11}-code-1} with opening curly braces{-code-11} or parentheses{-code-12} is a common oversight.

    foreach {-code-11}-code-1}{-code-17}a as {-code-17}b{-code-23}
            ⇑
    

    Or even:

    function foobar{-code-11}-code-1}{-code-17}a, {-code-17}b, {-code-17}c{-code-21} {-code-11}
                   ⇑
    
  • Or trying to dereference {-code-16}ants {-code-12}before PHP 5.6{-code-23} as arrays:

    {-code-17}var = {-code-16}{-code-11}-code-1}123{-code-21};
           ⇑
    

    At least PHP interprets that{-code-16} as a {-code-16}ant name.

    If you meant to access an array variable {-code-12}which is the typical cause here{-code-23}, then add the leading{-code-17} sigil — so it becomes a{-code-17}varname.

  • You are trying to use the{-code-19} keyword on a member of an associative array. This is not valid syntax:

    {-code-19} {-code-17}var{-code-11}-code-1}'key'{-code-21};
    

Unexpected{-code-21} closing square bracket

This is somewhat rarer, but there are also syntax accidents with the terminating array{-code-21} bracket.

  • Again mismatches with{-code-23} parentheses or} curly braces are common:

    function foobar{-code-12}{-code-17}a, {-code-17}b, {-code-17}c{-code-21} {-code-11}
                              ⇑
    
  • Or trying to end an array where there isn’t one:

    {-code-17}var = 2{-code-21};
    

    Which often occurs in multi-line and nested array declarations.

    {-code-17}array = {-code-11}-code-1}1,{-code-11}-code-1}2,3{-code-21},4,{-code-11}-code-1}5,6{-code-11}-code-1}7,{-code-11}-code-1}8{-code-21},{-code-11}-code-1}9,10{-code-21}{-code-21},11{-code-21},12{-code-21}{-code-21},15{-code-21};
                                                 ⇑
    

    If so, use your IDE for bracket matching to find any premature{-code-21} array closure. At the very least use more spacing and newlines to narrow it down.


729

votes

Answer

Solution:

Unexpected {-code-1{-code-16}

An «{-code-13{-code-16}unexpected{-code-1{-code-16}«{-code-13{-code-16} means that there’s a literal{-code-2{-code-16} name{-code-8{-code-16} which doesn’t fit into the current expression/statement structure{-code-4{-code-16}

purposefully abstract/inexact operator+{-code-2{-code-16} diagram

  1. Missing semicolon

    It most commonly indicates a missing semicolon in the previous line{-code-4{-code-16} Variable assignments following a statement are a good indicator where to look:

            {-code-3{-code-16}
    
  2. String concatenation

    A frequent mishap are string concatenations with {-code-14{-code-16}gotten{-code-4{-code-16} operator:

                                    {-code-5{-code-16}
    

    Btw{-code-8{-code-16} you should prefer string interpolation {-code-23}basic variables in double quotes) whenever that helps readability{-code-4{-code-16} Which avoids these syntax issues{-code-4{-code-16}

    String interpolation is a scripting language core feature{-code-4{-code-16} No shame in utilizing it{-code-4{-code-16} Ignore any micro-optimization advise about variable{-code-4{-code-16} concatenation being faster{-code-4{-code-16} It’s not{-code-4{-code-16}

  3. Missing expression operators

    Of course the same issue can arise in other expressions{-code-8{-code-16} {-code-14{-code-16} instance arithmetic operations:

                {-code-7{-code-16}
    

    PHP can’t guess here {-code-19} the variable should have been added{-code-8{-code-16} subtracted or compared etc{-code-4{-code-16}

  4. Lists

    Same {-code-14{-code-16} syntax {-code-11{-code-16}s{-code-8{-code-16} like in array populations{-code-8{-code-16} where the parser also indicates an expected comma{-code-8{-code-16} {-code-14{-code-16} example:

                                           ⇓
     $var = array{-code-23}"{-code-13{-code-16}1"{-code-13{-code-16} =>{-code-13{-code-16} $val{-code-8{-code-16} $val2{-code-8{-code-16} $val3 $val4){-code-13{-code-16}
    

    Or functions parameter {-code-11{-code-16}s:

                                     ⇓
     function myfunc{-code-23}$param1{-code-8{-code-16} $param2 $param3{-code-8{-code-16} $param4)
    

    Equivalently do you see this with{-code-11{-code-16} or{-code-12{-code-16} statements{-code-8{-code-16} or when lacking a{-code-13{-code-16} semicolon in a{-code-14{-code-16} loop{-code-4{-code-16}

  5. Class declarations

    This parser error also occurs in class declarations{-code-4{-code-16} You can only assign static constants{-code-8{-code-16} not expressions{-code-4{-code-16} Thus the parser complains about variables as assigned data:

     class xyz {      ⇓
         var $value = $_GET["{-code-13{-code-16}input"{-code-13{-code-16}]{-code-13{-code-16}
    

    Unmatched{-code-16} closing curly braces can in particular lead here{-code-4{-code-16} If a method is terminated too early {-code-23}use proper indentation!){-code-8{-code-16} then a stray variable is commonly misplaced into the class declaration body{-code-4{-code-16}

  6. Variables after ident{-code-19}iers

    You can also never have a variable follow an ident{-code-19}ier directly:

                  ⇓
     $this->{-code-13{-code-16}myFunc$VAR{-code-23}){-code-13{-code-16}
    

    Btw{-code-8{-code-16} this is a common example where the intention was to use variable variables perhaps{-code-4{-code-16} In this case a variable property lookup with$this->{-code-13{-code-16}{"{-code-13{-code-16}myFunc$VAR"{-code-13{-code-16}{-code-16}{-code-23}){-code-13{-code-16} {-code-14{-code-16} example{-code-4{-code-16}

    Take in mind that using variable variables should be the exception{-code-4{-code-16} Newcomers often try to use them too casually{-code-8{-code-16} even when arrays would be simpler and more appropriate{-code-4{-code-16}

  7. Missing parentheses after language constructs

    Hasty typing may lead to {-code-14{-code-16}gotten opening or closing parenthesis
    {-code-14{-code-16}{-code-19} and{-code-14{-code-16} and{-code-14{-code-16}each statements:

            ⇓
     {-code-14{-code-16}each $array as $key) {
    

    Solution: add the missing opening{-code-23} between statement and variable{-code-4{-code-16}

                           ⇓
     {-code-19} {-code-23}$var = pdo_query{-code-23}$sql) {
          $result = …
    

    The curly{ brace does not open the code block{-code-8{-code-16} without closing the{-code-19} expression with the) closing parenthesis first{-code-4{-code-16}

  8. Else does not expect conditions

         ⇓
    else {-code-23}$var >{-code-13{-code-16}= 0)
    

    Solution: Remove the conditions fromelse or use {-code-4{-code-16}

  9. Need brackets {-code-14{-code-16} closure

         ⇓
    function{-code-23}) use $var {{-code-16}
    

    Solution: Add brackets around$var{-code-4{-code-16}

  10. Invisible whitespace

    As mentioned in the reference answer on «{-code-13{-code-16}Invisible stray Unicode»{-code-13{-code-16} {-code-23}such as a non-breaking space){-code-8{-code-16} you might also see this error {-code-14{-code-16} unsuspecting code like:

    <{-code-13{-code-16}?php
                              в‡ђ
    $var = new PDO{-code-23}{-code-4{-code-16}{-code-4{-code-16}{-code-4{-code-16}){-code-13{-code-16}
    

    It’s rather prevalent in the start of files and {-code-14{-code-16} copy-and-pasted code{-code-4{-code-16} Check with a hexeditor{-code-8{-code-16} {-code-19} your code does not visually appear to contain a syntax issue{-code-4{-code-16}

See also

  • Search: unexpected {-code-1{-code-16}


365

votes

Answer

Solution:

Unexpected T_CONSTANT_ENCAPSED_STRING
Unexpected T_ENCAPSED_AND_WHITESPACE

The unwieldy namesT_CONSTANT_ENCAPSED_STRING andT_ENCAPSED_AND_WHITESPACE refer to quoted "string" literals.

They’re used in different contexts, but the syntax issue are quite similar. T_ENCAPSED… warnings occur in double quoted string context, while T_CONSTANT… strings are often astray in plain PHP expressions or statements.

  1. Incorrect variable interpolation

    And it comes up most frequently for incorrect PHP variable interpolation:

                              ⇓     ⇓
    echo "Here comes a $wrong['array'] access";
    

    Quoting arrays keys is a must in PHP context. But in double quoted strings (or HEREDOCs) this is a mistake. The parser complains about the contained single quoted'string', because it usually expects a literal identifier / key there.

    More precisely it’s valid to use PHP2-style simple syntax within double quotes for array references:

    echo "This is only $valid[here] ...";
    

    Nested arrays or deeper object references however require the complex curly string expression syntax:

    echo "Use {$array['as_usual']} with curly syntax.";
    

    If unsure, this is commonly safer to use. It’s often even considered more readable. And better IDEs actually use distinct syntax colorization for that.

  2. Missing concatenation

    If a string follows an expression, but lacks a concatenation or other operator, then you’ll see PHP complain about the string literal:

                           ⇓
    print "Hello " . WORLD  " !";
    

    While it’s obvious to you and me, PHP just can’t guess that the string was meant to be appended there.

  3. Confusing string quote enclosures

    The same syntax error occurs when confounding string delimiters. A string started by a single' or double" quote also ends with the same.

                    ⇓
    print "<a href="' . $link . '">click here</a>";
          вЊћвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЊџвЊћвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЊџвЊћвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЊџ
    

    That example started with double quotes. But double quotes were also destined for the HTML attributes. The intended concatenation operator within however became interpreted as part of a second string in single quotes.

    Tip: Set your editor/IDE to use slightly distinct colorization for single and double quoted strings. (It also helps with application logic to prefer e.g. double quoted strings for textual output, and single quoted strings only for constant-like values.)

    This is a good example where you shouldn’t break out of double quotes in the first place. Instead just use proper for the HTML attributesВґ quotes:

    print "<a href="{$link}">click here</a>";
    

    While this can also lead to syntax confusion, all better IDEs/editors again help by colorizing the escaped quotes differently.

  4. Missing opening quote

    Equivalently are forgotten opening a recipe for parser errors:

                   ⇓
     make_url(login', 'open');
    

    Here the', ' would become a string literal after a bareword, when obviouslylogin was meant to be a string parameter.

  5. Array lists

    If you miss a, comma in an array creation block, the parser will see two consecutive strings:

    array(               ⇓
         "key" => "value"
         "next" => "....",
    );
    

    Note that the last line may always contain an extra comma, but overlooking one in between is unforgivable. Which is hard to discover without syntax highlighting.

  6. Function parameter lists

    The same thing for function calls:

                             ⇓
    myfunc(123, "text", "and"  "more")
    
  7. Runaway strings

    A common variation are quite simply forgotten string terminators:

                                    ⇓
    mysql_evil("SELECT * FROM stuffs);
    print "'ok'";
          ⇑
    

    Here PHP complains about two string literals directly following each other. But the real cause is the unclosed previous string of course.

  8. HEREDOC indentation

    Prior PHP 7.3, the heredoc string end delimiter can’t be prefixed with spaces:

    print <<< HTML
        <link..>
        HTML;
       ⇑
    

    Solution: upgrade PHP or find a better hoster.

See also

  • Interpolation (double quoted string) of Associative Arrays in PHP
  • PHP — syntax error, unexpected T_CONSTANT_ENCAPSED_STRING
  • Syntax error, unexpected T_CONSTANT_ENCAPSED_STRING in PHP
  • Unexpected T_CONSTANT_ENCAPSED_STRING error in SQL Query


275

votes

Answer

Solution:

Unexpected

is a bit of a misnomer. It does not refer to a quoted{-code-2}. It means a raw identifier was encountered. This can range from{-code-3} words to leftover{-code-4} or function names, forgotten unquoted strings, or any plain text.

  1. Misquoted strings

    This syntax error is most common for misquoted string values however. Any unescaped and stray{-code-5} or{-code-6} quote will form an invalid expression:

                   ⇓                  ⇓
     {-code-11} {-code-5}<{-code-29}a href={-code-5}http://example.com{-code-5}>{-code-29}click here<{-code-29}/a>{-code-29}{-code-5}{-code-29}
    

    Syntax highlighting will make such mistakes super obvious. It{-code-6}s important to remember to use backslashes for escaping{-code-33}{-code-5} double quotes, or{-code-33}{-code-6} single quotes — depending on which was used as string enclosure.

    • For convenience you should prefer outer single quotes when outputting plain HTML with double quotes within.
    • Use double quoted strings if you want to interpolate variables, but then watch out for escaping literal{-code-5} double quotes.
    • For lengthier output, prefer multiple{-code-11}/{-code-12} lines instead of escaping in and out. Better yet consider a HEREDOC section.

    Another example is using PHP entry inside HTML code generated with PHP:

    {-code-14} = {-code-6}<{-code-29}div>{-code-29}some text with {-code-25}php {-code-11} {-code-6}some php entry{-code-6} ?>{-code-29}<{-code-29}/div>{-code-29}{-code-6}
    

    This happens if{-code-14} is large with many lines and developer does not see the whole PHP variable value and focus on the piece of code forgetting about its source. Example is here

    See also What is the difference between single-quoted and double-quoted strings in PHP?.

  2. Unclosed strings

    If you miss a closing then a syntax error typically materializes later. An unterminated string will often consume a bit of code until the next intended string value:

                                                           ⇓
    {-code-11} {-code-5}Some text{-code-5}, {-code-32}a_variable, {-code-5}and some runaway string {-code-29}
    success({-code-5}finished{-code-5}){-code-29}
             в‡Ї
    

    It{-code-6}s not just literals which the parser may protest then. Another frequent variation is an for unquoted literal HTML.

  3. Non-programming string quotes

    If you copy and paste code from a blog or website, you sometimes end up with invalid code. Typographic quotes aren{-code-6}t what PHP expects:

    {-code-14} = ’Something something..’ + {-code-20} ain{-code-6}t quotes”{-code-29}
    

    Typographic/smart quotes are Unicode symbols. PHP treats them as part of adjoining alphanumeric text. For example{-code-20} is interpreted as a constant identifier. But any following text literal is then seen as a {-code-3}word/ by the parser.

  4. The missing semicolon{-code-29} again

    If you have an unterminated expression in previous lines, then any following statement or language construct gets seen as raw identifier:

           {-code-21}
    

    PHP just can{-code-6}t know if you meant to run two functions after another, or if you meant to multiply their results, add them, compare them, or only run one{-code-22} or the other.

  5. Short open tags and{-code-23} headers in PHP scripts

    This is rather uncommon. But if short_open_tags are enabled, then you can{-code-6}t begin your PHP scripts with an XML declaration:

          ⇓
    {-code-23} {-code-27}={-code-5}1.0{-code-5}?>{-code-29}
    


Share solution ↓

Additional Information:

Date the issue was resolved:

2021-12-15

Link To Source

Link To Answer
People are also looking for solutions of the problem: the metadata storage is not up to date, please run the sync-metadata-storage command to fix this issue.

Didn’t find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.


Similar questions

Find the answer in similar questions on our website.

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.


About the technologies asked in this question

PHP

PHP (from the English Hypertext Preprocessor — hypertext preprocessor) is a scripting programming language for developing web applications. Supported by most hosting providers, it is one of the most popular tools for creating dynamic websites.
The PHP scripting language has gained wide popularity due to its processing speed, simplicity, cross-platform, functionality and distribution of source codes under its own license.
https://www.php.net/

Laravel

Laravel is a free open source PHP framework that came out in 2011. Since then, it has been able to become the framework of choice for web developers. One of the main reasons for this is that Laravel makes it easier, faster, and safer to develop complex web applications than any other framework.
https://laravel.com/

JavaScript

JavaScript is a multi-paradigm language that supports event-driven, functional, and mandatory (including object-oriented and prototype-based) programming types. Originally JavaScript was only used on the client side. JavaScript is now still used as a server-side programming language. To summarize, we can say that JavaScript is the language of the Internet.
https://www.javascript.com/

MySQL

DBMS is a database management system. It is designed to change, search, add and delete information in the database. There are many DBMSs designed for similar purposes with different features. One of the most popular is MySQL.
It is a software tool designed to work with relational SQL databases. It is easy to learn even for site owners who are not professional programmers or administrators. MySQL DBMS also allows you to export and import data, which is convenient when moving large amounts of information.
https://www.mysql.com/

HTML

HTML (English «hyper text markup language» — hypertext markup language) is a special markup language that is used to create sites on the Internet.
Browsers understand html perfectly and can interpret it in an understandable way. In general, any page on the site is html-code, which the browser translates into a user-friendly form. By the way, the code of any page is available to everyone.
https://www.w3.org/html/



Welcome to programmierfrage.com

programmierfrage.com is a question and answer site for professional web developers, programming enthusiasts and website builders. Site created and operated by the community. Together with you, we create a free library of detailed answers to any question on programming, web development, website creation and website administration.

Get answers to specific questions

Ask about the real problem you are facing. Describe in detail what you are doing and what you want to achieve.

Help Others Solve Their Issues

Our goal is to create a strong community in which everyone will support each other. If you find a question and know the answer to it, help others with your knowledge.

Технология AJAX — это способ обмена данными клиента (компьютера пользователя) с сервером для обновления частей веб-страницы без перезагрузки всей страницы. Для выполнения  AJAX-запросов  в нативном JavaScript существует специальный объект XMLHTTPRequest. Библиотека jQuery предоставляет для работы с AJAX набор методов, которые имеет смысл использовать в различных ситуациях в зависимости от типа запроса и вида передаваемых данных.

Виды методов jQuery для выполнения AJAX-запросов

В следующей таблице перечислены все AJAX-методы. доступные в библиотеке jQuery, причем, если в первой колонке вы видите ссылку на метод, то на сайте есть статья, которая ему посвящена:

Метод Описание
$.ajax() Выполняет асинхронный AJAX-запрос
$.ajaxPrefilter() Обработка пользовательских Ajax -параметров или изменение существующих параметров перед отправкой каждого запроса и до того, как они будут обработаны методом $.ajax()
$.ajaxSetup() Устанавливает значения по умолчанию для будущих AJAX-запросов
$.ajaxTransport() Создает объект, который обрабатывает фактическую передачу данных Ajax
$.get() Загружает данные с сервера с помощью AJAX-запроса методом GET
$.getJSON() Загружает данные в кодировке JSON с сервера с помощью HTTP-запроса GET.
$.parseJSON() Принимает правильно сформированную строку JSON и возвращает полученное значение JavaScript. Не рекомендуется в версии 3.0, используйте вместо этого метод JSON.parse().
$.getScript() Загружает (и выполняет) JavaScript с сервера с помощью AJAX и GET-запроса
$.param() Создает сериализованное представление массива или объекта (может использоваться как строка запроса URL для запросов AJAX)
$.post() Загружает данные с сервера с помощью HTTP POST-запроса
ajaxComplete() Задает функцию, запускаемую после завершения AJAX-запроса
ajaxError() Задает функцию, запускаемую, когда AJAX-запрос завершается с ошибкой
ajaxSend() Задает функцию, запускаемую  перед отправкой AJAX-запроса
ajaxStart() Задает функцию, запускаемую  при первом AJAX-запросе
ajaxStop() Определяет функцию, запускаемую, когда все запросы AJAX завершены
ajaxSuccess() Задает функцию, запускаемую при успешном завершении AJAX-запроса
load() Загружает данные с сервера и помещает возвращенные данные в выбранный элемент
serialize() Кодирует набор элементов формы как строку для отправки данных в виде пар «имя1=значение1&имя2=значение2»
serializeArray() Кодирует набор элементов формы как массив имен и значений

Каждый из этих методов может употребляться в зависимости от ситуации, но, пожалуй, самым универсальным из них является метод $.ajax, практическое использование которого мы рассмотрим в этой статье.

Метод  $.ajax

Прежде,чем мы будем применять метод  $.ajax в JavaScript, давайте определимся с практической задачей. Она достаточно простая — пользователь должен заполнить простую форму, а после этого мы отправим ее на сервер и получим все заполненные данные в виде таблицы. В форме нужно будет указать имя (логин), email и набор знаний в виде отмеченных флажков (чекбоксов).

HTML-разметка

Давайте посмотрим на разметку формы в html-файле:

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

<form action=«php/test-ajax.php» class=«small-form» id=«testForm»>

    <p><label for=«username»>Ваше имя</label>

       <input type=«text» id=«username» name=«username» required></p>

    <p><label for=«useremail»>Ваш email</label>

       <input type=«email» id=«useremail» name=«useremail» required></p>

    <p class=«col-2»><label>Знания:</label></p>

    <div class=«row»>

       <div>

          <label><input type=«checkbox» name=«skills[]» value=«HTML»> HTML</label>

          <label><input type=«checkbox» name=«skills[]» value=«CSS»> CSS</label>

       </div>

       <div>

          <label><input type=«checkbox» name=«skills[]» value=«JavaScript»> JavaScript</label>

          <label><input type=«checkbox» name=«skills[]» value=«PHP»> PHP</label>

      </div>

    </div>

    <button id=«send» class=«btn btn-info»>Отправить</button>

</form>

<div class=«loader» style=«display: none»>

    <div id=«loader-1»>

        <span></span>

        <span></span>

        <span></span>

        <span></span>

    </div>

</div>

<table class=«small-width»>

    <thead>

        <tr>

            <th>Данные</th>

            <th>Значение</th>

        </tr>

    </thead>

    <tbody></tbody>

</table>

<script src=«js/jquery-3.5.1.min.js»></script>

<script src=«js/jquery-ajax.js»></script>

Обратите внимание на name="skills[]" — мы даем одинаковые имена нескольким чекбоксам (флажкам), чтобы собрать затем все отмеченные пользователем значения в массив.

Кроме того, в самой форме (тег <form>) есть атрибут action, который нам понадобится в скрипте.

JavaScript

Метод  — $.ajax  позволяет передать ряд параметров внутри функции. Например, это url файла, который будет обрабатывать данные, — он передается в параметре url. В параметре type указывается метод передачи данных: чаще всего ‘POST’, т.к. он позволяет передавать бОльшие объемы данных, но также может быть ‘GET’, особенно, когда данные нужно получать, а не передавать.

Кстати, параметр method: «GET» — это значение по умолчанию для $.ajax, поэтому при загрузке данных вы можете смело его опустить.

В параметре data указываются те данные, которые нужно отправить на сервер в виде пар «имя_переменной: значение». Очень удобно использовать для этой цели метод jQuery serialize(), который собирает все данные формы в строку "переменная1=значение1&переменная2=значение2&переменная3=значение3" и т.д.

Функция success позволит нам вставить полученное ею значение (параметр ) в нужное место html-разметки. Код, представленный ниже нужно разместить в файле jquery-ajax.js, который в разметке мы подключим после подключения jQuery нужной вам версии.

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

$(document).ready(function() {

    let testForm = $(‘#testForm’);

    testForm.submit(function() {

        if ($(‘#username’).val().length < 5) {

            alert(«Введите не менее 5 символов!»);

            $(‘#username’).focus();

            return false;

        }

        if ($(‘#useremail’).val().length < 5) {

            alert(«Введите не менее 5 символов!»);

            $(‘#useremail’).focus();

            return false;

        }

        if ($(‘input[name=»skills[]»]:checked’).length == 0) {

            alert(«Выберите хотя бы один пункт!»);

            return false;

        }

        $.ajax({

            url: testForm.attr(‘action’),

            type: ‘POST’,

            data: testForm.serialize(),

            dataType: ‘html’,

            beforeSend: function(){

               $(‘.loader’).show();

            },

            success: function(result) {

                $(«.small-width tbody»).html(result);

            },

            complete: function(){

                $(‘.loader’).hide();

            }

        });

        return false;

    });

});

Обратите внимание, что мы обрабатываем событие submit для формы. Сначала мы проверяем правильность заполнения всех полей, и только в случае, если все верно заполнено пользователем, переходим к методу $.ajax.

При отправке AJAX-запроса указываем в параметре url данные из атрибута action нашей формы. В нашем примере это файл test-ajax.php, который размещен в папке php, являющейся дочерней для каталога с нашим html-файлом.

Использование предзагрузчика

Как правило, для того чтобы данные ушли на сервер, и файл на сервере вернул ответ, нужно некоторое время. Чем проще передаваемые данные и меньше их объем, а также больше скорость Интернета, тем меньше времени требуется для выполнения этих действий. Чтобы показать пользоваелю, что процесс идет, обычно используют предзагрузчик — gif-изображение или код HTML+CSS. Мы используем второй вариант — для этого перед таблицей в html-разметке у нас есть <div class="loader" style="display: none">. Здесь сразу явно указано, что первоначально этот блок скрыт. Вы можете сделать это в css-файле — здесь код css приводить не будем.

В JavaScript при отправке запроса методом $.ajax можно использовать функцию beforeSend для отображения предзагрузчика и функцию complete для его скрытия.

beforeSend: function(){

   $(‘.loader’).show();

},

...,

complete: function(){

    $(‘.loader’).hide();

}

Если у вас хорошая скорость Интернета, то вы можете не заметить появления предзагрузчика. Если же вы смотрите работу кода через мобильный Интернет, то скорей всего увидите его. Кроме того, в Chrome можно эмулировать соединение через 3G, выбрав соответствующую настройку на вкладке Сеть.

Медленный Интернет в настройках Chrome

Медленный Интернет в настройках Chrome

Код PHP-файла

Код PHP-файла test-ajax.php тоже простой. Мы сделаем проверку на наличие нужных переменных, а затем соберем их значения в виде строк таблицы:

<?php

if(!isset($_POST[‘username’])|| !isset($_POST[‘useremail’]) ||

!isset($_POST[‘skills’]) ) die(‘Нет нужных данных’);

$res = »;

foreach($_POST as $key=>$value){

    if($key == ‘username’) $first = ‘Имя (Логин)’;

    if($key == ‘useremail’) $first = ‘Email’;

    if($key == ‘skills’) {

        $first = ‘Знания:’;

        if(is_array ($value))$value = implode(‘, ‘, $value);

    }

    $res .= «<tr><td>$first</td><td>$value</td></tr>»;

}

echo $res;

die();

Давайте проверим код в действии (открыть пример в новой вкладке).

Работаем с Инспектором свойств браузера

Заголовки AJAX-запроса

Помимо того, что мы видим работу запроса в виде таблицы в html-файле, мы можем также проверить наш XHR запрос на вкладке Сеть (Network) в Инструментах разработчика (F12, или CTRL +SHIFT + I) в Chrome или Mozilla Firefox, так как все передаваемые нами данные уходят с помощью специальных заголовков.

Запрос с одним чекбоксом в Chrome

Запрос с одним чекбоксом в Chrome

Слева мы видим php-файл, который получил запрос и как-то на него ответил. Справа — данные самого запроса. На скриншоте выше это те отправленные данные, которые заполнил (отметил) в форме пользователь в виде пар имя_переменной: значение.

В случае, когда пользователь отметил 1, 2 и более чекбокса, мы видим, что в Google Chrome передаются данные массива.

Запрос с несколькими чекбоксами в Chrome

Запрос с несколькими чекбоксами в Chrome

В инспекторе свойств браузера Firefox  подобная картина, хоть и несколько иначе отображаемая.

Запрос с одним чекбоксом в Firefox

Запрос с одним чекбоксом в Firefox

Запрос с несколькими чекбоксами в Firefox

Запрос с несколькими чекбоксами в Firefox

Ответ сервера

В той же вкладке Сеть (Network) Инспектора свойств вы найдете и ответ сервера, который был сформирован нашим php-файлом. И в Chrome, и в Firefox мы можем видеть строки таблицы с отправленными данными.

Результат из php-файла в Chrome

Результат из php-файла в Chrome

Результат из php-файла в Firefox

Результат из php-файла в Firefox

Ошибки при AJAX-запросах

К сожалению, не все бывает так радужно с первого раза. Довольно часто в консоли вы можете наблюдать 500-ю ошибку (Internal Server Error). Как правило, она возникает тогда, когда есть ошибки в PHP-коде.

500-я ошибка при AJAX-запросеНапример, эта возникла, когда в 4-й строке вместо знака => стоял знак = в записи foreach($_POST as $key=>$value) . Не хватало всего-навсего угловой скобки, но это та синтаксическая  ошибка, которая не дает выполнить скрипт.

Узнать подробнее об ошибках вы можете из файла error_log, который автоматически формируется на сервере в той папке, где произошла ошибка.

PHP Parse error:  syntax error, unexpected ‘=’, expecting :: (T_PAAMAYIM_NEKUDOTAYIM) in /ajax/php/testajax.php on line 4

Кроме того, у вас может возникнуть 403 ошибка в том случае, если доступ к каким-то файлам или папкам на сервере у вас ограничен.

Особенности AJAX-запросов в  jQuery 3-й версии

В официальной документации по методу jQuery.ajax() вы найдете информацию о том, что функции success(), error() и complete() заменены на done(), fail() и always().

ajax в jQuery v3

ajax в jQuery v3

Однако, код, приведенный выше с использованием функций success() и complete() вполне работоспособный: запрос отправляется и ответ от сервера возвращается. Происходит это потому, что данные функции являются свойствами объекта $.ajax, а не его методами. Deprecated (устаревшими) являются методы изменения состояния AJAX .success, .error и .complete для объекта JQuery XML HTTP Request (jqXHR), которые действительно устарели.

Тем не менее, вы можете перейти к рекомендуемым функциям и несколько переделать код js-файла таким образом:

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

$(document).ready(function() {

    let testForm = $(‘#testForm’);

    testForm.submit(function() {

        if ($(‘#username’).val().length < 5) {

            alert(«Введите не менее 5 символов!»);

            $(‘#username’).focus();

            return false;

        }

        if ($(‘#useremail’).val().length < 5) {

            alert(«Введите не менее 5 символов!»);

            $(‘#useremail’).focus();

            return false;

        }

        if ($(‘input[name=»skills[]»]:checked’).length == 0) {

            alert(«Выберите хотя бы один пункт!»);

            return false;

        }

        $.ajax({

            url: testForm.attr(‘action’),

            type: ‘POST’,

            data: testForm.serialize(),

            dataType: ‘html’,

            beforeSend: function() {

                $(‘.loader’).show();

            }

        }).done(function(result) {

            $(«.small-width tbody»).html(result);

        }).always(function() {

            $(‘.loader’).hide();

        });

        return false;

    });

})

Второй пример с использованием функций done() и always() (открыть в новой вкладке):

Обратите внимание, что синтаксис этих функция несколько иной, т.к. используется технология промисов, которая позволяет назначать несколько обратных вызовов для одного запроса, например, так:

var somerequest = $.ajax({ ... });

somerequest.done(function(data) { /* Код 1 */ });

somerequest.done(function(data) { /* Код 2 */ });

Так что выбор способа описания функций остается за вами.

Еще один пример использования метода jQuery $.ajax вы можете найти в статье «Ajax-запросы с помощью jQuery 3-й версии и модального окна Bootstrap 4».

Просмотров: 1 389

Как решить эту ошибку: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

Я отправлял некоторые данные из ajax и php.

вот мой код ajax:

flag = 111;
var dt = $(this).serializeArray();
dt.push({
name: 'flag',
value: flag
});

$.ajax({
url: 'emp.php',
type: "post",
async: true,
data: dt,
dataType: 'html',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
success: function(data) {
var x = JSON.parse(data); //THIS Line shows error!!
alert(x);
$('#name').val(x.ename);
$('#designation').val(x.designation);
$('#department').val(x.department);
$('#sd').val(x.secdivision);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});

вот мой php:

$empid = (isset($_POST['employeeid'])) ? $_POST['employeeid'] : 'NOT';
$flag  = (isset($_POST['flag'])) ? $_POST['flag'] : 0;
if($flag == 111){
$stid = oci_parse($conn, " begin
:result :=  PKG_PAYROLL.get_emp_by_id('<employee_id>$empid/employee_id>');
end;" );

oci_bind_by_name($stid, ':result',$ru, 5000);
$output = oci_execute($stid);
$ru = new SimpleXMLElement($ru);
$json = json_encode($ru, JSON_NUMERIC_CHECK);
$jsonarray = json_decode($json ,true);
$jsn = $jsonarray['employee'];

$array = array('employee' =>   $jsn['EMPID'],
'ename' => $jsn['ENAME'],
'designation' => $jsn['DESIGNATION'],
'department'=>  $jsn['DEPARTMENT'],
'secdivision'=>  $jsn['SECDIVISION']);
echo json_encode($array);
}

Обновления:
Вот пример данных ответа, которые я получил в консоли после echo json_encode($array);

<br />
<font size='1'><table class='xdebug-error xe-notice' dir='ltr' border='1' cellspacing='0' cellpadding
='1'>
<tr><th align='left' bgcolor='#f57900' colspan="5"><span style='background-color: #cc0000; color: #fce94f
; font-size: x-large;'>( ! )</span> Notice: Undefined index: employee in C:wampwwwPayrollemp.php
on line <i>24</i></th></tr>
<tr><th align='left' bgcolor='#e9b96e' colspan='5'>Call Stack</th></tr>
<tr><th align='center' bgcolor='#eeeeec'>#</th><th align='left' bgcolor='#eeeeec'>Time</th><th align
='left' bgcolor='#eeeeec'>Memory</th><th align='left' bgcolor='#eeeeec'>Function</th><th align='left'
bgcolor='#eeeeec'>Location</th></tr>
<tr><td bgcolor='#eeeeec' align='center'>1</td><td bgcolor='#eeeeec' align='center'>0.0002</td><td bgcolor
='#eeeeec' align='right'>247040</td><td bgcolor='#eeeeec'>{main}(  )</td><td title='C:wampwwwPayroll
emp.php' bgcolor='#eeeeec'>..emp.php<b>:</b>0</td></tr>
</table></font>
{"employee":"FMCSC00015","ename":"Tom","designation":"Teacher","department":"English","secdivision":"Academic"}

parsererror SyntaxError: JSON.parse: неожиданный символ в строке 1
столбец 1 данных JSON

Я не совсем понимаю основную причину этой ошибки, потому что ранее я уже делал код такого же типа с json. Я проверил, что php работает нормально.

5

Решение

Вы возвращаетесь JSON с сервера и разбора HTML dataType на стороне клиента. Итак, в вашем коде измените ваш тип данных:

dataType: 'html'

в

dataType: 'json'

Надеюсь это поможет.

8

Другие решения

**** Если ваш ответ в формате HTML, но ответ содержит данные JSON. Затем вы столкнулись с этой ошибкой («JSON.parse: неожиданный символ в строке 1 столбца 1 данных JSON»). Чтобы избежать этой ошибки, используйте код, указанный ниже: ****

$.ajax({
url: 'emp.php',
type: "post",
async: true,
data: dt,
dataType: 'html',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
success: function(data) {
try {
var x = JSON.parse(data);
} catch (e) {
return false;
}
//JSON.parse(data) THIS Line shows error!!
alert(x);
$('#name').val(x.ename);
$('#designation').val(x.designation);
$('#department').val(x.department);
$('#sd').val(x.secdivision);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});

Если вы отвечаете из PHP в простом формате json, то вы должны использовать этот код. Но в этом случае ваш ответ из PHP-файла — только формат json.

$.ajax({
url: 'emp.php',
type: "post",
async: true,
data: dt,
dataType: 'json',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
success: function(data) {
$('#name').val(data.ename);
$('#designation').val(data.designation);
$('#department').val(data.department);
$('#sd').val(data.secdivision);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}

0

The JavaScript exceptions thrown by JSON.parse() occur when string failed
to be parsed as JSON.

Message

SyntaxError: JSON.parse: unterminated string literal
SyntaxError: JSON.parse: bad control character in string literal
SyntaxError: JSON.parse: bad character in string literal
SyntaxError: JSON.parse: bad Unicode escape
SyntaxError: JSON.parse: bad escape character
SyntaxError: JSON.parse: unterminated string
SyntaxError: JSON.parse: no number after minus sign
SyntaxError: JSON.parse: unexpected non-digit
SyntaxError: JSON.parse: missing digits after decimal point
SyntaxError: JSON.parse: unterminated fractional number
SyntaxError: JSON.parse: missing digits after exponent indicator
SyntaxError: JSON.parse: missing digits after exponent sign
SyntaxError: JSON.parse: exponent part is missing a number
SyntaxError: JSON.parse: unexpected end of data
SyntaxError: JSON.parse: unexpected keyword
SyntaxError: JSON.parse: unexpected character
SyntaxError: JSON.parse: end of data while reading object contents
SyntaxError: JSON.parse: expected property name or '}'
SyntaxError: JSON.parse: end of data when ',' or ']' was expected
SyntaxError: JSON.parse: expected ',' or ']' after array element
SyntaxError: JSON.parse: end of data when property name was expected
SyntaxError: JSON.parse: expected double-quoted property name
SyntaxError: JSON.parse: end of data after property name when ':' was expected
SyntaxError: JSON.parse: expected ':' after property name in object
SyntaxError: JSON.parse: end of data after property value in object
SyntaxError: JSON.parse: expected ',' or '}' after property value in object
SyntaxError: JSON.parse: expected ',' or '}' after property-value pair in object literal
SyntaxError: JSON.parse: property names must be double-quoted strings
SyntaxError: JSON.parse: expected property name or '}'
SyntaxError: JSON.parse: unexpected character
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data

Error type

What went wrong?

JSON.parse() parses a string as JSON. This string has to be valid JSON
and will throw this error if incorrect syntax was encountered.

Examples

JSON.parse() does not allow trailing commas

Both lines will throw a SyntaxError:

JSON.parse("[1, 2, 3, 4,]");
JSON.parse('{"foo": 1,}');
// SyntaxError JSON.parse: unexpected character
// at line 1 column 14 of the JSON data

Omit the trailing commas to parse the JSON correctly:

JSON.parse("[1, 2, 3, 4]");
JSON.parse('{"foo": 1}');

Property names must be double-quoted strings

You cannot use single-quotes around properties, like ‘foo’.

JSON.parse("{'foo': 1}");
// SyntaxError: JSON.parse: expected property name or '}'
// at line 1 column 2 of the JSON data

Instead write «foo»:

JSON.parse('{"foo": 1}');

Leading zeros and decimal points

You cannot use leading zeros, like 01, and decimal points must be followed by at least
one digit.

JSON.parse('{"foo": 01}');
// SyntaxError: JSON.parse: expected ',' or '}' after property value
// in object at line 1 column 2 of the JSON data

JSON.parse('{"foo": 1.}');
// SyntaxError: JSON.parse: unterminated fractional number
// at line 1 column 2 of the JSON data

Instead write just 1 without a zero and use at least one digit after a decimal point:

JSON.parse('{"foo": 1}');
JSON.parse('{"foo": 1.0}');

See also

Понравилась статья? Поделить с друзьями:

Читайте также:

  • After effects ошибка 127
  • After effects неизвестная ошибка рисования mac os
  • After effects код ошибки 1609629695
  • After effects как изменить цвет сплошной заливки
  • After effects как изменить цвет солида

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

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