Syntax error, unrecognized expression on ajax call - javascript

I am working on a project where i have an issue with the commenting function i've made. Whenever i comment and use special characters the console displays this error: syntax error, unrecognized expression. Furthermore the request goes through and my backend (PHP) inserts the data to the DB but i then have to refresh to get the updated version of the post with that new comment. I can't figure out why even after a couple of searches here on stack and i could really use a new pair of eyes on the code.
I figure that the backend isn't the issue which is why it's left out of this post. Furthermore the form just contains a text input and a submit button. It might be important to mention that i use jQuery v3.3.1.
Finally when the form is submitted an ajax call gets triggered. Here it is:
var newComment;
$(document).on("submit", "form[data-comment]", function(e){
e.preventDefault();
var where = $(this);
var updateThis = $(where).parent().parent();
var data = $(where).attr("data-comment").split(",");
var comment = $(where).find("input[name='commenter']").val().toString();// <= this might be the issue?
if (data[0] == 1){
if (data[1] != "" && data[2] != "" && data[3] != ""){
//insert comment via ajax and return post and insert post
if (newComment){ <= prevent firing until newComment = false
newComment.abort();
return false;
}
$(where).find("input[type='submit']").prop("disabled", true);
$(where).find("input[type='submit']").val("commenting...");
newComment = $.ajax({
url: "mypage/core/AjaxRequests.php", <= call to php handler
type: "POST",
data: { type: "15", data: data, comment: comment }
});
$(comment).val("");
newComment.done(function(response, textStatus, jqXHR){
newComment = false;
$(where).find("input[type='submit']").prop("disabled", false);
$(where).find("input[type='submit']").val("Comment");
if (response.length > 200){
$(updateThis).parent().fadeTo(0,0);
$(updateThis).parent().prop('outerHTML', response);
$(updateThis).parent().fadeTo(1,1);
}
});
}
}
});

Related

AJAX JQuery PHP mail sending form

I am working on a site which having 2 contact forms, and I use ajax jquery to send mail via php.
When I use single form and jQuery, it works fine.
And when I paste the jQuery code and modify as per form 2 variables, it works, but then first jQuery code is sending blank values.
Over all at a time, only 1 form is working for my HTML forms on different page.
I appreciate your help in advance.
Jquery code
var form=$('#contactform_forms');
var formMessages=$('#message');
$(form).submit(function(e){
$('#submit_btns')
.after('<img src="images/AjaxLoader.gif" class="loader" />')
.attr('disabled','disabled');
e.preventDefault();
var formData=$(form).serialize();
$.ajax({
type:'POST',
url:'contact.php',
data:formData
})
.done(function(response){
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
$(formMessages).text('Thanks! Message has been sent.');
$(formMessages).fadeOut(10000);
$('#contactform_forms img.loader').fadeOut('slow',function(){$(this).remove()});
$('#submit_btns').removeAttr('disabled');
$('#contact_name').val('');
$('#contact_email').val('');
$('#contact_phone').val('');
$('#contact_message').val('');
}).fail(function(data){
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
if(data.responseText!==''){
$(formMessages).text(data.responseText);
}else{
$(formMessages).text('Oops! An error occured.');
}
});
});
jQuery code for form 2 with the same js file:
var form=$('#wholesalers_forms');
var formMessages=$('#message');
$(form).submit(function(e){
$('#submit_btns1')
.after('<img src="images/AjaxLoader.gif" class="loader" />')
.attr('disabled','disabled');
e.preventDefault();
var formData=$(form).serialize();
$.ajax({
type:'POST',
url:'wholesalers.php',
data:formData
})
.done(function(response){
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
$(formMessages).text('Thanks! Message has been sent.');
$(formMessages).fadeOut(10000);
$('#wholesalers_forms img.loader').fadeOut('slow',function(){$(this).remove()});
$('#submit_btns1').removeAttr('disabled');
$('#hs_name').val('');
$('#hs_email').val('');
$('#hs_company').val('');
$('#hs_vat').val('');
$('#hs_address').val('');
$('#hs_postcode').val('');
$('#hs_city').val('');
$('#hs_phone').val('');
$('#hs_message').val('');
}).fail(function(data){
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
if(data.responseText!==''){
$(formMessages).text(data.responseText);
}else{
$(formMessages).text('Oops! An error occured.');
}
});
});
When I use both as the above order: 1st one send empty value and second form working perfectly, if i remove 2nd jQuery then first code working fine, but second do not have code to send.
There are a few issues here. First I can see you've got duplicate element IDs on the page which will produce undefined results. Second, you shouldn't be copying and pasting code but iterating through (or making generic) your code, depending on the usage. This keeps your code DRY. Further reading here: https://en.wikipedia.org/wiki/Don%27t_repeat_yourself.
If you are still having trouble, add a jsFiddle with the specific parts of the code you are having trouble with.
I'd do something like this:
function getFormData(form_id) {
var form_data = {};
$.each($("#" + form_id).serializeArray(), function(i, obj) {
if (form_data[obj.name] == undefined) {
form_data[obj.name] = obj.value;
} else if (typeof form_data[obj.name] == Array) {
form_data[obj.name].push(obj.value);
} else {
form_data[obj.name] = [form_data[obj.name], obj.value];
}
});
return form_data;
}
function validate(form_id) {
var error = false;
//run some validation, which alters display and sets error to true on failure.
return error;
}
$(document).on("submit", "form", function(event) {
var form_id = $(this).attr("id");
if (validate(form_id)) { //If error is found.
event.preventDefault();
} else { //Else the form is good.
var form_data = getFormData(form_id),
url = (form_id == "contactform_forms") ? "contact.php" : "wholsalers.php";
$.ajax({
type: "post",
url: url,
data: form_data,
success: function(data) {
//Display a confirmation message.
}
})
}
});

