Taking post parameters in ajax comment form - php

I'm trying to customize one comment form from template which I purchased. In short I have 3 files - post.php, comment_post.php and main.js. In post.php is simple html comment form. I'm not that good in ajax part and still trying to learn php so I'll need some help with this.
<form class="row" role="form" id="comments-form" name="comments-form" action="comments-send.php" method="POST">
<input type="text" class="form-control form-name-error" name="comments[form-name]" id="form-name" placeholder="Name">
<input type="email" class="form-control form-email-error" id="form-email" name="comments[form-email]" placeholder="Email">
<input type="hidden" name="comments[post_id]" value="<?php echo $row['post_id'];?>" >
<textarea class="form-control input-row-2 form-review-error" rows="3" id="form-comments" name="comments[form-review]" placeholder="Comment"></textarea>
<div class="form-group text-right btn-submit">
<button type="submit" class="btn btn-dark button-submit">Send</button>
<div class="message-success alert-success alert hidden" style="position: absolute"><i class="fa fa-check"></i></div>
</div>
</form>
I have one hidden field to get post_id..
Here is comment_post.php which is the problem ( I think ). The errors are Undefined variable: comment_author_name, comment_author_image .. etc
if(isset($_POST['comments'])) {
$response = array('status' => '', 'errors'=>array());
foreach($_POST['comments'] as $key => $value) {
if($value == '') {
$response['errors'][$key.'-error'] = 'error';
}
}
if(empty($response['errors'])) {
$_POST['comments']['form-name'] = $comment_author_name;
$_POST['comments']['form-email'] = $comment_author_email;
$_POST['comments']['post_id'] = $post_id;
$_POST['comments']['form-review'] = $comment_text;
$sql = "INSERT INTO comments (comment_author_name, comment_author_email, comment_date, comment_text, post_id)
VALUES (:comment_author_name, :comment_author_email, NOW(), :comment_text, :post_id)";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(":comment_author_name", $comment_author_name);
$stmt->bindValue(":comment_author_email", $comment_author_email);
$stmt->bindValue(":post_id", $post_id);
$stmt->bindValue(":comment_text", $comment_text);
$stmt->execute();
$response['status'] = 'ok';
} else {
$response['status'] = 'error';
}
echo json_encode($response);
}
In original file (comment_post.php) there is nothing for database insertion and this is my code. I'm not sure how to get values from the form when is send to the php part. This is from main.js file for the comment_form.
$("#comments-form").submit(function(e) {
$('#comments-form .form-control').removeClass('#comments-form message-error');
$.post("comments-send.php", $('#comments-form').serialize(), function(data) {
if (data.status === 'ok') {
$("#comments-form .message-success").removeClass('hidden').velocity({ opacity : 1 });
$("#comments-form .button-submit").addClass('button-transparent');
$('#comments-form .form-control').val('');
setTimeout(function() {
$("#comments-form .message-success").velocity({ opacity : 0 }, function() {
$(this).addClass('hidden');
});
$("#comments-form .button-submit").removeClass('button-transparent');
}, 3000);
} else {
$.each(data.errors, function(i, e) {
$('.' + i).addClass('#comments-form message-error');
});
}
}, 'json');
e.preventDefault();
});
$("#comments-form").on('keyup', '.contact-form', function() {
var that = this;
if ($(this).val() !== '') {
$(this).removeClass('message-error');
} else {
$(that).addClass('message-error');
}
});

It looks like you are not setting your variables correctly
update to this
$comment_author_name = $_POST['comments']['form-name'];
$comment_author_email = $_POST['comments']['form-email'];
$post_id = $_POST['comments']['post_id'];
$comment_text = $_POST['comments']['form-review'];
What you want to do is actually get the values from the $_POST and save them to the variables you have created.
Previously you were doing the oposite, therefore the variables did not exist and you were also reseting the values in your $_POST

Related

Unable to show error text in a div after ajax success

