Json response not showing in div - php

Hopefully someone can help me here, I am tired of banging my head on the desk. I am not sure why the json response isn't showing up on the div below the form. I can see the response in my firebug debugger(Firefox debugger), but nothing shows up in div.
I've the main register.php that contains the form and javascript and calls another register.php file with the php code that calls the registration function. I can create new account and data files to the database without any problem, but I am unable to get the response back in my div. Please help!
register.php
<body>
<div class="logo"></div>
<div class="form">
<form id="register" method="post">
<input type="text" name="email" id="email" placeholder="Email Address" /><br/><br/>
<input type="text" name="username" id="username" placeholder="Username" />
<input type="password" name="password" id="password" placeholder="Password" />
<input type="submit" id="register" value="Register" />
</form>
</div>
<div class="small">
I already have an account<br/>
</div>
<div id="message"></div>
<script type="text/javascript">
$(document).ready(function(){
var myForm = $('#register');
myForm.validate({
errorClass: "errormessage",
onkeyup: false,
errorClass: 'error',
validClass: 'valid',
rules: {
email: { required: true, email: true, minlength: 3, maxlength: 100 },
username: { required: true, minlength: 3, maxlength: 30 },
password: { required: true, minlength: 3, maxlength: 100 }
},
errorPlacement: function(error, element)
{
var elem = $(element),
corners = ['right center', 'left center'],
flipIt = elem.parents('span.right').length > 0;
if(!error.is(':empty')) {
elem.filter(':not(.valid)').qtip({
overwrite: false,
content: error,
position: {
my: corners[ flipIt ? 0 : 1 ],
at: corners[ flipIt ? 1 : 0 ],
viewport: $(window)
},
show: {
event: false,
ready: true
},
hide: false,
style: {
classes: 'ui-tooltip-red'
}
})
.qtip('option', 'content.text', error);
}
else { elem.qtip('destroy'); }
},
success: $.noop,
})
});
$("#register").submit(function(event) {
if($("#register").valid()) {
event.preventDefault();
var $form = $( this ),
mail = $form.find('input[name="email"]').val(),
user = $form.find('input[name="username"]').val(),
pass = $().crypt({method:"sha1",source:$().crypt({method:"sha1",source:$form.find('input[name="password"]').val()})});
$.post("inc/action.php?a=register", {email: mail, username: user, password: pass},
function(data) {
$("#message").html('<p> code: ' + data.error + '</p>');
$("#message").append('<p> message: ' + data.message + '</p>');
}, "json"
);
}
else
{
$("[id^=ui-tooltip-]").effect("pulsate", {times: 3}, 300);
return false;
}
});
</script>
</body>
register.php
<?php
if(isset($_POST['email'])) { $email = $_POST['email']; } else { echo 1; exit(); }
if(isset($_POST['username'])) { $username = $_POST['username']; } else { echo 1; exit(); }
if(isset($_POST['password'])) { $password = $_POST['password']; } else { echo 1; exit(); }
$register = $auth->register($email, $username, $password);
$return = array();
switch($register['code'])
{
case 0:
$return['error'] = 1;
$return['message'] = "You are temporarily locked out of the system. Please try again in 30 minutes.";
break;
case 1:
$return['error'] = 1;
$return['message'] = "Username / Password is invalid";
break;
case 2:
$return['error'] = 1;
$return['message'] = "Email is already in use";
break;
case 3:
$return['error'] = 1;
$return['message'] = "Username is already in use";
break;
case 4:
$return['error'] = 0;
$return['message'] = "Account created ! Activation email sent to " . $register['email'];
break;
default:
$return['error'] = 1;
$return['message'] = "System error encountered";
break;
}
$return = json_encode($return);
echo $return;

Add header('Content-Type: application/json') before returning the json-encoded data.
in json.php
<?php
$data['error']=1;
$data['msg']="error";
header('Content-Type: application/json');
echo json_encode($data);
?>
in index.php
<script type="text/javascript">
$.ajax({
url:'json.php',
success:function(data){
$('body').html(data.msg);
}
});
</script>