Google reCAPTCHA reset multiple captchas rendered by function call

I have many reCAPTCHA's who are rendered dynamically, sometimes there are 2 sometimes 50 depends on page.
I've done rendering with this:
<script src="https://www.google.com/recaptcha/api.js?onload=CaptchaCallback&render=explicit" async defer></script>
var CaptchaCallback = function(){
$('.g-recaptcha').each(function(index, el) {
grecaptcha.render(el, {'sitekey' : 'myKey'});
});
};
And placed this where I want captcha to be displayed:
<div class="g-recaptcha" data-sitekey="myKey"></div>
I've got ajax call, that submits form data to process.php, and if form data isn't verified returns custom errors
$.ajax({
type : 'POST',
url : 'process.php',
data : $(this).serialize(),
dataType : 'json'
})
.done(function(data) {
if ( ! data.success) { ...
It works as intended, but now I want to show message to user as part of validation, if he forgot to solve captcha.
With
var response = grecaptcha.getResponse();
if(response.length == 0){
$('.result').append('Captcha incorrect, please click I am not robot');
}
and to reset captcha add this bellow
if ( ! data.success) {
grecaptcha.reset();
What does it do is: reset captcha if user didn't completed all forms valid.
This all works only on 1st occurrence of reCAPTCHA.
And I need it to somehow tell it to reset only captcha that is currently in use.
My best guess was to try with
var form = $(this); //get current form
grecaptcha.reset(form);
It won't work, since i need widget ID, and not form.
Can you assist me pls?
All credits to https://stackoverflow.com/a/41860070/7327467
reset is done with
var form = $(this); //store current form
var response = grecaptcha.getResponse(jQuery(form).find('#data-widget-id').attr('data-widget-id'));
if(response.length == 0){ //append error to result div
form.find('.result').append('<div class="alert alert-danger">' + "Captcha incorrect" + '</div>'); }
and to reset recaptcha, I've added this instead previous "grecaptcha.reset();"
grecaptcha.reset(jQuery(form).find('#data-widget-id').attr('data-widget-id'));
Hope this helps.

How to display comment form submit without refresh the page using AJAX?

Comment Form is submitting and also data getting saved to the database. But not displaying on the browser without refreshing the page.
here is the code:
$("#post_reply").click(function (event) {
$("#data_status").html("");
$('#ajax_loading').show();
event.preventDefault();
if (document.getElementById('_comment').value.trim() == "") {
return false;
}
$.post('../services/leave_comment.php', $("#open_status").serialize(), function (data) {
$('#ajax_loading').hide();
if (data.split("::")[1] == true) {
$("#data_status").html("Commented Successfully..");
$("#data_status").fadeOut(3000);
document.getElementById('_comment').value = '';
$('#_comment').html("");
} else if (data.split("::")[1] == false) {
$("#data_status").html("Error occured in Comment Submission.. TryAgain..");
$("#data_status").fadeOut(3000);
}
});
});
EDIT:
All i can understand is i haven't published the data with ajax??
Is this what i need to do??
$("#post_reply").click(function (event) {
$("#data_status").html("");
$('#ajax_loading').show();
event.preventDefault();
if (document.getElementById('_comment').value.trim() == "") {
return false;
}
$.post('../services/leave_comment.php', $("#open_status").serialize(), function (data) {
$('#ajax_loading').hide();
if (data.split("::")[1] == true) {
$("#data_status").html("Commented Successfully..");
$("#data_status").fadeOut(3000);
document.getElementById('_comment').value = '';
$('#_comment').html("");
$.ajax({
type: 'POST',
url : 'http://localhost/tech1/services/get_more_comments.php',
data: 'last_id='+last_id,
success: function(data){
$('.view_container').append(data);
},
complete: function(){
console.log('DONE');
}
});
} else if (data.split("::")[1] == false) {
$("#data_status").html("Error occured in Comment Submission.. TryAgain..");
$("#data_status").fadeOut(3000);
}
});
});
All your code does is post the data to the server. There is nothing that fetches the new comments from the server or manually appends the posted comment. You can either use ajax again to refresh comments or more simply append a comment with the posted content.
I would say to search the web for jQuery's .load :
example:
function updateShouts(){
// Assuming we have #shoutbox
$('#shoutbox').load('latestShouts.php');
}
in this case shoutbox would be the containing div with your comments,
you would call this function on the success of your ajax post
latestshouts.php would only contain the content of that div.
kinda hard to explain, i hope it makes sense to you
link: http://api.jquery.com/load/

Rails, AJAX form validation

I am new to jQuery, AJAX, and javascript in general, and I am trying to do some front end validation for a rails form that uses an ajax call to have the server run a query. It seems to work well, if I am in the debugger (since the AJAX call has enough time to return and stop the submission of the form), but it wont work all of the time when I am just testing it without the debugger. I believe this happens because after the ajax call, the javascript validation method exits, and the form submits. Here is my javascript method
$('#runner-job-submit').click(function(e) {
runnerJobValidation(e);
});
function runnerJobValidation(e) {
var user_login = $('#user_login').val();
var name = $('#name').val();
var location = $('#location').val();
var description = $('#description').val();
var user_exists;
//AJAX call to check if user exists in the database
$.post("/jobs/user_exists", {user_login: user_login}, function (response) {
if(response == "false") {
$('#runner-new-job-errors').html('');
e.preventDefault();
$('#runner-new-job-errors').append('<small style="color:red"> User doesnt exist </small>');
}
});
if(user_login == "" || name == "" || location == "" || description == "") {
$('#runner-new-job-errors').html('');
e.preventDefault();
$('#runner-new-job-errors').append('<small style="color:red"> Please fill out all fields </small>');
}
}
And here is my controller action url it is hitting
def user_exists?
user_login = params[:user_login]
user = User.where("login = ?", user_login).first
user_exists = user.present?
respond_to do |format|
format.js { render :json => user_exists.to_json}
format.html { redirect_to jobs_path }
end
end
Can someone please tell me the correct way to do this. I feel the solution is to somehow prevent runnerJobValidation() from exiting before response is received from the server, but I just dont know how to do this.
You are trying to make an synchronous ajax request. In short, you can do it by set async in ajax object to false.
You can found your solution here : How to make JQuery-AJAX request synchronous.
Hope this help.
You can user jQuery validation plugin like http://jqueryvalidation.org/
For validation you should add new validation method http://jqueryvalidation.org/jQuery.validator.addMethod/
Something like this:
jQuery.validator.addMethod("user_exists", function(value, element, param) {
var isSuccess = false;
isSuccess = $.ajax(type: "POST", url: "/jobs/user_exists", data: {user_login: user_login}, dataType: "json").responseText == "false" ? false : true;
return isSuccess;
}, jQuery.format("User already exists!"));
And for form submit:
$("#myform").validate({
submitHandler: function(form) {
// some other code
// maybe disabling submit button
// then:
$(form).submit();
}
});
About how to properly use plugin read docs at http://validation.bassistance.de/documentation/

setTimeout doesn't start until I stop the page

On the event of a form submit, I have a jquery ajax function that queries for the amount of data uploaded from a file that I can use in making a progress bar. This is my js file:
var submitted = '';
var counter = 0;
$('#webfileuploadform').submit(function(){
if(submitted == 'submitted') return false; // prevents multiple submits
var freq = 1000; // freqency of update in ms
var progress_url = '/upload_progress/' + $('#id_progress_id').val(); // ajax view serving progress info
update_progress_bar();
function update_progress_bar(){
$.ajax({
dataType:"json",
url: progress_url,
success: function(data){
counter ++
console.log('hit success ' + counter);
},
complete: function(jqXHR, status){
if (status == 'success'){
console.log('hit complete', status == success')
} else {
console.lot('hit complete', status == something else')
}
}
});
setTimeout(function(){update_progress_bar()}, freq);
}
submitted = 'submitted'; // marks form as submitted
});
So, the user will use the form to select the file then click submit. This all happens just fine. The form submits, the file is uploaded, and the progress shows just fine when I open my ajax view in a separate tab and keep refreshing it. What I don't understand is why the update_progress_bar function runs once until I stop the page. I'll upload a file but until I click the 'x' on my browser I won't get any of the 'hit success' in my console. After I hit stop, the console spits out the 'hit success ' plus the counter. But I shouldn't have to hit stop to do this. I need this to work when the file is uploading.
Any ideas what my problem is?
**
EDIT
**
Not sure if it makes a difference, but I am doing all this on a django development server. Which I think shouldn't have a problem with two XMLHTTPRequests in the same session.
Try this:
var $submitted = '';
$('#webfileuploadform').submit(function(){
if($submitted == 'submitted') return false; // prevents multiple submits
var freq = 1000; // freqency of update in ms
update_progress_bar();
function update_progress_bar(){
var progress_url = '/upload_progress/' + $('#id_progress_id').val(); // ajax view serving progress info
$.ajax({
dataType:"json",
url: progress_url,
success: function(data){
console.log("hit success");
},
complete:function(jqXHR, status) {
if (status == 'success') {
setTimeout(update_progress_bar, freq);
}
}
});
}
$submitted = 'submitted'; // marks form as submitted
});
As it stands, the code looks good to me. I would add some more console logging to make sure the ajax call is returning with the status you expect:
complete:function(jqXHR, status) {
console.log('got to complete, status: ', status);
if (status == 'success') {
console.log('status is success, calling setTimeout.');
setTimeout(update_progress_bar, freq);
}
}
In the ajax function I set the async setting to false:
$.ajax({
async: false,
...
});
This has solved the problem. I have no idea how. From what I understand, this setting forces the ajax request to wait until all other http requests are finished before allowing it to continue. With that being the case, I have no idea how this works. I'll keep from answering my own question in case someone knows why this is working this way...

Categories

Resources