In my app I want to make a login page. I want do do this login using ajax jquery. If login success it navigate to next page or show a error message in a div.
this is my code
<form role="form">
<div class="form-group radio-inline">
<label><b>I Am</b></label>
<input type="radio" name="category" value="s"> Student
<input type="radio" name="category" value="t"> Teacher
<input type="radio" name="category" value="p"> Parent
</div>
<div class="form-group">
<input type="email" class="form-control" id="email" name="email" placeholder="Enter email address">
</div>
<div class="form-group">
<input type="password" class="form-control" id="password" name="password" placeholder="Enter password">
</div>
<button type="submit" class="btn btn-primary btn-block">Sign in</button>
</form>
<div id="error">
</div>
jquery
$(document).on('click','.btn',function() {
var email = $("#email").val();
var password = $("#password").val();
var category = $("input[name=category]:checked").val();
$.ajax({
url: "../logincheck.php",
type: "POST",
data: {category:category,email:email,password:password},
success:function(data) {
if (data==='studentlogin') {
window.location.href = '../student/index.php';
}
if(data==='teacherlogin'){
window.location.href = '../teacher/index.php';
}
if(data==='teachersubject') {
window.location.href = '../teacher/subjectadd.php';
}
else {
window.location.href = 'login.html';
$("#error").html("Invalis Email/Password");
}
}
});
});
logincheck.php
$category=$_POST['category'];
$email=$_POST['email'];
$pwd=$_POST['password'];
if ($category == 's') {
$result=mysqli_query($conn,"SELECT studentid,studentfname FROM studentinfo WHERE emailid='$email' and pwd='$pwd'");
$res=mysqli_fetch_array($result);
if($res[0]>0){
$_SESSION['snstudentid']=$res[0] ;
$_SESSION['snstudentfname']=$res[1] ;
echo "studentlogin";
//header("location:student/index.php");
exit();
}
else{
echo "error";
//header("location:pages/login.html");
}
} elseif ($category == 't') {
$result=mysqli_query($conn,"SELECT teacherid,teacherfname FROM teacherinfo WHERE emailid='$email' and pwd='$pwd'");
$res=mysqli_fetch_array($result);
if($res[0]>0){
$check_subject = mysqli_query($conn, "SELECT count(teachersubjectid) FROM teachersubject WHERE teacherid='$res[0]'");
$subject_result = mysqli_fetch_array($check_subject);
if ($subject_result[0]>0) {
$_SESSION['snteacherid']=$res[0];
$_SESSION['snteacherfname']=$res[1];
echo "teacherlogin";
//header("location:teacher/index.php");
exit();
} else {
$_SESSION['snteacherid']=$res[0];
$_SESSION['snteacherfname']=$res[1];
echo "teachersubject";
//header("location:teacher/subjectadd.php");
exit();
}
} else{
echo "error";
//header("location:pages/login.html");
}
}
that error message show for few second and then it goes.I do that error class style display:none;
How I do that?Please help me.
Have a look at what this code does:
else {
window.location.href = 'login.html';
$("#error").html("Invalis Email/Password");
}
yes, it redirects the page to login.html, then, while the page is loading it puts up the error message, then the page load completes and, in your initial login page, the error message is empty.
Remove the line:
window.location.href = 'login.html';
assuming you are already on login.html.
If <div id="error"> has a style of display:none;, then its contents will not be displayed. Inside of the ajax success callback, $("#error").html("Invalis Email/Password"); needs to be $("#error").html("Invalis Email/Password").show(); to set display:block;. See .show().

Showing success message in php using ajax

