I am making a website and I have a signup.php page where the users can register and enter their information into the mysqli database. When I do this, I am almost there, I just keep getting a problem at this one line:
ajax.send("&u="+u+"&e="+e+"&p="+p1+"&g="+g);
It is basically sending the variables in the ajax/javascript check to get ready for transport to server. But I am getting an internal server 500 error at that line. Any ideas? I will post more code if you want me to.
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
function signup(){
var u = _("username").value;
var e = _("email").value;
var p1 = _("pass1").value;
var p2 = _("pass2").value;
var g = _("gender").value;
var status = _("status");
if(u == "" || e == "" || p1 == "" || p2 == "" || g == ""){
status.innerHTML = "Fill out all of the form data";
} else if(p1 != p2){
status.innerHTML = "Your password fields do not match";
} else {
_("signupbtn").style.display = "none";
status.innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "signup.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "signup_success"){
status.innerHTML = ajax.responseText;
_("signupbtn").style.display = "block";
} else {
window.scrollTo(0,0);
_("signupform").innerHTML = "OK "+u+", check your email inbox and junk mail box at <u>"+e+"</u> in a moment to complete the sign up process by activating your account. You will not be able to do anything on the site until you successfully activate your account.";
}
}
}
type:post;
ajax.send("&u="+u+"&e="+e+"&p="+p1+"&g="+g);
}
}
A 500 Internal Server Error code is an HTTP response code, indicating that you have reached out to the server and it has responded with an error. So it doesn't appear to be a problem with your JS code (at least as far as we can tell from what you've posted).
Try doing var_dump($_REQUEST); die(); as the first line in signup.php. Does that give you a 200 status code? If so, try moving that line down your code on the server until you get back to the 500 Internal Server Error, and you've found the line that's causing the problem.
You have the question tagged with jQuery, but I don't see any jQuery in your code sample. If you do have it, try this:
function signup() {
var status = $('#status');
var signupbtn = $('#signupbtn');
var data = {
u: $('#username').val(),
e: $('#email').val(),
p: $('#pass1').val(),
g: $('#gender').val()
};
if (data.u == '' || data.e == '' || data.p == '' || data.g == '') {
status.text('Fill out all of the form data');
return;
} else if (data.p != $('#pass2').val()) {
status.text('Your password fields do not match');
return;
}
signupbtn.hide();
status.text('please wait...');
$.ajax({
type: 'post',
url: 'signup.php',
data: data,
success: function(responseText) {
if (responseText != 'signup_success') {
status.text(responseText);
signupbtn.show();
return;
}
window.scrollTo(0, 0);
$('#signupform').html('OK '+ data.u +', check your email inbox and junk mail box at <u>'+ data.e +'</u> in a moment to complete the sign up process by activating your account. You will not be able to do anything on the site until you successfully activate your account.');
},
});
}
Related
Okay so i have php code which is supposed to check if there is an existing user in database when login is attempted and send back to javascript fail or success
Php code:
<?php
require_once 'Korisnik.php';
require_once 'dbconn/korisnikdb.php';
if ($_SERVER["REQUEST_METHOD"] === "POST") {
// collect value of input field
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
$korisnik = getKorisnikByUserPass($username, $password);
if ($korisnik == null) {
$statusArray = array("status"=>"fail");
echo json_encode($statusArray);
return;
} else {
session_start();
$_SESSION["prijavljeniKorisnik"] = $username;
$statusArray = array("status"=>"success");
echo json_encode($statusArray);
return;
}
}
?>
Here i have my javascript code :
$(document).ready(function() {
var usernameInput = $('#usernameInput');
var passwordInput = $('#passwordInput');
var pogresniPodaci = $('#pogresniPodaci');
var praznaPolja = $('#praznaPolja');
pogresniPodaci.hide();
praznaPolja.hide();
$('#submitButton').on('click', function(event) {
var username = usernameInput.val();
var password = passwordInput.val();
console.log(username);
console.log(password);
if (username == '' || password == '') {
praznaPolja.show();
event.preventDefault();
return false;
}
var params = {
'username': username,
'password': password
}
$.post('loginCheck.php', params, function(data) {
console.log(data.status);
if (data.status == 'fail') {
pogresniPodaci.show();
usernameInput.val('');
passwordInput.val('');
return;
}
if (data.status == 'success') {
location.href = 'pocetna';
}
});
event.preventDefault();
return false;
});
});
http://prntscr.com/skb37r -> here you can see status after i press that button
The problem is that php code in loginCheck.php never actually executes, I tried adding echo at start of php file but it doesn't execute.
You are sending http request to localhost. Even if file doesn't exist, your localhost will return status 200, unless it's configured to throw an error.
Try this:
go to http://localhost/loginCheck.php and echo anything there.
echo "This is loginCheck";
If it echoes, you are on the right route to loginCheck file.
If it works, go to browser dev tools > network > and see request headers and find "Request URL" header. it should be "http://localhost/loginCheck.php" - the route to file you visited previously. if its not, you have to fix it in $.post request.
I'm trying to show an alert every time customer is trying to add variant quantity that is bigger than available quantity. When that's happens I see 422 response from add.js -
{status: 422, message: "Cart Error",…}
description: "All 1 Black Basic High Waisted Briefs - black / 1 are in your cart."
message: "Cart Error"
status: 422
I need to display the description for customers, how that is possible?
Here is my code -
var shopifyAjaxAddURL = '/cart/add.js';
var shopifyAjaxCartURL = '/cart.js';
var shopifyAjaxStorePageURL = '/search';
$(document).on('submit', 'form[action="/cart/add"]:not(.noAJAX, .feedback-go_to_cart)', function(e) {
var $form = $(this);
//Add to cart
$.post(shopifyAjaxAddURL, $form.serialize(), function(itemData) {
//Enable add button
$btn.html(theme.icons.tick + ' ' + {{ 'products.product.added_to_cart' | t | json }});
setTimeout(function(){
//Not added, show message
if(typeof(data) != 'undefined' && typeof(data.status) != 'undefined') {
var jsonRes = $.parseJSON(data.responseText);
window.showQuickPopup(jsonRes.description, $btn);
} else {
//Some unknown error? Disable ajax and submit the old-fashioned way.
$form.addClass('noAJAX');
$form.submit();
}
});
Your code seems bit buggy. Possible solution could be, check if the status is 422 and send the customer an alert message.
if( itemData.status === 422 ) { alert('Quantity not available in the inventory') }
Full code might look like:
var shopifyAjaxAddURL = '/cart/add.js';
var shopifyAjaxCartURL = '/cart.js';
var shopifyAjaxStorePageURL = '/search';
$(document).on('submit', 'form[action="/cart/add"]:not(.noAJAX, .feedback-go_to_cart)', function (e) {
var $form = $(this);
//Add to cart
$.post(shopifyAjaxAddURL, $form.serialize(), function (itemData) {
if( itemData.status === 422 ) { alert('Quantity not available in the inventory') }
else {
//Enable add button
$btn.html(theme.icons.tick + ' ' + {{ 'products.product.added_to_cart' | t | json }});
setTimeout(function () {
//Not added, show message
if (typeof (data) != 'undefined' && typeof (data.status) != 'undefined') {
var jsonRes = $.parseJSON(data.responseText);
window.showQuickPopup(jsonRes.description, $btn);
} else {
//Some unknown error? Disable ajax and submit the old-fashioned way.
$form.addClass('noAJAX');
$form.submit();
}
}
});
I am trying to develop a login process using json.
My problem is that when I make many login attempts , parameters are not overriden but concatenated.
Below is the code I'm writing.
I do not see where the problem is.
Thank you in advance .
var loginReq = Titanium.Network.createHTTPClient();
loginReq.onload = function() {
var json = this.responseText;
Titanium.API.info("step 1 done");
var response = JSON.parse(json);
if (response.status == true) {
Titanium.App.Properties.setString("key", response.key);
alert("Success");
} else {
alert("Email or password wrong");
}
};
function doConnVerif() {
if ($.email.value != '' && $.password.value != '') {
loginReq.open("POST", "URL");
loginReq.send({
'email' : $.email.value ,
'password' : $.password.value
});
} else {
alert("Enter email and password");
}
}
By your question I can't grasp the full aspect of the problem, but definitely a good idea would be only allow one login attempt at a time.
Something like:
var pendingRequest = false;
// ...
if(!pendingRequest) {
loginReq.send({
'email' : $.email.value ,
'password' : $.password.value
});
pendingRequest = true
}
// ...
loginReq.onload = function() {
pendingRequest = false
// ...
I am not much of a javascript programmer, I am learning so please forgive the stupid mistakes.
I am trying to save customer details using ajax (its not the jquery ajax), which returns another form for advanced details. I am using a jquery plugin for validation of input boxes. But the validation doesn't work on the form returned by ajax.
Ajax code:
function createcustomer() {
var firstname = _("firstname").value;
var lastname = _("lastname").value;
var email = _("email").value;
var phone = _("phone").value;
var status = _("status");
if (firstname == "" || lastname == "" || email == "" || phone == "") {
status.innerHTML = "Fill out all of the form data";
} else {
_("signupbtn").style.display = "none";
status.innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "save-customer.php");
ajax.onreadystatechange = function () {
if (ajaxReturn(ajax) == true) {
if (ajax.responseText != "failure") {
_("signupform").innerHTML = "";
_("advancedform").innerHTML = ajax.responseText;
} else {
window.scrollTo(0, 0);
_("signupform").innerHTML = "Error Occured";
}
}
}
ajax.send("firstname=" + firstname + "&lastname=" + lastname + "&email=" + email + "&phone=" + phone);
}
}
function ajaxObj(meth, url) {
var x = new XMLHttpRequest();
x.open(meth, url, true);
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x) {
if (x.readyState == 4 && x.status == 200) {
return true;
}
}
I have tested the ajax return code thouroughly and the jquery works independently on that form.
This is how I initiate the jquery validation plugin :
$(document).ready(function() {
$('form').validationEngine();
});
I tried putting the exact code in the createcustomer() function to reload the jquery function but it doesnt work. Is there any way I can call that jquery validation function in the ajax function?
Any help will be appreciated.
Regards
Priyanshu
I'm suspecting that your validation is trying to find a form that doesnt exists at the execution time, try putting the validation binding when you have sure that the form exists in your DOM. To achieve this you should put the validation binder:
$('form').validationEngine();
...inside the callback after the ajax loads some HTML data in the document. Like this:
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "failure"){
_("signupform").innerHTML = "";
_("advancedform").innerHTML = ajax.responseText;
$('#ajaxreturnform').validationEngine('attach'); //Here
} else {
window.scrollTo(0,0);
_("signupform").innerHTML = "Error Occured";
}
}
}
I've looked around here and found this post Attach Validation the accepted answer may inlight your problem also. Try to put the 'attach' command as a parameter to your binder as well as the #id of your form.
I have a sign-up form which prompts for the first name, last name, username, password and e-mail address. I'm using two separate $.get() methods to check if the username and e-mail address are not existing.
This is my function:
function validateSignUp() {
var firstName = $("#first-name").val();
var lastName = $("#last-name").val();
var username = $("#username").val();
var password = $("#pass").val();
var email = $("#email").val();
var passwordVerifier = $("#retype-pass").val();
var emailVerifier = $("#retype-email").val();
errorMessage = "";
var isUsernameValid = validateUsername(username);
var isError = false;
// validate first name field
if (firstName == "" || lastName == "") {
isError = true;
$("#error-message").html("All fields are required");
}
// validate password
if (validatePassword(password) == false) {
isError = true;
$("#check-password").html("Password is invalid");
}
else {
$("#check-password").html("");
}
// validate password verifier
if (passwordVerifier == password) {
if (validatePassword(passwordVerifier) == false) {
isError = true;
$("#recheck-password").html("Minimum of 6 characters and maximum of 30 characters");
}
else {
if (password != passwordVerifier) {
isError = true;
$("#recheck-password").html("Minimum of 6 characters and maximum of 30 characters ");
}
else {
$("#recheck-password").html("");
}
}
}
else {
isError = true;
$("#recheck-password").html("Passwords didn't match");
}
// validate username field
if (isUsernameValid == false) {
isError = true;
$("#check-username").html("Alphanumeric characters only");
} // if
else if (isUsernameValid == true) {
$.get("/account/checkavailabilitybyusername", { username: username },
function(data) {
if (data == "Not Existing") {
$("#check-username").html("");
}
else if (data == username) {
isError = true;
$("#check-username").html("Sorry, this username is already registered");
}
}
);
} // else
// validate e-mail address field
if (validateEmail(email) == false) {
isError = true;
$("#check-email").html("Sorry, the e-mail you typed is invalid");
} // if
else if (validateEmail(email) == true) {
$.get("/account/checkavailabilitybyemail", { email: email },
function(data) {
if (data == "Not Existing") {
$("#check-email").html("");
}
else if (data == email) {
isError = true;
$("#check-email").html("Sorry, this e-mail is already registered");
}
});
}
if (isError == true) {
return false;
}
return true;
}
When other fields are blank and the username and/or e-mail address is existing, the form is not submitted. And the callback functions of the get methods are called as well. But when I'm going to submit my form with no empty fields, it is automatically submitted without checking the username and/or e-mail by $.get(). Is there anything wrong with my function or I'm not yet discovering something. Thanks.
You need to use a full ajax() call and set the async property to false. This makes your request synchronous, i.e. it forces the browser to wait until doing anything else. Try this:
$.ajax({
url: "/account/checkavailabilitybyemail",
data: { email: email },
async: false,
success: function(data) {
if (data == "Not Existing") {
$("#check-email").html("");
} else if (data == email) {
isError = true;
$("#check-email").html("Sorry, this e-mail is already registered");
}
})
});
if (isError == true) {
return false;
}
I suggest you leverage Jquery validate with two remote rules. It's quite easy to implement and a very mature plugin. This way you can focus on other aspects of your UX and not have to re implement this validation logic should you need to validate another form in your project.
Inside your main function, you cannot directly wait for the $.get() to return. But you can move the form submission to the success callback of the AJAX call (assuming form to contain a reference to the actual form element):
$.get("/account/checkavailabilitybyusername", { username: username },
function(data) {
if (data == "Not Existing") {
$("#check-username").html("");
form.submit();
//--------------------------^
}
else if (data == username) {
isError = true;
$("#check-username").html("Sorry, this username is already registered");
}
}
);
Note however, that then the form submission depends on the AJAX to return. Most useful would be a timeout (with window.setTimeout()) and a server-side validation, if the JS doesn't respond or the user has JS disabled.