Submit form via Ajax - javascript

So, I followed a tutorial here to be able to submit a form with ajax. I followed the tutorial exactly (atleast I thought I did) and when I try to submit the form the page just refreshes and it never gets to the php script to send it to the database.
The script that I am using is below:
$(function () {
$(".button").click(function () {
$(function () {
$('.error').hide();
$("#submit_btn").click(function () {
//validate and process form here
$('.error').hide();
var firstname = $("input#firstname").val();
if (firstname == "") {
$("label#firstname_error").show();
$("input#firstname").focus();
return false;
}
var lastname = $("input#lastname").val();
if (lastname == "") {
$("label#lastname_error").show();
$("input#lastname").focus();
return false;
}
var email = $("input#email").val();
if (email == "") {
$("label#email_error").show();
$("input#email").focus();
return false;
}
var pin = $("input#parent_pin").val();
if (pin == "") {
$("label#parent_pin_error").show();
$("input#parent_pin").focus();
return false;
}
var login = $("input#login").val();
if (login == "") {
$("label#login_error").show();
$("input#login").focus();
return false;
}
var passwd = $("input#passwd").val();
if (passwd == "") {
$("label#passwd_error").show();
$("input#passwd").focus();
return false;
}
var cpasswd = $("input#cpasswd").val();
if (cpasswd == "") {
$("label#cpasswd_error").show();
$("input#cpasswd").focus();
return false;
}
var user_type = $("input#user_type").val();
if (user_type == "") {
$("label#user_type_error").show();
$("input#user_type").focus();
return false;
}
var dataString = 'firstname=' + firstname + '&lastname=' + lastname + '&email=' + email + '&parent_pin=' + pin + '&login='
login + '&passwd='
passwd + 'user_type' = user_type;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "studentAccess/files/AddNewUser.php",
data: dataString,
success: function () {
$('#form-body').html("<div id='message'></div>");
$('#message').html("<h2>New User Added Successfully!</h2>");
}
});
});
});
});
});
The error that I am receiving in Google Chrome's console is:
Uncaught SyntaxError: Unexpected identifier AddNewUser.js:65
Line 65 would be:
var dataString = 'firstname=' + firstname + '&lastname=' + lastname + '&email=' + email + '&parent_pin=' + pin + '&login=' login + '&passwd=' passwd + 'user_type' = user_type;
I'm not sure how to fix this problem because I don't know what the error means. Any help would be great!
UPDATE
<?php
$con = mysqli_connect("");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "INSERT INTO members (firstname, lastname, email, login, psswd, user_type)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[email]', '$_POST[login]', '$_POST[psswd]', '$_POST[user_type]')";
if (!mysqli_query($con, $sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>

You have missed + symbols in the #65 line
Should be
var dataString = 'firstname=' + firstname + '&lastname=' + lastname + '&email=' + email + '&parent_pin=' + pin + '&login=' + login + '&passwd=' + passwd + '&user_type=' + user_type;
Please read http://en.wikipedia.org/wiki/JavaScript_syntax
Remove $(function () { in .button click handler. Now it just registers a handle on button click but not executes it

At the very end of that line you have:
'user_type' = user_type;
It needs to be:
'&user_type=' + user_type;
You may also need to add return false; after your ajax to prevent the page from refreshing (and clearing out your form).
$.ajax({
type: "POST",
url: "studentAccess/files/AddNewUser.php",
data: dataString,
success: function () {
$('#form-body').html("<div id='message'></div>");
$('#message').html("<h2>New User Added Successfully!</h2>");
}
});
return false; //Keep page from refreshing
Further EDIT:
You also have a .click() embedded in a .click(). You cannot click two buttons at one time. You need to change this:
$(function () {
$(".button").click(function () {
$(function () {
$('.error').hide();
$("#submit_btn").click(function () {
to this...
$(function () {
$('.error').hide();
$("#submit_btn").click(function (e) {
e.preventDefault();
...

In the below line, it should be '&user_type=' + user_type; instead of 'user_type' = user_type;
var dataString = 'firstname=' + firstname + '&lastname=' + lastname + '&email=' + email + '&parent_pin=' + pin + '&login=' login + '&passwd=' passwd + 'user_type' = user_type;
Also, if the button is a submit button, you should prevent the default form submit action using event.preventDefault(); within the button's click event.
In addition, the first two lines of code is not required. I have commented them out.
/*$(function () {
$(".button").click(function () {*/
$(function () {
$('.error').hide();
$("#submit_btn").click(function (event) {
event.preventDefault();
//rest of your current validation code should be put here.
});
});

Related

Cannot retrieve data from PHP array, which is returned by a function() that uses JQuery Ajax

I have this "click Listener" that calls and sends a userId parameter to the function-"getModalData" which then returns an array value to the variable-"arrayedUserData".
$('body').on('click', '.openModal', function () {
var userId = $(this).val(),
btnText = $(this).text(),
btnClass = '',
colorCode = '',
arrayedUserData = getModalData(userId);
if (btnText === "Delete") {
btnClass = 'danger';
colorCode = '#d9534f';
} else {
btnClass = 'warning';
colorCode = '#f0ad4e';
}
$('#actionBtn').removeClass().addClass('btn btn-' + btnClass).text(btnText);
$('#modalTitle').text('Confirm ' + btnText);
$('#S-modalbody p').text('Are you sure you want to ' + btnText + ' user: ');
$('#S-modalbody h4').css('color', colorCode).text(userId + " - " + arrayedUserData.LastName + ", " + arrayedUserData.FirstName);
});
This is the function-"getModalData". The returned php array from the Ajax's "success" will then be passed to the variable-"UserData" that is then returned by the function.
function getModalData(passedUserId) {
var UserData;
$.ajax(
{
type: "POST",
url: "get/get_modal_data.php",
data: { passedUserId: passedUserId },
dataType: "json",
success: function (data) {
UserData = data;
}
}
);
return UserData;
}
this is the "get_modal_data.php".
<?php
include "../includes/connect.php";
if (isset($_POST['passedUserId'])) {
$UserId = mysqli_real_escape_string($con, $_POST['passedUserId']);
$getUserData = mysqli_query($con, "SELECT * FROM tblUserAccounts WHERE uaUserId = '".$UserId."'");
$uaRow = mysqli_fetch_assoc($getUserData);
$UserDataArr = array("UserId" => $uaRow['uaUserId'],
"EmailAddress" => $uaRow['uaEmailAddress'],
"FirstName" => $uaRow['uaFirstName'],
"LastName" => $uaRow['uaLastName'],
"BirthDate" => $uaRow['uaBirthDate'],
"Address" => $uaRow['uaAddress'],
"Gender" => $uaRow['uaGender'],
"ContactNumber" => $uaRow['uaContactNumber'],
"BloodTypeId" => $uaRow['uaBloodTypeId'],
"AccountStatus" => $uaRow['uaAccountStatus'],
);
echo json_encode($UserDataArr);
exit();
}
?>
this error appears on the console:
Uncaught TypeError: Cannot read property 'LastName' of undefined get_user_accounts.js:66
this is the line 66 of get_user_accounts.js, which is present on the "click listener".
$('#S-modalbody h4').css('color', colorCode).text(userId + " - " + arrayedUserData.LastName + ", " + arrayedUserData.FirstName);
but, I am confused because the php array appears on the browser's Network Response:
Successful Connection{"UserId":"1","EmailAddress":"paulanselmendoza#gmail.com","FirstName":"Paul Ansel","LastName":"Mendoza","BirthDate":"1998-12-17","Address":"Phase 1B Block 8 Lot 20 Olivarez Homes South, Sto. Tomas, Binan City, Laguna","Gender":"Male","ContactNumber":"2147483647","BloodTypeId":"0","AccountStatus":"ACTIVE"}
Did you see that you get: Successful Connection before the JSON data? You have to remove that, if not it will be an invalid JSON response. The code you have shared doesn't have the particular stuff.
I believe you have to check your database connection, where on successful connection, it is set to output Successful Connection, which breaks your response. Please remove that bit of code.
include "../includes/connect.php";
It can be something like:
$conn = mysqli_connect() or die("Error");
echo "Successful Connection";
Because getModalData fucntion return the UserData before it asign by ajax(UserData = data;). use a callback function:
using callbacks
function getModalData(passedUserId,callback) {
$.ajax(
{
type: "POST",
url: "get/get_modal_data.php",
data: { passedUserId: passedUserId },
dataType: "json",
success: function (data) {
callback(data);
}
}
);
}
$('body').on('click', '.openModal', function () {
var userId = $(this).val(),
btnText = $(this).text(),
btnClass = '',
colorCode = '';
getModalData(userId, function (arrayedUserData) {
if (btnText === "Delete") {
btnClass = 'danger';
colorCode = '#d9534f';
} else {
btnClass = 'warning';
colorCode = '#f0ad4e';
}
$('#actionBtn').removeClass().addClass('btn btn-' + btnClass).text(btnText);
$('#modalTitle').text('Confirm ' + btnText);
$('#S-modalbody p').text('Are you sure you want to ' + btnText + ' user: ');
$('#S-modalbody h4').css('color', colorCode).text(userId + " - " + arrayedUserData.LastName + ", " + arrayedUserData.FirstName);
});
});

Javascript: return false from asynchronous function

I'm having some real trouble trying to get this form to work properly. The form should validate each field and successfully charge a credit card before submitting.
The issue is that I can't pass my return value to the parent function to prevent the form from submitting. I read this post and tried using deferred objects, a callback function, and placing return statements all over the place but I'm missing something. I've been at this for about a week and the frustration is getting to me. Could anyone help me with this? I would greatly appreciate it and thanks!
HTML:
<form onSubmit="return billingfunction1();" name="form5" method="post" action="" id="newform">
</form>
JS: (trimmed to size)
function billingfunction1() {
var first_name = $.trim($("#first_name").val());
var last_name = $.trim($("#last_name").val());
var cardtype = $.trim($("#cardtype").val());
var maxlen = 16;
var digits = cardnumber.toString().length;
var submiteval;
if (cardtype == '') {
// alert("Enter Card Type");
$('#cardtype_msg').html('Enter Card Type.');
$('#cardtype').css('border','1px solid #28a616');
$('#cardtype').css('box-shadow','0 0 3px 0 #28a616');
return false;
} else if (nameoncardfirst == '') {
//alert("Enter Name On Card");
$('#nameoncardfirst_msg').html('Enter First Name On Card.');
$('#nameoncardfirst').css('border','1px solid #28a616');
$('#nameoncardfirst').css('box-shadow','0 0 3px 0 #28a616');
return false;
} else if (nameoncardlast == '') {
//alert("Enter Name On Card");
$('#nameoncardlast_msg').html('Enter Last Name On Card.');
$('#nameoncardlast').css('border','1px solid #28a616');
$('#nameoncardlast').css('box-shadow','0 0 3px 0 #28a616');
return false;
} else {
function foo(callback) {
return $.ajax({
url: 'edit_billing2.php',
data: "nameoncardfirst=" + nameoncardfirst+ "&nameoncardlast=" + nameoncardlast + "&street_address2=" + street_address2 +"&city2=" + city2 +"&state=" + state +"&zip=" + zip + "&cardnumber=" + cardnumber + "&expirationdate=" + expirationdate + "&cvv=" + cvv + "&cardtype=" + cardtype+ "&amount=" + amount + "&gender=" + gender + "&first_name=" + first_name + "&last_name=" + last_name + "&address=" + address + "&address2=" + address2 + "&city=" + city + "&post_code=" + post_code + "&country=" + country + "&mobile=" + mobile + "&email=" + email + "&newsletter=" + newsletter + "&make=" + vehicle + "&model=" + model + "&model_year=" + model_year,
success: callback
});
}
function myCallback(response) {
console.log("Success response. Attempting to authorize payment.");
//alert(response);
result = response.split('_');
//alert("Successfully Saved");
alert(result[0]);
if(result[0]=="Your Payment has completed successfully")
{
console.log("Payment Success");
submiteval = true;
}
else
{
console.log("Payment Failed, Aborting form submission.");
submiteval = false;
}
return submiteval;
}
console.log("Valid inputs: attempting to pass via AJAX");
foo(myCallback).done(function(response) {
return submiteval;
});
}
EDIT:
I tried using event.preventDefault() to stop the submission and handle the submission manually, but then the form would reload the current page and skip over some PHP I had before the form code that I neglected to mention:
if (isset($_POST[Submit]))
{
// do registration things
}
I ended up changing the $_POST[Submit] to
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
// do registration things
}
removing the onsubmit attribute from my form:
<form name="form5" method="post" action="" id="newform">
and moving it to my submit button:
<input onClick="return billingfunction1();" type="submit" value="Submit"
name="Submit" class="submit_btn">
My new callback function will submit the form manually under the success condition:
function myCallback(response) {
console.log("Success response. Attempting to authorize payment.");
result = response.split('_');
alert(result[0]);
if(result[0]=="Your Payment has completed successfully") {
console.log("Payment Success");
document.forms["form5"].submit();
} else {
console.log("Payment Failed, Aborting form submission.");
}
}
Everything seems to be working as it should. Thanks so much for your help!
You can just add a submit listener to the form
$("#newform").submit(function(){...})
Prevent the default action
event.preventDefault()
And submit the form manually
$("#newform").submit()
if the condition is meet when the response to the AJAX call comes back.
emphasized text
function billingfunction1() {
var first_name = $.trim($("#first_name").val());
var last_name = $.trim($("#last_name").val());
var cardtype = $.trim($("#cardtype").val());
var maxlen = 16;
var digits = cardnumber.toString().length;
var submiteval;
if (cardtype == '') {
// alert("Enter Card Type");
$('#cardtype_msg').html('Enter Card Type.');
$('#cardtype').css('border','1px solid #28a616');
$('#cardtype').css('box-shadow','0 0 3px 0 #28a616');
return false; //show error to the user instead of returning false
} else if (nameoncardfirst == '') {
//alert("Enter Name On Card");
$('#nameoncardfirst_msg').html('Enter First Name On Card.');
$('#nameoncardfirst').css('border','1px solid #28a616');
$('#nameoncardfirst').css('box-shadow','0 0 3px 0 #28a616');
return false; //show error to the user instead of returning false
} else if (nameoncardlast == '') {
//alert("Enter Name On Card");
$('#nameoncardlast_msg').html('Enter Last Name On Card.');
$('#nameoncardlast').css('border','1px solid #28a616');
$('#nameoncardlast').css('box-shadow','0 0 3px 0 #28a616');
return false; //show error to the user instead of returning false
} else {
$.ajax({
url: 'edit_billing2.php',
data: "nameoncardfirst=" + nameoncardfirst+ "&nameoncardlast=" + nameoncardlast + "&street_address2=" + street_address2 +"&city2=" + city2 +"&state=" + state +"&zip=" + zip + "&cardnumber=" + cardnumber + "&expirationdate=" + expirationdate + "&cvv=" + cvv + "&cardtype=" + cardtype+ "&amount=" + amount + "&gender=" + gender + "&first_name=" + first_name + "&last_name=" + last_name + "&address=" + address + "&address2=" + address2 + "&city=" + city + "&post_code=" + post_code + "&country=" + country + "&mobile=" + mobile + "&email=" + email + "&newsletter=" + newsletter + "&make=" + vehicle + "&model=" + model + "&model_year=" + model_year,
success: myCallback
});
function myCallback(response) {
console.log("Success response. Attempting to authorize payment.");
//alert(response);
result = response.split('_');
//alert("Successfully Saved");
alert(result[0]);
if(result[0]=="Your Payment has completed successfully")
{
console.log("Payment Success");
submiteval = true;
document.forms["form5"].submit();
}
else
{
console.log("Payment Failed, Aborting form submission.");
submiteval = false; //show error to the user instead of returning false
}
return submiteval;
}
}
<form name="form5" method="post" action="" id="newform">
<input type="button" value ="submit" onClick="billingfunction1();" />
</form>
Assign billingfunction1 to onclick event instead of submit.
use document.forms["form5"].submit() to manually submit the form after validating the response from server.
$.ajax has a option named beforeSend(func). U can validate ur data in this func, and return false to cancel ajax.

get message without re open div

Im working in a chat system very simple. But i have a problem. I can only get the other user messages if i close and re open the chat conversation div, then the message appears.
How can I solve this? The problem should be in this piece of code. As I am not very comfortable with ajax I ask for your help.
JS:
$(document).ready(function(){
var snd = new Audio("images/new_msg.wav");
var open=Array();
$("#jd-chat .jd-online_user").click(function(){
var user_name = $.trim($(this).text());
var id = $.trim($(this).attr("id"));
if($.inArray(id,open) !== -1 )
return
open.push(id);
$("#jd-chat").prepend('<div class="jd-user">\
<div class="jd-header" id="' + id + '">' + user_name + '<span class="close-this"> X </span></div>\
<div class="jd-body"></div>\
<div class="jd-footer"><input id="textareabox" placeholder="escrever..."></div>\
</div>');
$.ajax({
url:'chat.class.php',
type:'POST',
data:'get_all_msg=true&user=' + id ,
success:function(data){
$("#jd-chat").find(".jd-user:first .jd-body").append("<span style='display:block' class='me'> " + data + "</span>");
}
});
});
$("#jd-chat").delegate(".close-this","click",function(){
removeItem = $(this).parents(".jd-header").attr("id");
$(this).parents(".jd-user").remove();
open = $.grep(open, function(value) {
return value != removeItem;
});
});
$("#jd-chat").delegate(".jd-header","click",function(){
var box=$(this).parents(".jd-user,.jd-online");
$(box).find(".jd-body,.jd-footer").slideToggle();
});
$("#search_chat").keyup(function(){
var val = $.trim($(this).val());
$(".jd-online .jd-body").find("span").each(function(){
if ($(this).text().search(new RegExp(val, "i")) < 0 )
{
$(this).fadeOut();
}
else
{
$(this).show();
}
});
});
$("#jd-chat").delegate(".jd-user input","keyup",function(e){
if(e.keyCode == 13 )
{
var $cont = $('.jd-body');
var box=$(this).parents(".jd-user");
var msg=$(box).find("input").val();
var to = $.trim($(box).find(".jd-header").attr("id"));
$.ajax({
url:'chat.class.php',
type:'POST',
data:'send=true&to=' + to + '&msg=' + msg,
success:function(data){
$('#textareabox').val('');
$(box).find(".jd-body").append("<span style='display:block' class='me'> " + msg + "</span>");
$cont[0].scrollTop = $cont[0].scrollHeight;
$cont.append('<span>' + $(this).val() + '</span>');
$cont[0].scrollTop = $cont[0].scrollHeight;
$(this).val('');
}
});
}
});
function message_cycle()
{
$.ajax({
url:'chat.class.php',
type:'POST',
data:'unread=true',
dataType:'JSON',
success:function(data){
$.each(data , function( index, obj ) {
var user = index;
var box = $("#jd-chat").find("div#2").parents(".jd-user");
$(".jd-online").find(".light").hide();
$.each(obj, function( key, value ) {
if($.inArray(user,open) !== -1 )
$(box).find(".jd-body").append("<span style='display:block' class='other'> " + value + "</span>");
else
snd.play();
$(".jd-online").find("span#" + user + " .light").show();
});
});
}
});
}
setInterval(message_cycle,1000);
});
How messages are displayed when you first open the chat conv div ?
I'm assuming message_cycle() is supposed to display new messages in your div every second, i suppose your problem is here...
I'm not really confortable with this :
var box = $("#jd-chat").find("div#2").parents(".jd-user");
A div can't have an id starting with a number, you need <div id="chat2"> instead of <div id="2">.
After your line add a console.log('Box found : '+box.length) ; just to make sure your box is correctly found in message_cycle.

Document.Ready function doesn't seem to be working

Right now I have username and password saved in cookies. My goal is to send that data to my server and then the server will send back response and I will display the response on my webpage. But before I do that I used alert() to see if it is working.
I think something is wrong with the JS:
$(document).ready(function () {
var messageType = "3";
var cookie_name = "username";
var cookie_name2 = "password";
var YouWrote = getName(cookie_name);
var YouWrote2 = getName2(cookie_name2);
var userName = YouWrote;
var password = YouWrote2;
auth(messageType, userName, password);
});
function auth(messageType, userName, password) {
$.ajax({
type: "POST",
//SEND TO SERVER URL
url: "######",
dataType: 'json',
async: false,
data: '{"messageType": "' + messageType + '", "userName": "' + userName + '", "password" : "' + password + '"}',
error: function (xhr, error) {
alert('Error!');
},
success: function (data, textStatus, jqXHR) {
alert(data.details + '\nHello ' + data.clientInfo.firstName + ' ' + data.clientInfo.lastName + '. \nBalance:' + data.clientInfo.balance);
}
})
}
These two functions will help me get the cookie data saved (this works, I have tested it):
function getName() {
if (document.cookie) {
index = document.cookie.indexOf(cookie_name);
if (index != -1) {
namestart = (document.cookie.indexOf("=", index) + 1);
nameend = document.cookie.indexOf(";", index);
if (nameend == -1) {
nameend = document.cookie.length;
}
YouWrote = document.cookie.substring(namestart, nameend);
return YouWrote;
}
}
}
function getName2() {
if (document.cookie) {
index = document.cookie.indexOf(cookie_name2);
if (index != -1) {
namestart = (document.cookie.indexOf("=", index) + 1);
nameend = document.cookie.indexOf(";", index);
if (nameend == -1) {
nameend = document.cookie.length;
}
YouWrote2 = document.cookie.substring(namestart, nameend);
return YouWrote2;
}
}
}
I turned my server off on purpose because I want to see if it will show alert("Error!"). It doesn't which means the functions aren't running properly in the document.ready.
Is there an obvious issue that I'm missing? Any help will be much appreciated.
Your functions will need to have input argument specified:
function getName(cookie_name){ ... };
function getName2(cookie_name2){ ... };

jquery click does not work

Anyone have an idea why my jQuery click won't work?
It's attached to a hyperlink.
jQuery(function ($) {
$(".delete").click(function(e) {
alert("Hello");
});
var socket = io.connect();
var $messageForm = $('#sendmessage');
var $messageTitle = $('#title');
var $messageBox = $('#message');
var $chat = $('#chat');
$messageForm.click(function (e) {
if ($.trim($("#title").val()).length === 0) {
alert('You must provide valid input');
$messageTitle.val('');
$messageBox.val('');
return false;
}
if ($.trim($("#message").val()).length === 0) {
alert('You must provide valid input');
$messageTitle.val('');
$messageBox.val('');
return false;
} else {
e.preventDefault();
socket.emit('send message',
'<b>' + $messageTitle.val() + '</b>' + ' - '
+ $messageBox.val() + ' ' + '[' +
'<a class="delete" href="#">Delete</a>' + ']');
$messageTitle.val('');
$messageBox.val('');
}
});
socket.on('new message', function (data) {
$chat.prepend(data + "<br/>");
});
});
Since the delete links are dynamically generated, you need to use event delegation:
$('#chat').on('click', '.delete', function(e) {
alert("Hello");
});
Hello try to modify your jquery initialization like this:
(function($){ }(jQuery)
If your script still doesn't fire the click event, check if $messageForm exists, using console.log($messageForm). You can modify var $messageForm in var messageForm from what I seen that variable does not need a scope so wide. I hope this could help you

Categories