Iam Working on a project using OO php and i want to display success message when submit is clicked
I've searched all on the web but the solutions am getting are not working for me!!
I tried using both jquery and ajax but i keep on getting the same error
Here is my html
<form method="post" id="postForm" class="form-horizontal" action = "index.php">
<div class="form-group">
<label for="Title" class="control-label col-sm-3">Title</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="title" id="title" placeholder="Enter Title of your Post"/>
</div>
</div>
<div class="form-group">
<label for="Title" class="control-label col-sm-3">Body</label>
<div class="col-sm-9">
<Textarea type="text" class="form-control" name="body" id="body" placeholder="Enter Body of your Post"></textarea>
</div>
</div>
<button type="submit" class="btn btn-default" name="submit">submit</button><br/>
<div class="text-center">
<span id="success" class="text-success"></span>
<span id="wanings" class="text-danger"></span>
</div>
</form>
This is my jquery script file inserted into the same page index.php
<script>
$(document).ready(function(){
$('#postForm').submit(function(event){
event.preventDefault();
var $form = $(this),
var title = $('#title').val();
var body = $('#body').val();
var url = $form.attr('action');
var method = $form.attr('method');
if(title == '' || body == ''){
$('#warnings').html('All Fields are Required');
}else{
$('#warnings').html('');
$.ajax({
url: url,
method:method,
data:{title: title, body:body},
success:function(data){
$('#postForm').trigger('reset');
$('#success').fadeIn().html(data);
setTimeout(function function_name() {
$('#success').fadeOut('slow');
}, 3000);
}
});
}
});
});
</script>
And the Php is just above the Html also in the same page. Its supposed to get the post title and insert it into the database but echo the message that data has been successfully added if submit is clicked.
Here is the Snippet
<?php
require 'classes/Database.php';
$database = new Database;
$post = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
if($post['submit']){
$title = $post['title'];
$body = $post['body'];
$database->query('INSERT INTO posts (title, body) VALUES(:title, :body)');
$database->bind(':title', $title);
$database->bind(':body', $body);
$database->execute();
if($database->lastInsertId()){
echo "<h1>Post added Successfully To the Database</h1>";
}
}
?>
When i run the page in the browser, it displays the whole html in the div.
instead of a message set and then it throws the following error in the console.
Could any of you be knowing why it can't show the message? thanks
As you notice by the image, all the text is green, this is because you are rendering the response within that text-success span. Not ideal.
Instead of responding with HTML respond with JSON, and do your checks within the javascript to determine whether it was successful or a warning.
Some other issues:
You're not sending up submit so it will always skip passed the if statement.
So try something like:
$(document).ready(function() {
$('#postForm').submit(function(event) {
event.preventDefault();
var $form = $(this);
var title = $('#title').val();
var body = $('#body').val();
var url = $form.attr('action');
var method = $form.attr('method');
if (title == '' || body == '') {
$('#warnings').html('All Fields are Required');
if (title == '') {
$('#title').closest('.form-group').find('.help-block').html('Title is a required field')
}
if (body == '') {
$('#body').closest('.form-group').find('.help-block').html('Body is a required field')
}
} else {
$('#warnings').html('');
$form.find('.help-block').html('')
$.ajax({
url: url,
method: method,
data: {
title: title,
body: body
},
success: function(response) {
// got errors from server
if (response.status === 'error') {
if (response.errors.title) {
$('#title').closest('.form-group').find('.help-block').html(response.errors.title)
}
if (response.errors.body) {
$('#body').closest('.form-group').find('.help-block').html(response.errors.body)
}
if (response.errors.global) {
$('#warnings').html(response.errors.global)
}
}
// all good, assign message to success
else {
$('#success').fadeIn().html(response.msg);
setTimeout(function() {
$('#success').fadeOut('slow');
}, 3000);
$('#postForm').trigger('reset');
}
}
});
}
});
});
<form method="post" id="postForm" class="form-horizontal" action="index.php">
<div class="form-group">
<label for="title" class="control-label col-sm-3">Title</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="title" id="title" placeholder="Enter Title of your Post" />
</div>
<span class="help-block"></span>
</div>
<div class="form-group">
<label for="body" class="control-label col-sm-3">Body</label>
<div class="col-sm-9">
<textarea type="text" class="form-control" name="body" id="body" placeholder="Enter Body of your Post"></textarea>
</div>
<span class="help-block"></span>
</div>
<button type="submit" class="btn btn-default">submit</button><br/>
<div class="text-center">
<span id="success" class="text-success"></span>
<span id="warnings" class="text-danger"></span>
</div>
</form>
PHP code, basically validate and return as JSON.
<?php
require 'classes/Database.php';
$database = new Database;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$post = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
$response = [];
$errors = [];
// validate inputs
if (empty($post['title'])) {
$errors['title'] = 'Title is a required field';
}
if (empty($post['body'])) {
$errors['body'] = 'Body is a required field';
}
// errors is empty so its all good
if (empty($errors)) {
//
$database->query('INSERT INTO posts (title, body) VALUES(:title, :body)');
$database->bind(':title', $post['title']);
$database->bind(':body', $post['body']);
$database->execute();
if ($database->lastInsertId()) {
$response = [
'status' => 'success',
'msg' => 'Post added successfully added'
];
} else {
$response = [
'status' => 'error',
'errors' => [
'global' => 'Failed to insert post, contact support'
]
];
}
} else {
$response = [
'status' => 'error',
'errors' => $errors
];
}
exit(json_encode($response));
}
// guessing after this is your rendering of that form
You need to check if($_POST) instead of if($post['submit']) because in your case its not going into if condition and echo out your result. Also after echo add "exit" statement so that form will not be printed in division.

