Я хочу реализовать отправку и моментальное отображение комментария через ajax.
Передаю необходимую инфу. Возвращаю обратно готовую разметку нового комментария.
Вот полный код ошибки :
Код на jquery:
function sendComment() {
const sendButton = $('.post__write-comment-sbmt');
sendButton.each(function () {
$(this).click(function (e) {
e.preventDefault();
const clicked = $(this);
//ПЕРЕМЕННЫЕ ДЛЯ ПЕРЕДАЧИ ПО AJAX
const message = clicked.siblings('.post__write-comment-write').val()
const postID = clicked.closest('.post').attr('id');
const commentsCount = clicked.closest('.post').find('.post__comment-count');
//___________________________________________________________________________________
$.ajax({
type: 'POST',
url: 'php-scripts/likes-commentshandler.php',
data: {
sendComment: '',
postID: postID,
message: message,
commentsCount: commentsCount.text(),
},
dataType: 'html',
success: function (data) {
const comItems = clicked.siblings('.post__com-items');
comItems.append($(data));
commentsCount.text(commentsCount + 1);
}
});
});
});
}
Код на php:
function sendComment()
{
require __DIR__ . '/../#DATABASE.php';
if (isset($_POST['sendComment'])) {
//---------------ПЕРЕМЕННЫЕ-----------------------
$postID = $_POST['postID'];
$userID = $_SESSION['user']['id'];
$message = htmlspecialchars($_POST['message']);
$commentsCount = $_POST['commentsCount'];
$name = $_SESSION['user']['name'];
$surname = $_SESSION['user']['surname'];
//________________________________________________
//---------------mysql-запрос---------------------
$query = $db->prepare(
"INSERT INTO `comments` (`postid`, `userid`, `message`, `id`) VALUES ('$postID', '$userID', :message, NULL)"
);
$param = [
'message' => $message
];
$query->execute($param);
//_____________________________________________________
//-------------------Ответ ajax------------------------
echo 'div class="post__com-item"><div class="post__com-header"><div class="post__com-author"><a href="another-page.php?uid=' . $userID . '" class="post__com-author-link"><img src="img/ava.jpg" alt="" class="post__com-ava"><span class="post__com-nickname">' . $name . ' ' . $surname . '</span></a></div></div><div class="post__com-body"><p class="post__com-message">' . $message . '</p></div></div>';
//______________________________________________________
}
}
По поводу js понятно.
А вот код ничего не дал. Реакция та же.
jquery-3.3.1.min.js:2 Uncaught Error: Syntax error, unrecognized expression: +7 (111) 111-11-11
at Function.oe.error (jquery-3.3.1.min.js:2)
at oe.tokenize (jquery-3.3.1.min.js:2)
at oe.select (jquery-3.3.1.min.js:2)
at Function.oe [as find] (jquery-3.3.1.min.js:2)
at w.fn.init.find (jquery-3.3.1.min.js:2)
at new w.fn.init (jquery-3.3.1.min.js:2)
at w (jquery-3.3.1.min.js:2)
at Object.success (js1.js:774)
at u (jquery-3.3.1.min.js:2)
at Object.fireWith [as resolveWith] (jquery-3.3.1.min.js:2)
В принципе есть идея убирать скобки перед отправкой а в php их добавлять..но как то выглядит это .. что то отрезал что то пришил..почему такая реакция на скобки…?
Добавлено через 27 секунд
без скобок все работает
Добавлено через 1 час 32 минуты
в общем не совсем в этом проблема как оказалось. Мне нужна была маска ввода на телефон. я использовал следующий код(код не мой) :
Javascript | ||
|
в этом случае маска отрабатывает просто отлично, на 100% устраивая меня. Получше того плагина маски что так часто встречается в инете..но как следствие ajax не принимает скобки при отправке. Отправка то происходит но ошибка в консоли отображается. Если этот код отключить все отправляется нормально и со скобками.
Let’s face it, nobody is perfect! Everyone makes mistakes now and then and jQuery is the same – although they have an excellent bug fixing team who are fixing up errors and enhancing jQuery around the clock errors may appear from time to time.
In light of this and the fact that I’ve been developing with jQuery for quite a while now and every now and then an error will show in the Firebug Console and “I have to Google it”. I thought I would share some of the most common jQuery errors so that when you encounter them you might have some idea of how to solve the puzzle.
Error: “jquery.1.4.2.js error “a is null””
Possible Causes
a is null
[Break On This Error] a))();else c.error("Invalid JSON: "+a)...(d)if(i)for(f in a){if(b.apply(a[f],
jquery....min.js (line 29)
I was thinking it might have something to do with this line failing because there was no matches.
$.each(rawData.match(secureQueryRegex), function(index, currentQuery)
Then, I was thinking it may have been the size of data as it was 69,443 characters long…
Possible Solutions
But I eventually found out it was bad characters inside the data string (which was grabbed directly from HTML). See cleanHTML() function to remove bad characters form HTML.
rawData = rawData.replace(/[^<>a-zA-Z 0-9]+/g,''); /* clean up for match() statement */
Specific Versions
Seen in 1.4.2
Error: “SyntaxError: invalid object initializer”
Possible Causes
Object declaration syntax error.
$.getScript(
{
'http://www.domain.com/js/preview.js'
});
OR
$("div").css(
{
padding:'0',
margin,'4px'
});
Possible Solutions
Remove the brackets the getScript() function can be called with just the url. The same applies to any other object declaration or function call with an object that doesn’t accept one.
$.getScript('http://www.domain.com/js/preview.js');
Change the comma to a semi colon.
$("div").css(
$("div").css(
{
padding: '0',
margin: '4px'
});
Specific Versions
Seen in 1.4.2
Error: “uncaught exception: Syntax error, unrecognized expression: [object HTMLLIElement]”
Possible Causes
This seems like a jQuery selector error. It seems to appear more frequently in v1.4.2 or earlier so try updating to the latest version of jQuery.
$(this+' a').css(
var req = $("input[@name=required]").val();
Possible Solutions
Not sure but take a look at your selectors and make sure they work properly. Try including the full jQuery versions first to get better error info on what might be causing the problem.
@ is old selector syntax.
var req = $("input[name=required]").val();
Specific Versions
Seen in 1.4.2
Error: “SyntaxError: missing ) after argument list”
Possible Causes
Missing off closing brackets or curly braces.
})(jQuery
Possible Solutions
})(jQuery);
Specific Versions
Seen in 1.4.2
Error: “SyntaxError: missing : after property id”
Possible Causes
This is a repeat of the object initialize error but it’s caused by Using curly brackets when they are not needed.
$.getScript(
{
'http://www.domain.com/js/preview.js', function(data, textStatus){
console.log(data); //data returned
console.log(textStatus); //success
console.log('Load was performed.');
});
Possible Solutions
$.getScript('http://www.domain.com/js/preview.js', function(data, textStatus)
{
console.log(data); //data returned
console.log(textStatus); //success
console.log('Load was performed.');
}
);
Specific Versions
Seen in 1.4.2
Error: “TypeError: jsSrcRegex.exec(v) is null”
Possible Causes
Caused by double exec on same regex OR caused by invalid html “jsSrcRegex.exec(v) is null”.
console.log(jsSrcRegex.exec(v));
console.log(jsSrcRegex.exec(v)[1]);
Possible Solutions
Check the html first:
if(jsSrcRegex.exec(html)){
console.dir(jsSrcRegex.exec(html)[1]);
}
OR
Use recompile the regex:
console.log(jsSrcRegex.exec(v));
jsSrcRegex.compile();
console.log(jsSrcRegex.exec(v)[1]);
Specific Versions
n/a
Error: “XML descendants internal method called on incompatiable object”
Possible Causes
Double full stop in jQuery chain commands.
$('.'+inElem)..removeClass('mouseover').addClass('selected');
Possible Solutions
To fix simply remove the double full stop.
Specific Versions
n/a
Error: “undetermined string literal”
You may have seen this one before!
Possible Causes
Many possible causes: could be that you put code where a selector should be or multiple line strings or wrong string format (bad characters) or angle brackets etc.
Possible Solutions
See jQuery Undetermined String Literal Error for a very detailed explanation on this error!
Specific Versions
n/a
Error: “Syntax Error: Unrecognized Expression”
Possible Causes
Missing attribute name in selector.
$('input["depDate"]').val(departureDate);
Possible Solutions
Add in the name attribute (or id, class etc) into the selector.
$('input[name="depDate"]').val(departureDate);
Specific Versions
n/a
Error: “SyntaxError: syntax error”
(click image to enlarge)
Possible Causes
Well, this error is very generic and there might be a number of reasons why is happens but in this example you can clearly see it was caused by an extra “+” in the jQuery selector.
$('.itemColumn'+currentColNum+).append(v);
Possible Solutions
Unfortunately, on this one you’ve just got to carefully check through your syntax and make sure you don’t have any mistakes. Try using something like jshint or another js checker to assist.
$('.itemColumn'+currentColNum).append(v);
Specific Versions
n/a
Error: “(d || “”).split is not a function”
Possible Causes
Sorry, I found this error and took a screenshot but can’t remember how i got it! I think it might be a live image hover bug in jQuery 1.4.2 but not sure.
Here is something bug 862 similar which i found (it was logged 5 years ago aha).
Sometimes you see a similar error which reads “jquery error d is undefined” or such which I saw a few times in jQuery 1.5.
Possible Solutions
Update to latest version of jQuery.
Specific Versions
Seen in 1.4.2
Error: “Syntax error, unrecognized expression: >”
Possible Causes
if ($('#'+$form).length == 0)
{
...
}
if ($('#'+$form))
{
...
}
Possible Solutions
Don’t try to use html as a jQuery selector element.
Specific Versions
Seen in 1.7.1
Error: “Syntax error, unrecognized expression: #[object Object]”
Possible Causes
Using an DOM element as a jQuery selector element.
$('#'+$form)
Possible Solutions
Check your jQuery selectors are correct.
Specific Versions
Seen in 1.7.1
Error: “Syntax error, unrecognized expression: name”
Possible Causes
var code = $(':input:name=["disCode"]').val();
Possible Solutions
Move square bracket before attribute name.
var code = $(':input:[name="disCode"]').val();
Specific Versions
Seen in 1.7.2
Error: “XML descendants internal method called on incompatible Object”
Possible Causes
discElem..parent().after(data.html);
Possible Solutions
discElem.parent().after(data.html);
Specific Versions
Seen in 1.7.2
Error: “SyntaxError: invalid label”
Possible Causes
Using a colon at the end of a statement.
console.log(count):
Possible Solutions
Use a semi colon instead of a colon.
console.log(count);
Specific Versions
Seen in 1.7.2
Error: “TypeError: emails.match(/@/gim) is null”
Possible Causes
Using .length function on a regular expression which has no matches.
var emails = '',
count = emails.match(/@/igm).length;
Possible Solutions
If you reference the length property after then it simply returns undefined and no error. If you use the following you will see the error: “TypeError: count is null”.
var emails = '',
count = emails.match(/@/igm),
length = count.length;
If you check the count is not null before assigning the value it does not error and will give you 0 for a no count.
var emails = '',
regex = /@/igm,
count = emails.match(regex),
count = (count) ? count.length : 0;
Specific Versions
Seen in 1.7.2
Error: Error in Actionscript. Use a try/catch block to find error.”
Possible Causes
Using a call on a Flowplayer or Flash based Object with errors.
$f('fms2').toggleFullscreen();
Possible Solutions
Try checking the initialisation code for the Flash Object.
Specific Versions
Seen in 1.7.2
After seeing all those errors, here’s something to cheer you up!
Or you can see more errors and bugs on the Official jQuery Bug Tracker.
If you find any errors please leave a comment with the error and solution and i will add it to the list!
Cheers!
- Remove From My Forums
-
Question
-
Hi, I am having trouble using SPServices.SPGetCurrentUser function. The script containing my code
$.SPServices.SPGetCurrentUser({ fieldName: "EMail", debug: false });
is returning
Uncaught Error: Syntax error, unrecognized expression: <!DOCTYPE html...</html>.
Console:
Sizzle.error @ jquery-1.9.0.js:4411 tokenize @ jquery-1.9.0.js:5057 select @ jquery-1.9.0.js:5439 Sizzle @ jquery-1.9.0.js:3984 find @ jquery-1.9.0.js:5553 init @ jquery-1.9.0.js:179 jQuery @ jquery-1.9.0.js:53 V.fn.SPServices.SPGetCurrentUser @ jquery.SPServices-0.7.2.min.js:19 (anonymous function) @ EditForm.aspx?ID=8&Source=[source] dispatch @ jquery-1.9.0.js:3045 elemData.handle @ jquery-1.9.0.js:2721
The error is displaying the whole html markup of the page. The .js file is added to the form page using Content Editor. Other files referenced
inside my .js are:<script type="text/javascript" src="/js/jquery.SPServices-0.7.2.min.js"></script> <script type="text/javascript" src="https://static.sharepointonline.com/bld/_layouts/15/16.0.5326.1210/clientpeoplepicker.js"></script>
I am also auto populating people picker fields within the form using hardcoded emails (link)
and it works just fine.Anyone encountered this error? Please share your thoughts. TIA
Jeff
Answers
-
Hi,
To get more details about current user, if REST API is accepted by you, here is a demo about how to get email of current user would be helpful.
This is the response of calling this endpoint:
The code in use:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script> <script type="text/javascript"> _spBodyOnLoadFunctionNames.push("ready"); function ready() { $.ajax({ url: _spPageContextInfo.webAbsoluteUrl + "/_api/SP.UserProfiles.PeopleManager/GetMyProperties", method: "GET", headers: { "Accept": "application/json; odata=verbose" }, success: function (data) { console.log(data.d.Email); } }); } </script>
Best regards,
Patrick
TechNet Community Support
Please remember to mark the replies as answers if they help, and unmark the answers if they provide no help. If you have feedback for TechNet Support, contact
tnmff@microsoft.com.-
Proposed as answer by
Thursday, June 16, 2016 8:51 AM
-
Marked as answer by
Patrick_Liang
Monday, June 20, 2016 8:26 AM
-
Proposed as answer by
- Remove From My Forums
-
Question
-
User-1188570427 posted
Hello,
I have this line of code:
let theId = $(`div:contains(${id})`).closest('.item-container').find('.item-identifier').val();
And when the text is this:
The HR Query (for admins)
It fails with this error:
Uncaught Error: Syntax error, unrecognized expression: div:contains(The HR Query (for admins)) at Function.Sizzle.error (jquery-3.4.1.js:1560) at Sizzle.tokenize (jquery-3.4.1.js:2216) at Sizzle.select (jquery-3.4.1.js:2643) at Function.Sizzle [as find] (jquery-3.4.1.js:862) at jQuery.fn.init.find (jquery-3.4.1.js:2896) at new jQuery.fn.init (jquery-3.4.1.js:3006) at jQuery (jquery-3.4.1.js:152) at list.js:129 at Array.map (<anonymous>) at createSelectedItemsContainer (list.js:127)
How would you handle parentheses within this call?
If I make it this:
The HR Query for admins
It works without errors.
Answers
-
User-939850651 posted
Hi tvb2727,
I think the value you get through ${id} as a parameter of the contains function is not a correct format.
You could try to use the $.escapeSelector(param) function to escape special characters, or you could use quotation marks to enclose the parameters.
Something like this:
<head> <meta charset="utf-8" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <title></title> <script> $(document).ready(function () { var id = "The HR Query (for admins)"; //console.log($(id).val()); console.log($($.escapeSelector(id))); var value1 = $('div:contains(' + id + ')').text(); var value2 = $('div:contains(' + $.escapeSelector(id) + ')').text(); console.log(value1); console.log(value2); }); </script> </head> <body> <div> The HR Query (for admins) </div> </body>
I will get the same error as you said in the commented line.
Result:
Hope this can help you.
Best regards,
Xudong Peng
-
Marked as answer by
Thursday, October 7, 2021 12:00 AM
-
Marked as answer by