Related

I am enable to get the success message..!

i am trying to get the user details into database and data is stored..i want a success message to fade in i have tried out some code but sadly its not working...plzz help me out of this..beg u pardon if am wrong..
here gose my register.php code
<?php
require_once 'DB_Functions.php';
$db = new DB_Functions();
// json response array
$response = array("error" => false);
if (!empty($_POST['fname']) && !empty($_POST['lname']) && !empty($_POST['email']) && !empty($_POST['password']) && !empty($_POST['mobile'])){
// receiving the post params
$fname = trim($_POST['fname']);
$lname = trim($_POST['lname']);
$email = trim($_POST['email']);
$password = $_POST['password'];
$mobile = trim($_POST['mobile']);
// validate your email address
if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
// valid email address
if ($db->isUserExisted($email)) {
// user already existed
$response["error"] = true;
$response["error_msg"] = "User already existed with " . $email;
echo json_encode($response);
} else {
// create a new user
$user = $db->storeUser($fname, $lname, $email, $password, $mobile);
if ($user) {
// user stored successfully
$response["error"] = false;
$response["uid"] = $user["id"];
$response["user"]["fname"] = $user["fname"];
$response["user"]["lname"] = $user["lname"];
$response["user"]["email"] = $user["email"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else {
// user failed to store
$response["error"] = true;
$response["error_msg"] = "Unknown error occurred in registration!";
echo json_encode($response);
}
}
} else {
// invalid email address
$response["error"] = true;
$response["error_msg"] = "invalid email address";
echo json_encode($response);
}
} else {
$response["error"] = true;
$response["error_msg"] = "Required parameters are missing!";
echo json_encode($response);
}
?>
and here gose the .html file with jquery..
<html>
<head>
<title>jQuery Test</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src = "register.js"></script>
</head>
<body>
<!--html body-->
<form name = "register" id = "register" method = "POST">
<label>First name:</label>
<input type = text name = "fname" id = "fname" required>
<label>Last name:</label>
<input type = "text" name = "lname" id = "lname" required>
<label>E-mail:</label>
<input type = "email" name = "email" id = "email" required>
<label>Password</label>
<input type = "password" name = "password" id = "password" required>
<label>Mobile no:</label>
<input type = "number" name = "mobile" id = "mobile" required>
<input type="submit" value="Insert" name="submit" id = "submit">
</form>
<div id = "result" align = "right"></div>
</body>
</html>
here gose me /.js/ file
$(document).ready(function(){
$("#submit").click(function(e){
e.preventDefault();
$.ajax({
url: "register.php",
type: "POST",
data: {
fname: $("#fname").val(),
lname: $("#lname").val(),
email: $("#email").val(),
password: $("#password").val(),
mobile: $("#mobile").val()
},
dataType: "JSON",
success: function (json) {
$("#result").html(json.user.email); // like that you can display anything inside #result div
$("#result").fadeOut(1500);
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
});
});
There's no need to use JSON.stringify(jsonStr) because jQuery has already parsed the response object for you. jQuery will look at the Content-Type of the response and, if it's application/json, it will parse it, and provide the parsed result to your success handler.
Your jQuery should be like this:
$(document).ready(function(){
$("#submit").click(function(e){
e.preventDefault();
$.ajax({
url: "register.php",
type: "POST",
data: {
fname: $("#fname").val(),
lname: $("#lname").val(),
email: $("#email").val(),
password: $("#password").val(),
mobile: $("#mobile").val()
},
dataType: "JSON",
success: function (json){
if(json.error){
$("#result").html(json.error_msg); // display error message
}else{
$("#result").html(json.user.email); // like that you can display anything inside #result div
}
$("#result").fadeOut(1500);
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
});
});

Javascript Validation if statement

I'm trying to use javascript validation for a simple login form. Right now I'm just focusing on the username input (Want it to display as red and have the error below it "That username is already taken" if the username is already taken). However, nothing shows up when the input is changed even though when I did inspect element network I saw that it was going to the registerjs.php file
In the head of the html form page i have
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
function valusername() {
var username = $('input#username').val();
if ($.trim(username) != '') {
$.post('../ajax/registerjs.php', {username: username}, function(data) {
if (data == 'That username is already taken') {
document.getElementById("username").style.border="3px solid red";
$('div#username_error').text(data);
}
});
}
}
</script>
The actual text input is
<input class="input" type="text" tabindex="1" placeholder="Username*"
style="height:20px;" name="username" id="username" onchange="valusername()">
<div id="username_error"></div>
The php file registerjs.php that is linked I'm sure works
<?php
include('../init.php');
if (isset($_POST['username']) === true && empty($_POST['username']) === false) {
$username = $_POST['username'];
if (user_exists($username) === true) {
echo("
That username is already taken
");
} else {
echo("Good");
}
}
?>
Does anyone know why I'm having this problem? It seems to be the if statement in the script.
Do this :
function valusername()
{
var username = $('input#username').val();
if ($.trim(username) != '')
{
$.post('../ajax/registerjs.php', {username: username}, function(data)
{
if ($.trim(data) == 'That username is already taken')
{
document.getElementById("username").style.border="3px solid red";
$('div#username_error').text(data);
}
});
}
}
Better Approach:
<input class="input" type="text" tabindex="1" placeholder="Username*"
style="height:20px;" name="username" id="username" >
<div id="username_error"></div>
JS
<script>
$(function(){
$(document).on('change paste','#username', function () {
var username = $(this).val();
if ($.trim(username) !== '') {
$.post('../ajax/registerjs.php', {username: username},
function(data){
if (data) {
$("#username").css({'border','3px solid red'});
$('div#username_error').text('Username already exist');
return false;
}
}
); // end of $.post
} // end of if
})
})
</script>
registerjs.php
<?php
include('../init.php');
// here i assume user_exists return true or false
if ( !empty($_POST['username']) && user_exists($username)) {
return TRUE;
}
else{
return FALSE;
}
?>

Php response displays in browser instead of firing the ajax callback

I've spent some time looking on SO for an answer to this and have found some related issues, but nothing quite like mine...as usual....
I've got a fairly simple php/jquery ajax registration page that is working right up until the ajax callback. What I mean is the form data is passing to php and inserting into the db but when the php response is supposed to come back all that happens is the response displays in the browser. I've followed the logs, checked fiddler, re-written the code with/without json, and anothing seems to change. The odd thing is I have another form on a different page that is set up exactly the same way and everything works there perfectly. The only difference I can find between the two pages is the Request Headers of the php file. The one that works accepts json and the one the other one doesn't, but I have no idea if that means anything . . . I'm kind of grabbing for anything at this point.
So, without further delay, here is my code. Any thoughts/input are greatly appreciated. Thank you!
<!DOCTYPE html>
<head>
<link rel="stylesheet" type="text/css" href="mobile.css" media="screen and (max-device-width: 480px)" />
<!--[if IE]>
<link rel="stylesheet" type="text/css" media="screen and (min-width: 481px)" href="IEjoin.css" />
<![endif]-->
<script src="jquery-1.8.2.min.js" type="text/javascript"></script>
<script src="register.js" type="text/javascript"></script>
<script src="jquery.placeholder.js" type="text/javascript"></script>
</head>
<body>
<div id="wrapper">
<div id="logo">
</div>
<div id="headline">
<h1>Create your account</h1>
</div>
<div id="container">
<form id="register" action="form.php" method="post">
<ul>
<li id="first_name">
<input name="fname" type="text" value="" id="fname" placeholder="First Name" maxlength="30">
<div class="error"></div>
</li>
<li id="last_name">
<input name="lname" type="text" value="" id="lname" placeholder="Last Name" maxlength="30">
<div class="error"></div>
</li>
<li id="email_address">
<input name="email" type="text" value="" id="email" placeholder="Email Address" maxlength="60">
<div class="error"></div>
</li>
<li id="uname">
<input name="username" type="text" value="" id="username" placeholder="Username" maxlength="15">
<div class="error"></div>
</li>
<li id="pword">
<input name="password" type="password" value="" id="password" placeholder="Password">
<div class="error"></div>
</li>
<li id="gender_select">
<select id="gender" name="gender">
<option value="" selected="selected">Select your gender</option>
<option value="male">Male</option>
<option value="female">Female</option>
<option value="unspecified">Unspecified</option>
</select>
</li>
<li id="submit_button">
<button id="register_button" class="register_button_disabled">Create Account</button>
</li>
</ul>
</form>
<script> $('input[placeholder]').placeholder();</script>
</div>
</div>
</body>
$(document).ready(function() {
function validateEmail(email) {
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
return emailReg.test(email);
}
function submitButton() {
if (($("#first_name").hasClass("good")) && ($("#email_address").hasClass("good")) && ($("#uname").hasClass("good")) && ($("#pword").hasClass("good")) ){
$("#register_button").removeAttr("disabled");
$("#register_button").removeClass("register_button_disabled").addClass("register_button");
} else {
$("#register_button").attr("disabled", "disabled");
$("#register_button").removeClass("register_button").addClass("register_button_disabled");
}
}
$("body").mousedown(submitButton);
$("body").keyup(submitButton);
$("body").hover(submitButton);
$("body").mouseover(submitButton);
$("#fname").keydown(function(){
$("#first_name").removeClass("required");
$("#first_name div").html("");
});
$("#fname").bind ("keyup mousedown",function(){
if(this.value===""){
$("#first_name").removeClass("good").addClass("wait");
} else {
$("#first_name").removeClass("wait").addClass("good");
}
});
$("#fname").blur(function(){
if(this.value===""){
$("#first_name").removeClass("good").addClass("required");
$("#first_name div").html("Please enter your first name");
} else {
$("#first_name").removeClass("wait").addClass("good");
}
});
$("#email").keydown(function(){
$("#email_address").removeClass("required");
$("#email_address div").html("");
});
$("#email").bind ("keyup mousedown",function(){
var email = this.value;
var emailLength = email.length;
if (emailLength<=4){
$("#email_address").removeClass("good").addClass("wait");
} else {
$("#email_address").removeClass("wait").addClass("good");
}
});
$("#email").blur(function(){
var email = this.value;
var emailLength = email.length;
if ((emailLength<=4) || (!validateEmail(this.value))) {
$("#email_address").removeClass("good").addClass("required");
$("#email_address div").html("Please use a valid email address");
} else if (emailLength>=3){
$.ajax({
type: "POST",
cache: false,
url: "Check.php",
data: "email="+email,
dataType: "json",
success: function(data) {
if (data.status === "success") {
$("#email_address").removeClass("good").addClass("required");
$("#email_address div").html("Sorry, that email is already used");}
else {
$("#email_address").removeClass("wait").addClass("good");
}
}
});
} else {
$("#email_address").removeClass("wait").addClass("good");
}
});
$("#username").keydown(function(){
var un = this.value;
var unLength = un.length;
if(unLength<3){
$("#uname").removeClass("good").addClass("wait");
} else {
$("#uname").removeClass("wait").addClass("good");
}
});
$("#username").bind ("keyup mousedown",function(){
$("#uname").removeClass("required");
$("#uname div").html("");
});
$("#username").blur(function(){
var un = this.value;
var unLength = un.length;
if(unLength<3){
$("#uname").removeClass("good").addClass("required");
$("#uname div").html("Please use at least 3 characters");
} else if (unLength>=3){
$.ajax({
type: "POST",
cache: false,
url: "check.php",
data: "username="+un,
dataType: "json",
success: function(data) {
if (data.status === "success") {
$("#uname").removeClass("good").addClass("required");
$("#uname div").html("Sorry, that username is taken");
} else {
$("#uname").removeClass("wait").addClass("good");
}
}
});
} else {
$("#uname").removeClass("wait").addClass("good");
}
});
$("#password").keydown(function(){
var pw = this.value;
var pwLength = pw.length;
if(pwLength<=5){
$("#pword").removeClass("good").addClass("wait");
} else {
$("#pword").removeClass("wait").addClass("good");
}
});
$("#password").bind ("keyup mousedown",function(){
$("#pword").removeClass("required");
$("#pword div").html("");
});
$("#password").blur(function(){
var pw = this.value;
var pwLength = pw.length;
if(pw===""){
$("#pword").removeClass("good").addClass("required");
$("#pword div").html("Please enter a password");
}
if(pwLength<=5){
$("#pword").removeClass("good").addClass("required");
$("#pword div").html("Please use at least 6 characters");
} else {
$("#pword").removeClass("wait").addClass("good");
}
});
$("#button").click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
cache: false,
url: "form.php",
data: $('#register').serialize(),
success: function(data) {
if (data === "fname") {
$("#first_name").removeClass("good").addClass("required");
$("#first_name div").html("Please enter your first name");
} else if (data === "email") {
$("#email_address").removeClass("good").addClass("required");
$("#email_address div").html("Please use a valid email address");
} else if (data === "email2") {
$("#email_address").removeClass("good").addClass("required");
$("#email_address div").html("Sorry, that email is already used");
} else if (data === "username") {
$("#uname").removeClass("good").addClass("required");
$("#uname div").html("Please use at least 3 characters");
} else if (data === "username2") {
$("#uname").removeClass("good").addClass("required");
$("#uname div").html("Sorry, that username is taken");
} else {
window.location.href = "http://site.com";
},
error: function(httpRequest, textStatus, errorThrown) {
alert("status=" + textStatus + ",error=" + errorThrown);
}
});
return false;
});
});
<?php
$host=""; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name=""; // Database name
$tbl_name=""; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Get values from form
$fname = mysql_real_escape_string($_POST['fname']);
$lname = mysql_real_escape_string($_POST['lname']);
$email = mysql_real_escape_string($_POST['email']);
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$gender = mysql_real_escape_string($_POST['gender']);
//validate inputs
$emailpull = "SELECT email FROM $tbl_name WHERE email='$email'";
$emailresult=mysql_query($emailpull);
$emailnum=mysql_num_rows($emailresult);
$emailReg = "/^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/";
$unpull = "SELECT username FROM $tbl_name WHERE username='$username'";
$unresult=mysql_query($unpull);
$unnum=mysql_num_rows($unresult);
if ($fname == "") {
$response = "fname";
} elseif ($email == "") {
$response = 'email';
} elseif (!preg_match($emailReg, $email)) {
$response = 'email';
} elseif ($emailnum > 0) {
$response = 'email2';
} elseif (strlen($username)<3) {
$response = 'username';
} elseif ($unnum > 0) {
$response = 'username2';
} elseif (strlen($password)<6) {
$response = 'password';
} else {
// Insert data into mysql
$sql="INSERT INTO $tbl_name(fname,lname,email,username,password,gender)VALUES ('$fname','$lname','$email','$username','$password','$gender')";
}
$result=mysql_query($sql);
if($result)
$response = "success";
// send message back
echo $response;
?>
<?php
// close connection
mysql_close();
?>
The click handler for #button has this line which may be the culprit:
window.location.href = "http://crushonit.com";
This will redirect to that page when the form has no validation errors.

jquery/ajax form another div refresh

I would start with my code...
<script type="text/javascript">
$(document).ready(function(){
$("#cForm").validate({
debug: false,
rules: {
name: "required",
email: {
required: true,
email: true
},
comment: "required"
},
messages: {
name: "Empty.",
email: "Invalid email.",
comment: "Empty.",
},
submitHandler: function(form) {
// do other stuff for a valid form
$.post('process.php', $("#cForm").serialize(), function(data) {
$('#results').html(data);
});
}
});
});
The above code is working fine with the form below, and giving success message out of my process.php fine into div with id results but i have another div before that with id comments which selects and displays the data from the same table where this ajax/jquery form stores the data...I want to refresh that with the latest changes when the form is submitted..have a look at my code first.
<div id="comments">
<h2>Comments</h2>
<?php
$query3 = "SELECT name, c_c, c_date FROM blog_comments WHERE art_id='$id'";
$result3 = #mysql_query($query3);
while($rr=mysql_fetch_array($result3))
{
echo '<div class="comen">';
echo "<h3>";
echo $rr['name'];
echo "</h3>";
echo "<h4>";
echo $rr['c_date'];
echo "</h4>";
echo "<p>";
echo $rr['c_c'];
echo "</p>";
echo '</div>';
}
mysql_close();
?>
</div>
<p>Post your comments. All fields are obligatory.</p>
<div id="results"></div>
<form action="" id="cForm" name="cForm" method="post" class="cform">
<table>
<tr><td><label for="name" id="name_label">Name</label></td><td><input type="text" name="name" id="name" size="30" /></td></tr>
<tr><td><label for="email" id="email_label">Email</label></td><td><input type="text" name="email" id="email" size="30" /></td></tr>
<tr><td><label for="comment" id="comment_label">Comment</label></td><td><textarea name="comment" id="comment" cols="30" rows="5"></textarea></td></tr>
<tr><td><input type="hidden" name="idi" value="<?php echo $id ?>" /></td></tr>
<tr><td></td><td><input type="submit" name="submit" value="Submit" /></td></tr>
</table>
</form>
and my process php looks like this
if (isset($_POST['submit']))
{
include ('databas/conektion.php');
function escape_data ($data)
{
global $con;
if (ini_get('magic_quotes_gpc'))
{
$data = stripslashes($data);
}
return mysql_real_escape_string($data,$con);
}
if (empty($_POST['name']))
{
$n = FALSE;
echo '<p>Invalid name</p>';
}
else
{
$n = escape_data($_POST['name']);
}
if (empty($_POST['email']))
{
$e = FALSE;
echo '<p>Invalid Email</p>';
}
else
{
$e = escape_data($_POST['email']);
}
if (empty($_POST['comment']))
{
$c = FALSE;
echo '<p>Invalid Comments</p>';
}
else
{
$c = escape_data($_POST['comment']);
}
$id = $_POST['idi'];
if($n && $e && $c)
{
$query2 = "INSERT INTO blog_comments (name, c_email, c_c, art_id, c_date) VALUES ('$n', '$e', '$c', '$id', NOW())";
$result2 = #mysql_query($query2);
if($result2)
{
echo '<p>Your comments have been posted successfully.</p>';
}
else
{
echo '<p>System Error</p><p>' . mysql_error() . '</p>';
}
mysql_close();
}
else
{
echo '<p style="color:red">Please try again.</p>';
}
}
?>
what i want to do is refresh div with id comments, once form is submitted.what changes should i make in my code...thanks!!
Create a new file called comments.php (with source code of your comments block)
Initially load comments
$(document).ready(function() { $("#comments_div").load("comments.php"); });
Then when you want to refresh, just call $("#comments_div").load("comments.php");
ie. from your first given code
submitHandler: function(form) {
// do other stuff for a valid form
$.post('process.php', $("#cForm").serialize(), function(data) {
$('#results').html(data);
$("#comments_div").load("comments.php");
});
}
EDIT:
If you have an ID in your url, then replace
$("#comments_div").load("comments.php");
with
$.get("comments.php", {"id": "<?=(0+$_GET['id'])?>"},
function(response) {
$("#comments_div").html(response);
}
);
Where your_id is the name of GET parameter.
EDIT2:
So how about if you try something like:
$.get("comments.php", {id: <?php echo (0+$_GET['id']); ?>},
function(response) {
$("#comments_div").html(response);
}
);
Thanks bro for your help,,and giving me so much time...my head tags look like this altogether now...
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title><?php echo $page_title; ?></title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"> </script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<link href="style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(document).ready(function(){
$("#cForm").validate({
debug: false,
rules: {
name: "required",
email: {
required: true,
email: true
},
comment: "required"
},
messages: {
name: "Empty.",
email: "Invalid email.",
comment: "Empty.",
},
submitHandler: function(form) {
// do other stuff for a valid form
$.post('process.php', $("#cForm").serialize(), function(data) {
$('#results').html(data);
$.get("comment.php", {"id": "<?=(0+$_GET['id'])?>"},
function(response) {
$("#comment").html(response);
}
);
});
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function() { $.get("comment.php", {"id": "<?=(0+$_GET['id'])?>"},
function(response) {
$("#comment").html(response);
}
); });
</script>
</head>

Ajax to PHP form submission. Keep getting "parsererror"

ajaxSubmit.js:
$(document).ready(function(){
$('#submit').click(function() {
$('#waiting').show(500);
$('#reg').hide(0);
$('#message').hide(0);
$.ajax({
type : 'POST',
url : 'post.php',
dataType : 'json',
data: {
login : $('input#login').val(),
pass : $('input#pass').val(),
pass1 : $('input#pass1').val()
},
success : function(data){
$('#waiting').hide(500);
$('#message').removeClass().addClass((data.error === true) ? 'error' : 'success')
.text(data.msg).show(500);
if (data.error === true)
$('#reg').show(500);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
$('#waiting').hide(500);
$('#message').removeClass().addClass('error')
.text(textStatus).show(500);
$('#reg').show(500);
}
});
return false;
});
});
HTML Form:
<div id="message" style="display: none;">
</div>
<div id="waiting" style="display: none;">
Please wait<br />
<img src="images/ajax-loader.gif" title="Loader" alt="Loader" />
<br />
</div>
<form id="reg" class="form with-margin" name="reg" method="post" action="">
<br />
<p class="inline-small-label">
<label for="login"><span class="big">Email</span></label>
<input type="text" name="login" id="login" value="">
</p>
<p class="inline-small-label">
<label for="pass"><span class="big">Password</span></label>
<input type="password" name="pass" id="pass" value="">
</p>
<p class="inline-small-label">
<label for="pass1"><span class="big">Password Again</span></label>
<input type="password" name="pass" id="pass1" value="">
</p>
<div align="center"><button type="submit" name="submit" id="submit" >Register</button></div>
</form>
<script type="text/javascript" src="js/ajaxSubmit.js"></script>
post.php:
<?php
sleep(3);
$login = $_POST['login'];
$pass = $_POST['pass'];
$pass1 = $_POST['pass1'];
$login = mysql_real_escape_string($login);
$pass = mysql_real_escape_string($pass);
$pass1 = mysql_real_escape_string($pass1);
if (empty($login)) {
$return['error'] = true;
$return['msg'] = 'You did not enter you email.';
}
else if (empty($pass)) {
$return['error'] = true;
$return['msg'] = 'You did not enter you password.';
}
else if ($test == false) {
$return['error'] = true;
$return['msg'] = 'Please enter a correct email. This will be verified';
}
else if (empty($pass)) {
$return['error'] = true;
$return['msg'] = 'You did not enter you password twice.';
}
else if ($pass != $pass1) {
$return['error'] = true;
$return['msg'] = 'Your passwords dont match.';
}
else {
$return['error'] = false;
$return['msg'] = 'Thanks! Please check your email for the verification code!';
}
echo json_encode($return);
?>
Any ideas why I keep getting the parsererror?
you have a $test variable else if ($test == false) that is undefined.
I'd suggest that if you are having parse errors through ajax, that you just load up the .php file manually and then php will point you to the line that the error is occurring on.

Categories