How to return PHP response to HTML page using AJAX

I am trying to learn web applications, here I have my client side using HTML and server is PHP based.
I have signup from on my client side, which when filled and click submit button is sent to PHP page using jQuery AJAX.
So, after the form data is sent or POST to PHP page using AJAX, a couple of validations happen like checking username and email, if the validations succeed it should send back a JSON object to my HTML page "SUCCESS", if validation fails "Error".
So, the problem is when I submit the form it is redirecting me to the PHP page instead of displaying the JSON response back on my html.
I was trying to solve this since last week and I filtered stack overflow, youtube and many other sites for a solution, which didn't go well.
Here is the code
PHP:
<?php include ( "./inc/connect.inc.php" );
header("Content-type: application/javascript");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, GET");
session_start();
if (isset($_SESSION['user_login'])) {
$user = $_SESSION["user_login"];
}
else
{
$user = "";
}
?>
<?php
$registration = #$_POST['signup-submit'];
$fname = #$_POST['fname'];
$lname = #$_POST['lname'];
$uname = #$_POST['uname'];
$email = #$_POST['email'];
$email_repeat = #$_POST['email_repeat'];
$password = #$_POST['password'];
$ucheck_array = array('Username Takne');
$echeck_array = array('Email already used');
$siginup_sucess_array = array('Sucess');
//Sign-Up form validation
if ($registration) {
$usernamecheck = mysql_query("SELECT * FROM users WHERE username='$uname' ");
$usernamecount = mysql_num_rows($usernamecheck);
$emailcheck = mysql_query("SELECT * FROM users WHERE email='$email' ");
$emailcount = mysql_num_rows($emailcheck);
if ($usernamecount == 0 && $emailcount == 0) {
$squery = mysql_query("INSERT INTO users VALUES ('','$uname','$fname','$lname','$dob','$location','$email','$password','$date','0','','','','','','no')" );
echo json_encode($siginup_sucess_array);
}
else {
if ($usernamecount == 1) {
echo json_encode($ucheck_array);
}
else if ($emailcount == 1) {
echo json_encode($echeck_array);
}
}
}
HTML Form:
<form id="register-form" class="animated fadeInRight" action="http://localhost/Exercises/AJAX/df.php" method="post" role="form" style="display: none;">
<div class="form-group">
<input type="text" name="fname" id="fname" placeholder="First Name" value="" autofocus>
</div>
<div class="form-group">
<input type="text" name="lname" id="lname" tabindex="1" class="form-control" placeholder="Last Name" value="">
</div>
<div class="form-group">
<input type="text" name="uname" id="uname" tabindex="1" class="form-control" placeholder="User Name" value="">
</div>
<div class="form-group">
<input type="text" name="dob" id="dob" placeholder="D-O-B" value="">
</div>
<div class="form-group">
<input type="text" name="location" id="location" tabindex="1" class="form-control" placeholder="Location" value="">
</div>
<div class="form-group">
<input type="email" name="email" id="email" placeholder="Email" value="">
</div>
<div class="form-group">
<input type="email" name="email_repeat" id="email_repeat" placeholder="Confirm Email" value="">
</div>
<div class="form-group">
<input type="text" name="password" id="password" tabindex="1" class="form-control" placeholder="Password" value="">
</div>
<div class="form-group dob">
<input type="text" name="date" id="date" placeholder="Date" value="">
</div>
<p class="index_p">By creating the account you accept all the <span style="color: #4CAF50; font-weight: bold; text-decoration: underline;">Terms & Conditions.</span></p>
<div class="form-group">
<div class="row">
<div id="btn_signin" class="col-sm-6 col-sm-offset-3">
<input type="submit" name="signup-submit" id="signup-submit" value="SIGN UP">
</div>
</div>
</div>
</form>
<div id="signup-test"></div> //PHP response to be displayed here
JS:
$("#signup-submit").click( function() {
$.post( $("#register-form").attr("action"),
$("#register-form :input").serializeArray(),
function(signup_data){
$("#signup-test").html(signup_data);
});
clearInput();
});
$("#register-form").submit( function() {
return false;
});
function clearInput() {
$("#register-form :input").each( function() {
$(this).val('');
});
}
To be clear I tried e.preventDefault, return false and many other scripts,
and my PHP and HTML are not in the same folder or directory.
Thanks.
Try using a more flexible jQuery ajax. I use this version if ajax because I can change it to get and post very easily. I have tested this method and it works with your form:
<script>
function clearInput() {
$("#register-form :input").each( function() {
$(this).val('');
});
}
$(document).ready(function() {
$("#register-form").submit(function(e) {
//console.log($(this).attr("action"));
$.ajax({
url: $(this).attr("action"),
type: 'post',
data: $(this).serialize(),
success: function(response)
{
// console.log(response);
$("#signin-test").html(response);
clearInput();
},
error: function(response)
{
console.log(response);
}
});
e.preventDefault();
});
});
</script>
This may be because you are handling your form based on the behavior of a button. You should be listening for the onSubmit event of the form and preventing that from firing.
$("#register-form").submit( function( e ) {
e.preventDefault();
$.post( $("#register-form").attr("action"),
$("#register-form :input").serializeArray(),
function(signup_data){
$("#signup-test").html(signup_data);
});
clearInput();
});
I solved it with the following script, hope it would help someone.
The problem with all the scripts which I tried is, they don't have XMLHttpRequest permission to POST data and get the data back from PHP(server side in my case).
So, XMLHttpRequest is a must for Ajax to Get or Post data "CROSS_DOMAIN".
Script :
function signup(){
var firstname = document.getElementById("firstname").value;
var lastname = document.getElementById("lastname").value;
var uname = document.getElementById("uname").value;
var email = document.getElementById("email").value;
var email_repeat = document.getElementById("email_repeat").value;
var password = document.getElementById("password").value;
if (fname == "") {
document.getElementById("fname").style.background = "rgba(244,67,54,0.45)";
document.getElementById("fnamestatus").innerHTML = "<p style='width: 30px; color: rgba(255, 62, 48, 0.9); font-size: 14px; font-weight: bold; margin-top:5px; margin-left: -40px; margin-bottom: 0px;'>2-25</p>";
}
else if (email != email_repeat){
document.getElementById("email").style.background = "rgba(244,67,54,0.45)";
document.getElementById("email_repeat").style.background = "rgba(244,67,54,0.45)";
alert("Your email fields do not match");
}
else {
var signup_ajax = new XMLHttpRequest();
signup_ajax.open("POST", "URL which you want to post data", true);
signup_ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
signup_ajax.onreadystatechange = function () {
if (signup_ajax.readyState == 4 && signup_ajax.status == 200) {
if (signup_ajax.responseText = "Success"){
alert("Account created");
}
else if (signup_ajax.responseText = "Try again.") {
window.scrollTo(0,0);
alert("Try again.");
}
}
}
signup_ajax.send("fname=" +fname+ "&lname=" +lname+ "&uname=" +uname+ "&email=" +email+ "&email_repeat=" +email_repeat+ "&password=" +password );
}
}
PHP(I'm just posting the basic php, you can always add as may validations as you need) :
if(isset($_POST["uname"])) {
$fname = #$_POST['firstname'];
$lname = #$_POST['lastname'];
$uname = #$_POST['uname'];
$email = #$_POST['email'];
$email_repeat = #$_POST['email_repeat'];
$password = #$_POST['password'];
//Sign-Up form validation
if($_POST) {
$squery = mysql_query("INSERT INTO users VALUES ('','$uname','$fname','$lname','$email','$password')" );
echo 'Sucess';
}
else
echo 'Try again.';
}
Only change what I did to my HTML Form is :
<input type="button" name="signup-submit" id="signup-submit" class="form-control btn btn-signup" onclick="signup()" tabindex="4" value="SIGN UP">

No alert in success function

I am trying to insert value in database from jquery ajax and i want whenever data insertion is successfull, a result output comes true other wise "error:failed". My entry in database successfully updated, but when i alert(msg), its doesnt give me message.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script>
<body>
<div class="wrapper">
<div id="main" style="padding:50px 0 0 0;">
<!-- Form -->
<form id="contact-form" method="post">
<h3>Paypal Payment Details</h3>
<div class="controls">
<label>
<span>TagId</span>
<input placeholder="Please enter TagId" id="tagid" type="text" tabindex="1" >
</label>
</div>
<div class="controls">
<label>
<span>Paypal Email: (required)</span>
<input placeholder="All Payment will be collected in this email address" id="email" type="email" tabindex="2">
</label>
</div>
<div class="controls">
<label>
<span>Amount</span>
<input placeholder="Amount you would like to charged in GBP" id="amount" type="tel" tabindex="3">
</label>
</div>
<div class="controls">
<div id="error_div"></div>
</div>
<div>
<button name="submit" type="submit" id="form-submit">Submit Detail</button>
</div>
</form>
<!-- /Form -->
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('#form-submit').click(function()
{
var tagid = $("#tagid").val();
var email = $("#email").val();
var amount = $("#amount").val();
var param = 'tagid='+ tagid + '&email=' + email + '&amount=' + amount;
param = param + '&type=assign_amount';
locurl = 'dbentry.php';
$.ajax({
url: locurl,
type:'post',
data:param,
success:function(msg)
{
alert(msg);
}
});
});
});
dbentry.php
<?php
$vals = $_POST;
include 'dbconfig.php';
if($vals['type'] == "assign_amount")
{
$values = assign_amount();
echo json_encode(array('status' =>$values));
}
function assign_amount()
{
global $con;
global $vals;
$sql = "INSERT INTO `dynamic_url`(`tagid`,`email`,`amount`) VALUES('".$vals['tagid']."','".$vals['email']."','".$vals['amount']."')";
$result = mysql_query($sql,$con);
if($result){
if( mysql_affected_rows() > 0 ){
$status="success";
}
}else{
$status="failed";
}
return $status;
}
?>
Try to echo it like
if($result){
if( mysql_affected_rows() > 0 ){
$status="success";
}
} else {
$status="failed";
}
return $status;
And in your if statement code like
if($vals['type'] == "assign_amount")
{
$values = assign_amount();
echo $values;
}
For the ajax return purpose you better to echo or print rather than return it.
In order to see alert() message, you have to prevent default behaviour of clicked submit button:
$('#form-submit').click(function(e)
{
e.preventDefault();
//....
}
Otherwise, the FORM is submited and page is reloaded.
Display $status at last in php file instead of return statement
You will get it in alert
echo $status;
Can you try this,
var locurl = 'dbentry.php';
$.ajax({
url: locurl,
type:'post',
data:param,
dataType:'json',
success:function(msg)
{
alert(msg.status.sql);
}
});
Your code has a lot of flaws in it. For instance you are contatenating the string to create a data object. But if somebody would enter a & or = or any other special charactor in it, your form would fail.
Also you are binding on the click function on a button. While this works, it would be useless for people without javascript. This might not be an issue, but its easily prevented with some minor changes.
I would change the <button name="submit" to <input type="submit" and then bind jQuery to the form it self. Also add the action attribute to the form to include 'dbentry.php'
$(function(){
$('#contact-form').submit(function(){
var $form = $(this);
var data = $form.serialize();
var locurl = 'dbentry.php';
$.post(locurl,data, function(msg) {
alert(msg.status)
}, 'json');
return false; //prevent regular submit
});
});
Now to make it work PHP has to return JSON data.
<?php
header('Content-type: application/json');
//your code that includes
echo json_encode(array('status' =>$sql));
//also notice that your code only returns data on success. Nothing on false.
?>

CodeIgniter - Ajax validation not working correct and not storing data in database

I'd like some help please.
From my tests till now, I get these:
If validation fails - The div #ajaxResults from my view gets the class alert-error and shows the errors (as expected).
If validation succeeds - The div #ajaxResults gets the class alert-error (not expected) and shows true (as expected).
What I'd like to do is when there's an ajax request is this:
If the validation succeeds - return the div #ajaxResults with a class alert-success(bootstrap) and also display a message saying "data stored in database successfully". I can't figure out how should I return and the message from the controller.
If the validation fails to show the div #ajaxResults with a class alert-error with the validation errors. (as it is)
2.Also I have notice that in case of a NON-ajax-request the data are stored in the database, but in case of an ajax-request don't. How can I fix this to work correct??
This is my controller
public function manage($id = NULL){
$this->layout->add_includes('js/ckeditor/ckeditor.js')->add_includes('js/ajax_scripts.js');
$this->load->library('form_validation');
$data['categ'] = $this->category_model->with_parents();
//fetch a single product or create a new one
if ( isset($id) ) {
$data['prod'] = $this->product_model->get($id);
$data['attr'] = $this->attributes_model->get_by('product_id', $id);
} else {
$data['prod'] = $this->product_model->make_new();
$data['attr'] = $this->attribute_model->make_new();
}
if ( isset($_POST['general_settings']) ) {
if ($this->form_validation->run('product_rules') === true) {
// get post inputs and store them in database
$data = $this->product_model->input_posts(array('product_name', 'brand', 'category_id', 'general_description','visible'));
$this->product_model->save($data, $id);
$result = array('status' => 200, 'message' => 'data stored in database successfully');
} else {
// validation failed
$result = array('status' => 400, 'reason' => validation_errors());
}
if ( $this->input->is_ajax_request() ) {
echo json_encode($result);
exit;
}
$this->session->set_flashdata('message', $result);
redirect('admin/product');
}
// if ( isset($_POST['attribute_settings']) ) { same goes here }
// load the view
$this->load->view('admin/products/manage', $data);
}
this is my js script
$(document).ready(function () {
$('form.ajax-form').on('submit', function() {
var obj = $(this), // (*) references the current object/form each time
url = obj.attr('action'),
method = obj.attr('method'),
data = {};
obj.find('[name]').each(function(index, value) {
var obj = $(this),
name = obj.attr('name'),
value = obj.val();
data[name] = value;
});
// console.log(data);
// data.general_settings = 1;
$.ajax({ // see the (*)
url: url,
type: method,
data: data,
dataType: 'json',
success: function(response) {
//console.log(response);
$('#ajaxResults').removeClass('alert alert-success alert-error');
$('.control-group').removeClass('error warning error info success');
if (response.status == 200) {
$('#ajaxResults').addClass('alert alert-success').html(response.message);
$('.control-group').addClass('success'); // ** apply it only on valid fields
} else {
$('#ajaxResults').addClass('alert alert-error').html(response.reason);
$('.control-group').addClass('error'); // ** apply it only on invalid fields
}
}
});
return false; //disable refresh
});
});
one of my forms with class .ajax-form inside the view
<?php echo form_open('admin/product/manage/'.$prod->product_id, array('class' => 'ajax-form')); ?>
<div class="control-group">
<label class="control-label" for="product_name">Product *</label>
<input type="text" name="product_name" value="<?php echo set_value('product_name', $prod->product_name); ?>" />
<?php echo form_error('product_name'); ?>
</div>
<div class="control-group">
<label class="control-label" for="brand">Brand</label>
<input type="text" name="brand" value="<?php echo set_value('brand', $prod->brand); ?>" />
<?php echo form_error('brand'); ?>
</div>
// apply same to all my fields
<p>
<label for="category_id">Category *</label>
<?php echo form_dropdown('category_id', $categ);
echo form_error('category_id');
?>
</p>
<p>
<label for="general_description">General Description</label>
<textarea class="ckeditor" name="general_description" rows="10" cols="250"><?php echo set_value('general_description', $prod->general_description); ?></textarea>
<?php echo form_error('general_description') . PHP_EOL; ?>
</p>
<p>
<label for="visible">Visible</label>
<select name="visible" class="span1">
<option value="0">No</option>
<option value="1">Yes</option>
</select>
</p>
<p>
<button class="btn btn-primary" type="submit" name="general_settings">Ok</button>
</p>
<?php echo form_close() . PHP_EOL; ?>
Any help would be appreciated.
As I'm understand You need something like this (I've put just code fragments).
Controller:
if($this->form_validation->run('product_rules') === true){
//your code will be here
$result = array(
'status' => 200, 'message' => 'data stored in database successfully'
);
}
else{
$result = array('status' => 400, 'reason' => validation_errors());
}
if ( $this->input->is_ajax_request()){
echo json_encode($result);
exit;
}
else{
$this->session->set_flashdata('message', $result);
redirect('admin/product');
}
Ajax function:
data.general_settings = 1;
$.ajax({
url: url,
type: method,
data: data,
dataType: 'json',
success: function(response) {
$('#ajaxResults').removeClass('alert alert-success alert-error');
if(response.status == 200){
$('#ajaxResults').addClass('alert alert-success').html(response.message);
}
else{
$('#ajaxResults').addClass('alert alert-error').html(response.reason);
}
}
});
Are You saw same errors in firebug for ajax request?

Categories