I am trying to use ajax on a registration page in order to show either succes or errors. I cannot figure out why i get "Uncaught SyntaxError: Unexpected token I " in the console. Here is the code:
$("#submit").click(function(){
var name = $('#name').val();
var surname = $('#surname').val();
var username= $('#userName').val();
var email = $('#email').val();
var country = $('#country option:selected').text();
var password1 = $('#password1').val();
var password2 = $('#password2').val();
$.ajax({
url: "ajax-api.php",
type:'post', data:{name:name, surname:surname, username:username, email:email, country:country, password1:password1, password2:password2, submit:'yes'}
}).done(function(response) {
var errors = JSON.parse(response);
if(errors != ''){
var outputString = '';
for(var key in errors){
outputString += errors[key]+'<br /><br />';
}
alertify.error(outputString);
}else{
alertify.succes('You have been registered!');
}
});
});
});
The console says the error is in line 20 (var errors = JSON.parse(response);)
EDIT: I only get the console error in the success case( alertify.succes('You have been registered!');)
Related
I've been at this all day trying to figure out how to do an XMLHTTP request after authorization but just can't for the life of me figure it out.
So far I've got the code below which authorizes the user.
var OAUTHURL = 'https://accounts.google.com/o/oauth2/auth?';
var VALIDURL = 'https://www.googleapis.com/oauth2/v1/tokeninfo?
access_token=';
var SCOPE = 'https://www.googleapis.com/auth/userinfo.profile
https://www.googleapis.com/auth/userinfo.email';
var CLIENTID = 'NOT SHOWING FOR SECURITY REASONS';
var REDIRECT = 'NOT SHOWING FOR SECURITY REASONS'
var LOGOUT = 'http://accounts.google.com/Logout';
var TYPE = 'token';
var _url = OAUTHURL + 'scope=' + SCOPE + '&client_id=' + CLIENTID + '&redirect_uri=' + REDIRECT + '&response_type=' + TYPE;
var acToken;
var tokenType;
var expiresIn;
var user;
var loggedIn = false;
function login() {
var win = window.open(_url, "windowname1", 'width=800, height=600');
var pollTimer = window.setInterval(function() {
try {
console.log(win.document.URL);
if (win.document.URL.indexOf(REDIRECT) != -1) {
window.clearInterval(pollTimer);
var url = win.document.URL;
acToken = gup(url, 'access_token');
tokenType = gup(url, 'token_type');
expiresIn = gup(url, 'expires_in');
win.close();
validateToken(acToken);
}
} catch(e) {
}
}, 500);
}
function validateToken(token) {
$.ajax({
url: VALIDURL + token,
data: null,
success: function(responseText){
getUserInfo();
loggedIn = true;
$('#loginText').hide();
$('#logoutText').show();
},
dataType: "jsonp"
});
}
function getUserInfo() {
$.ajax({
url: 'https://www.googleapis.com/oauth2/v1/userinfo?access_token=' + acToken,
data: null,
success: function(resp) {
user = resp;
console.log(user);
$('#uName').text('Welcome ' + user.name);
$('#imgHolder').attr('src', user.picture);
},
dataType: "jsonp"
});
}
//credits: http://www.netlobo.com/url_query_string_javascript.html
function gup(url, name) {
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\#&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( url );
if( results == null )
return "";
else
return results[1];
}
function startLogoutPolling() {
$('#loginText').show();
$('#logoutText').hide();
loggedIn = false;
$('#uName').text('Welcome ');
$('#imgHolder').attr('src', 'none.jpg');
}
The code works fine as far as the login goes. It's after logging in that I don't know what to do. I've tried multiple ideas and have gotten nowhere. Any ideas on how I can call tags from tag manager in "readonly" mode after this login?
Hi I just decided to try using the JavaScript web app method and was able to get this working. If you run into the same issue using the ajax version here is the documentation! Make sure to select the JavaScript tab or you can try the oAuth2.
https://developers.google.com/identity/protocols/OAuth2UserAgent
How do I trim any dots before #mail.com? I am doing jQuery email validation and need to get rid of all the dots from username.
$('document').ready(function(){
var email_state = false;
$('#email').on('keyup', function(){
var email = $('#email').val();
if (email == '') {
email_state = false;
return;
}
$.ajax({
url: 'index.php',
type: 'post',
data: {
'email_check' : 1,
'email' : email,
},
success: function(response){.....
Use .replace(/\./g, "") for the part before #
function removeDots(email){
var email_s = email.split("#");
return email_s[0].replace(/\./g, "")+"#"+email_s[1];
}
var email = "some.emai.l#mail.com";
console.log(removeDots(email));
In your code's context
function removeDots(email) {
var email_s = email.split("#");
return email_s[0].replace(/\./g, "") + "#" + email_s[1];
}
var email = "some.emai.l#mail.com";
console.log(removeDots(email));
$('document').ready(function() {
var email_state = false;
$('#email').on('keyup', function() {
var email = $('#email').val();
email = removeDots(email); // call function here to remove dots
if (email == '') {
email_state = false;
return;
}
// Rest of your code
});
// Rest of your code
});
Regex: \.(?![^#]+$)
One line code: email.replace(/\.(?![^#]+$)/gy, '')
function myFunction() {
console.clear()
var s = document.getElementById("input").value;
console.log(s.replace(/\.(?![^#]+$)/g, ''));
}
<form action="javascript:myFunction()">
<input id="input" type="text" value="bla.bla.bla.#mail.net.com"><br><br>
<input type="submit" value="Submit">
</form>
First get the username of email using String.prototype.split() then remove all the . using .replace() and /\./g. Below is an example:
var email = "abc.d.e#mail.com";
var splitted = email.split("#");
console.log(splitted[0].replace(/\./g,"") + "#" + splitted[1]);
For updated question:
var email_state = false;
$('#email').on('keyup', function(){
var email = $('#email').val();
if (email == '') {
email_state = false;
var splitted = email.split("#");
email = splitted[0].replace(/\./g,"") + "#" + splitted[1];
}
}
This is my code:
$('body').on('click', '.update_contact_profile', function (){
var url = $("#ajaxUrl").val();
var ids = $(this).closest("div").nextAll(".contact-extra-info").find(".contact-ids").attr("id");
ids = ids.split("-")
var contactId = ids[0];
var customerId = ids[1];
var postDataUpdate = [];
$(this).closest("div").nextAll(".update_elements").find(".value :input").each(function(i, itemVal){
if ($(this).val()) {
postDataUpdate[''+$(this).attr('id')+''] = $(this).val();
}
});
var request = $.ajax({
url: url,
method: "POST",
data: {
id : contactId,
contact : postDataUpdate,
form_key : FORM_KEY,
customerId : customerId
}
});
request.success(function( text ) { // replace the ajax_wrapper with the new one
$(".ajax_wrapper").replaceWith(text);
$("#contact_form").find('select').selectize();
});
request.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
});
My problem is that this var postDataUpdate it didn't passed to ajax. On firebug the contact doesn't appear. If I do console.log(postDataUpdate) before my ajax request i got my array .
So any idea about this ?
postDataUpdate should be an object, instead of an array:
[..]
var postDataUpdate = {};
$(this).closest("div").nextAll(".update_elements").find(".value :input").each(function(i, itemVal){
if ($(this).val()) {
postDataUpdate[''+$(this).attr('id')+''] = $(this).val();
}
});
[..]
Check this snippet:
var asArray = [];
asArray[1] = "foo";
asArray["foo"] = "bar";
console.log("asArray:");
console.log(asArray);
var asObject = {};
asObject[1] = "foo";
asObject["foo"] = "bar";
console.log("asObject:");
console.log(asObject);
I have been getting an error when I try to post a message back.
messages.jsp
function success(data) {
$("#form" + data.target).toggle();
$("#alert" + data.target).text("Message sent.")
startTimer();
}
function error(data) {
alert("Error sending message");
}
function sendMessage(i, name, email){
var text = $("#textbox" + i).val();
$.ajax({
type: "POST",
url: '<c:url value="/sendmessage" />',
data: JSON.stringify({"target": i, "text": text, "name": name, "email": email}),
success: success,
error: error,
contentType: "application/json",
dataType: "json"
});
}
function showMessages(data){
$("div#messages").html("");
for(var i=0; i<data.messages.length; i++) {
var message = data.messages[i];
var messageDiv = document.createElement("div");
messageDiv.setAttribute("class", "message");
var subjectSpan = document.createElement("span");
subjectSpan.setAttribute("class", "subject");
subjectSpan.appendChild(document.createTextNode(message.subject));
var contentSpan = document.createElement("span");
contentSpan.setAttribute("class", "contentText");
contentSpan.appendChild(document.createTextNode(message.content));
var nameSpan = document.createElement("span");
nameSpan.setAttribute("class", "nameSpan");
nameSpan.appendChild(document.createTextNode("From: "+ message.name + '('));
var link = document.createElement("a");
link.setAttribute("class", "replylink");
link.setAttribute("href", "#");
link.setAttribute("onClick", "showReply(" + i + ")");
link.appendChild(document.createTextNode(message.email));
nameSpan.appendChild(link);
nameSpan.appendChild(document.createTextNode(")"));
var alertSpan = document.createElement("span");
alertSpan.setAttribute("class", "alert");
alertSpan.setAttribute("id", "alert" + i);
var replyForm = document.createElement("form");
replyForm.setAttribute("class", "replyForm");
replyForm.setAttribute("id", "form" + i);
var textarea = document.createElement("textarea");
textarea.setAttribute("class", "replyArea");
textarea.setAttribute("id", "textbox" + i);
var replyButton = document.createElement("input");
replyButton.setAttribute("class", "replyButton");
replyButton.setAttribute("type", "button");
replyButton.setAttribute("value", "reply");
replyButton.onclick = function(j, name, email) {
return function() {
sendMessage(j, name, email);
}
}(i, message.name, message.email);
replyForm.appendChild(textarea);
replyForm.appendChild(replyButton);
messageDiv.appendChild(subjectSpan);
messageDiv.appendChild(contentSpan);
messageDiv.appendChild(nameSpan);
messageDiv.appendChild(alertSpan);
messageDiv.appendChild(replyForm);
$("div#messages").append(messageDiv);
}
}
controller.java
#RequestMapping(value="/sendmessage", method=RequestMethod.POST, produces="application/json")
#ResponseBody
public Map<String, Object> sendMessages(Principal principal, #RequestBody Map<String, Object> data)
{
String text = (String)data.get("text");
String name = (String)data.get("name");
String email = (String)data.get("email");
Integer target = (Integer)data.get("target");
System.out.println(name + " , " + email + " , " + text);
Map<String, Object> returnVal = new HashMap<String, Object>();
returnVal.put("success", true);
returnVal.put("target", target);
return returnVal;
}
I can't post the message.
Any help or reason why I keep getting this error?
jquery.js:4 POST http://localhost:8080/spring/sendmessage 403 (Forbidden) send # jquery.js:4 ajax # jquery.js:4 sendMessage # messagesView:32 (anonymous function) # messagesView:90
I know that I should disable CSRF protection. But I don't know how to connect this function and ajax request. I've tried many ways to do that but none of them don't work.
$(function () {
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
$(document).ajaxSend(function(e, xhr, options) {
xhr.setRequestHeader(header, token);
});
});
Im having a problem with my mobile app i do not know how to solve it.
when i push a button that gets data from a database, i parse it in json and when i want to use it in my app i get the undefined. Hoe can i make it so i do not get the undifined.
Note
I only get the undefind when the database is empty.
This is the code that i use
subjectButton.addEventListener('click', function(e) {
Subjects.getSubjects(url, function(response) {
if(response == '') {
alert('There where no subjects found');
} else {
subjectView.remove(subjectsLabel);
var data = JSON.parse(response);
if(data != 'undefined') {
var subjectNameButton = [];
var subjectEditButton = [];
var subjectDeleteButton = [];
for(i in data) {
id = data[i].id;
var subject = data[i].subject;
var year = data[i].year;
var status = data[i].status;
var color;
Ti.API.info('id: ' + id);
Ti.API.info('type id: '+ typeof id);
Can someone explain to me how i can make it so i don't get the undefined
Like #0101 said json can't return undefined so your problem is somewhere else.
I know this is not the best solution but it seems to work for me:
subjectButton.addEventListener('click', function(e) {
Subjects.getSubjects(url, function(response) {
if(response == '') {
alert('There where no subjects found');
} else {
subjectView.remove(subjectsLabel);
var data = JSON.parse(response);
var subjectNameButton = [];
var subjectEditButton = [];
var subjectDeleteButton = [];
for(i in data) {
id = data[i].id;
var subject = data[i].subject;
var year = data[i].year;
var status = data[i].status;
var color;
Ti.API.info('id: ' + id);
if(id != undefined) {
//Your code here
} else {
alert('There where no subjects found');
}
}
}
});
});
So here you have a check if one of the variables returns undefined or not. If it isn't undefined it will run your code else it will give you / the user an alert message
You will never get "undefined" from JSON.parse. The error must occurred somewhere else. Try this:
Subjects.getSubjects(url, function(response) {
if(!response) {
alert('There where no subjects found');
}
else {
subjectView.remove(subjectsLabel); // You probably should move this after JSON.parse
try {
var data = JSON.parse(response),
subjectNameButton = [],
subjectEditButton = [],
subjectDeleteButton = [];
for (i in data) { // Global i?
id = data[i].id; // Global too?
var subject = data[i].subject;
var year = data[i].year;
var status = data[i].status;
var color;
Ti.API.info('id: ' + id);
Ti.API.info('type id: '+ typeof id);
// ...
}
}
catch(e) {
console.log("Invalid JSON")
};
// ...
}
}