Form submission using AJAX and handling response in Wordpress Website - ajax

I have a wordpress website. I have made a contact form and it is POSTed by AJAX.
Here's the code:
<script type="text/javascript">
jQuery(document).ready(function(){
$("#error_box").hide();
$('#contact_form').submit(function(e){
// prevent the form from submitting normally
e.preventDefault();
var na=$("#1").val();
var email2=$("#2").val();
var subject2 = $("#3").val();
var message2 = $("#4").val();
var mydata = "pn2="+na+"&email="+email2+"&subject="+subject2+"&msg="+message2;
alert(mydata);
$("#contact_form").css({"opacity":"0.1"});
$.ajax ({
type: 'POST',
url: $(this).attr.action, // Relative paths work fine
data: mydata,
success: function(){
$("#contact_form").css({"opacity":"1"});
$('#error_box').fadeIn('fast').css({"height": "auto"});
}
});
});
});
</script>
When the form is submitted, I want the error box (#error_box) to display a message according to the data submitted, for example if one of the fields is empty it should display an error, or display a success message if the processing is successful and the form has been mailed. Is there any way I can do this?
[UPDATE]
Here's my contact-form.php file(the action)
<?php if(isset($_POST['pn2']) && isset($_POST['email']) && isset($_POST['subject']) && isset($_POST['msg']))
{
if(empty($_POST['pn2']) || empty($_POST['email']) || empty($_POST['subject']) || empty($_POST['msg'])){
echo 'EMPTY ERROR';
}
else
{
$name = $_POST['pn2'];
$email = $_POST['email'];
$subj = $_POST['subject'];
$msg = $_POST['msg'];
$to = "ankushverma61#gmail.com";
$mail_cont = "FROM: $person_name. \n Email: $email. \n Msg: $msg";
echo "success";
mail($recipient, $subj, $mail_cont) or die("UNABLE TO SEND!!!");
}
}
?>

Form submission using Ajax call
Contact Form
<form action="#" id="contactForm" method="post">
<input class="require" type="text" placeholder="First Name" name="firstName">
<span class="fieldError"></span>
<input class="require" type="text" placeholder="Last Name" name="lastName">
<span class="fieldError"></span>
.
.
.
<input type="submit" value="Submit">
</form>
client side validation with ajax call
jQuery('#contactForm').submit(ajaxSubmit);
function ajaxSubmit(){
var newContactForm = jQuery(this).serialize();
var flag = 0;
jQuery('.require', '#contactForm').each(function(){
var inputVal = jQuery(this).val();
if(jQuery.trim(inputVal) === ""){
flag = 1;
jQuery(this).next().html("Can't be blank");
jQuery(this).next().show();
}
else{
jQuery(this).next().hide();
}
});
if(flag){
return false;
}
jQuery.ajax({
type:"POST",
url: "/wp-admin/admin-ajax.php?action=contactForm",
data: newContactForm,
success:function(data){
jQuery(':input','#contactForm')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
jQuery("#feedback").html(data);
jQuery("#feedback").fadeOut(10000);
},
error: function(errorThrown){
alert(errorThrown);
}
});
return false;
}
store form data in db and send mail
add the following code in functions.php
wp_enqueue_script('jquery');
add_action('wp_ajax_addContactForm', 'addContactForm');
add_action('wp_ajax_nopriv_addContactForm', 'addContactForm');
function addContactForm(){
global $wpdb;
$first_name = $_POST['firstName']; $last_name = $_POST['lastName'];
$email = $_POST['email'];
.
.
.
if($wpdb->insert('table_name',array(
'first_name' => $first_name,
'last_name' => $last_name,
'email' => $email,
.
.
.
))===FALSE){
echo "Error";
}
else {
$headers = 'From: xyz <xyz#xyz.com>';
$subject = "Thank you";
$body = "<p>Thank you</p><p>.........</p>";
wp_mail( $email, $subject, $body, $headers);
echo "<div class='success'>Thank you for filling out your information, we will be in contact shortly.</div>";
}
exit;
}

You should use:
$.ajax ({
type: 'POST',
url: $(this).attr.action,
data: mydata,
success: function(response) { // here you receive response from you serverside
$("#contact_form").css({"opacity":"1"});
$('#error_box').html(response).fadeIn('fast').css({"height": "auto"});
}
});
Your server action url: $(this).attr.action, should return message which be inserted in #error_box

First create form like this
<p class="register-message"></p>
<form action="#" method="POST" name="testregister" class="register-form">
<fieldset>
<label><i class="fa fa-file-text-o"></i> Register Form</label>
<input type="text" name="firstname" placeholder="Username" id="firstname">
<p id="firstname-error" style="display:none">Firstname Must be Enter</p>
<input type="email" name="email" placeholder="Email address" id="email">
<p id="email-error" style="display:none">Email Must Be Enter</p>
<input type="submit" class="button" id="test" value="Register">
</fieldset>
</form>
then bind the click and send ajax call
<script type="text/javascript">
jQuery('#test').on('click', function(e) {
e.preventDefault();
var firstname = jQuery('#firstname').val();
var email = jQuery('#email').val();
if (firstname == "") {
jQuery('#firstname-error').show();
return false;
} else {
jQuery('#firstname-error').hide();
}
if (email == "") {
jQuery('#email-error').show();
return false;
} else {
jQuery('#email-error').hide();
}
jQuery.ajax({
type: "POST",
dataType: 'json',
url: "<?php echo admin_url('admin-ajax.php'); ?>",
data: {
action: "test", // redirect function in function.php
firstname: firstname,
email: email
},
success: function(results) {
//console.log(results);
if (results == "1") {
jQuery('.register-message').text("Email already exist");
} else {
jQuery('.register-message').text("Register successfu");
}
},
error: function(results) {}
});
});
</script>
In function.php add the below code to insert data in table
<?php
//
add_action('wp_ajax_test', 'test', 0);
add_action('wp_ajax_nopriv_test', 'test');
function test()
{
$firstname = stripcslashes($_POST['firstname']);
$email = stripcslashes($_POST['email']);
global $wpdb;
$q = $wpdb->prepare("SELECT * FROM wp_test WHERE email='" . $email . "' ");
$res = $wpdb->get_results($q);
if (count($res) > 0) {
echo "1";
} else {
$user_data = array(
'firstname' => $firstname,
'email' => $email
);
$tablename = $wpdb->prefix . 'test';
$user_id = $wpdb->insert($tablename, $user_data);
echo "0";
}
die;
}

Related

How can I fetch autocomplete data into their respected element using Ajax and Laravel?

Here is my problem.
I'm trying to fetch the data from an auto-completing text-box.
There are two text-boxes:
Region and province.
I have successfully fetched the data on the text-box having region as name.
My problem is, it gives the same value to the next text-box having province as name.
In my Laravel blade I have this code:
<input id="region" type="text" class="form-control" name="region" value="" required autofocus>
<div id="regionList"> </div>
<input id="province" type="text" class="form-control" name="province" value="" required autofocus>
<div id="provinceList"> </div>
I have also a javascript file named auto-complete
$(document).ready(function() {
$('#region').keyup(function() {
var region = $(this).val();
if (region != '')
{
var _token = $('input[name="_token"]').val();
$.ajax({
url: "register/showRegion",
method: "POST",
data: { region: region, _token: _token },
success: function(data)
{
$('#regionList').fadeIn();
$('#regionList').html(data);
}
});
}
});
$(document).on('click', 'li', function() {
$('#region').val($(this).text());
$('#regionList').fadeOut();
});
$('#province').keyup(function() {
var province = $(this).val();
if (province != '')
{
var _prov_token = $('input[name="_token"]').val();
$.ajax({
url: "register/showProvince",
method: "POST",
data: { province: province, _token: _token },
success: function(data)
{
$('#provinceList').fadeIn();
$('#provinceList').html(data);
}
});
}
});
$(document).on('click', 'li', function() {
$('#province').val($(this).text());
$('#provinceList').fadeOut();
});
});
And on my routes I included this
Route::post('/register/showRegion', 'LocationController#showRegion');
Route::post('/register/showProvince', 'LocationController#showProvince');
And on my controller is this
public function index() {
return view('auth.register');
}
function showRegion(Request $request)
{
if ($request->get('region'))
{
$region = $request->get('region');
$regions = Refregion::where('regDesc', 'LIKE', "$region%")->get();
$output = '<ul class="dropdown-menu" style="display:block; position:absolute;">';
foreach($regions as $region)
{
$output .= '<li>'.$region->regDesc.'</li>';
}
$output .= '</ul>';
echo $output;
}
}
function showProvince(Request $request)
{
if ($request->get('province'))
{
$province = $request->get('province');
$province = Refprovince::where('provDesc', 'LIKE', "province%")->get();
$output = '<ul class="dropdown-menu" style="display:block; position:absolute;">';
foreach($provinces as $province)
{
$output .= '<li>'.$province->provDesc.'</li>';
}
$output .= '</ul>';
echo $output;
}
}
I'm trying to figure out why it gives the same value to the other text-box "province" when I have selected region.
Can someone help me with this, or at least explain to me why this happen?
Thank you
change it
$(document).on('click', 'li', function() {
$('#region').val($(this).text());
$('#regionList').fadeOut();
});
on this
$('#regionList').on('click', 'li', function() {
$('#region').val($(this).text());
$('#regionList').fadeOut();
});
and change it
$(document).on('click', 'li', function() {
$('#province').val($(this).text());
$('#provinceList').fadeOut();
});
on this
$('#provinceList').on('click', 'li', function() {
$('#province').val($(this).text());
$('#provinceList').fadeOut();
});

ajax is not able to call the function of codeigniter

This is Welcome controller method
public function send_otp()
{
echo 'in';
die;
$phone = $_POST['mobile'];
if ($phone != '') {
$mobile_detail = $this->welcome_model->check_if_already_mobile_no($phone);
if (!empty($mobile_detail)) {
if ($mobile_detail['is_verified'] == 'yes') {
$message = 'Already Verified.';
echo json_encode(array('status' => 'error', 'message' => $message));
exit;
} else {
$this->welcome_model->delete_mobile_no($phone);
}
}
$otp = self::generateRandomNo();
$this->welcome_model->insert_mobile_detail($phone, $otp);
$link = file_get_contents("http://49.50.67.32/smsapi/httpapi.jsp?username=aplusv&password=aplusv1&from=APLUSV&to=$phone&text=$otp&coding=0");
$status = '';
if ($link != '') {
$status = 'success';
$message = 'Successfully Otp send to your no.';
} else {
$status = 'error';
$message = 'Error in sending OTP.';
}
echo json_encode(array('status' => $status, 'message' => $message));
exit;
}
}
This is model
public function check_if_already_mobile_no($mobile_no = null)
{
$query = $this->db->get_where('mobile_sms', array('mobile_no' => $mobile_no));
return $query->row_array();
}
public function get_mobile_details($mobile_no = null, $otp = null)
{
$query = $this->db->get_where('mobile_sms', array('mobile_no' => $mobile_no, 'otp' => $otp));
return $query->row_array();
}
public function insert_mobile_detail($phone, $otp)
{
$this->mobile_no = $phone;
$this->otp = $otp;
$this->is_verified = 'no';
$this->created_at = date('Y-m-d H:i:s');
$this->db->insert('mobile_sms', $this);
}
This is view
<div class="container" style="margin-top: 25px;">
<div class="row">
<div class="col-md-12" id="response_msg"></div>
<div class="col-md-4" id="enter_mobile">
<form method="POST" action="#">
<div class="form-group">
<label for="phone">Phone </label>
<input type="text" class="form-control" id="mobile" name="phone" placeholder="Enter Mobile">
</div>
<button type="button" name="send_mobile" id="send_otp" class="btn btn-primary">Submit</button>
</form>
</div>
<script src="assets/js/jquery.js"></script>
<script type="text/javascript">
// var base_url = "<?php echo base_url();?>";
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script>
$(function () { // start of doc ready.
$("#send_otp").on('click', function (e) {
var mobile = $('#mobile').val();
alert(mobile);
$.ajax({
url: '<?php echo site_url('index.php/welcome/send_otp'); ?>',
data: {'mobile': mobile},
type: "post",
dataType: 'json',
success: function (data) {
if (data.status == 'success') {
$('#response_msg').html('<div class="alert alert-success" role="alert">' + data.message + '</div>');
$('#mobile_no').val(mobile);
$('#enter_mobile').hide();
$('#verify_otp_form').show();
} else {
$('#response_msg').html('<div class="alert alert-danger" role="alert">' + data.message + '</div>');
}
}
});
});
in ajax is not getting call ie $.ajax is not working here and my controller ie welcome with method send_otp is not called here.
why my function in controller is not getting called
how to solve the issue
what is the proper way to call the controller function using base_url
i have check the console also it is not showing any error
I noticed that you are using site_url() slightly incorrectly: don't write index.php there, just use site_url('welcome/send_otp')
Don't forget you have an unconditional die() at the top of your send_otp method - it will prevent any code below itself from executing

Submit form within bootstrap modal using ajax and codeigniter without page change

I am trying to submit a form within a bootstrap modal using ajax. And my form is successfully submitted, but the success statements within ajax are not executed. The page is redirected to a blank page saying {"msg":"ok"}.
I am pasting the code from controller and view. Please help.
Controller
$update_profile_details = $this->userp_m->edit_profile_m($uname,$uemail,$data1,$new_email);
if($update_profile_details == true)
{
$status['msg'] = 'ok';
}
else
{
$status['msg'] = 'err';
}
echo json_encode ($status);
View
$(document).ready(function()
{
$("#myForm").submit(function(e)
{
e.preventDefault();
var reg = /^[A-Z0-9._%+-]+#([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
var name = $('#inputName').val();
var email = $('#inputEmail').val();
if (name.trim() == '') {
alert('Please enter your name.');
$('#inputName').focus();
return false;
} else if (email.trim() == '') {
alert('Please enter your email.');
$('#inputEmail').focus();
return false;
} else if (email.trim() != '' && !reg.test(email)) {
alert('Please enter valid email.');
$('#inputEmail').focus();
return false;
} else {
var fd = new FormData(this);
$.ajax({
type: 'POST',
url: $('#myForm').attr('action'),
dataType: "json",
data: $('#myform').serialize(), fd,
contentType: false,
cache: false,
processData:false,
beforeSend: function()
{
$('.submitBtn').attr("disabled", "disabled");
$('.modal-body').css('opacity', '.5');
},
success: function(status)
{
alert(status);
if (status.msg == 'ok') {
$('#inputName').val('');
$('#inputEmail').val('');
$('.statusMsg').html('<span style="color:green;">Changes have been saved successfully.</p>');
} else
{
$('.statusMsg').html('<span style="color:red;">Some problem occurred, please try again.</span>');
}
$('.submitBtn').removeAttr("disabled");
$('.modal-body').css('opacity', '');
},
error: function(status)
{
alert("Some error, please try again");
}
});
}
});
HTML
<form id="myform" method="post" enctype="multipart/form-data" action="<?php echo site_url('User/user_index_c/edit_profile_c'); ?>">
<label>Full Name : </label>
<input class="name_styling" type="text" placeholder="Enter name" id="inputName" name="uname">
<label>Email Id : </label>
<input class="email_styling" type="email" placeholder="Enter email" id="inputEmail" name="new_email">
<div class="controls">
<label>Profile Photo : </label>
<input name="file1" type="file" id="image_file" />
<img id="blah" class="logoupload" src="#" alt="your image" />
<span class="filename"></span>
</div>
<center><input class="submitBtn" id="submit" type="submit" value="Save Changes" name="submit" ></center>
</form>
Instead of function you have to write jquery code like below.
Remove function submitContactForm(e){}
Add $(document).on('submit', '#myform', function(e) { })
$(document).on('submit', '#myform', function(e) {
e.preventDefault();
var reg = /^[A-Z0-9._%+-]+#([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
var name = $('#inputName').val();
var email = $('#inputEmail').val();
if (name.trim() == '') {
alert('Please enter your name.');
$('#inputName').focus();
return false;
} else if (email.trim() == '') {
alert('Please enter your email.');
$('#inputEmail').focus();
return false;
} else if (email.trim() != '' && !reg.test(email)) {
alert('Please enter valid email.');
$('#inputEmail').focus();
return false;
} else {
$('.submitBtn').prop("disabled", true);
$('.modal-body').css('opacity', '.5');
var myFormData = new FormData();
e.preventDefault();
var inputs = $('#myForm input[type="file"]');
$.each(inputs, function(obj, v) {
var file = v.files[0];
var filename = $(v).attr("data-filename");
var name = $(v).attr("name");
myFormData.append(name, file, filename);
});
var inputs = $('#myForm input[type="text"],input[type="email"]');
$.each(inputs, function(obj, v) {
var name = $(v).attr("name");
var value = $(v).val();
myFormData.append(name, value);
});
var xhr = new XMLHttpRequest;
xhr.open('POST', '<?php echo base_url(); ?>index.php/User/user_index_c/edit_profile_c/', true);
xhr.send(myFormData);
xhr.onload = function() {
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200) {
$('#inputName').val('');
$('#inputEmail').val('');
$('.statusMsg').html('<span style="color:green;">Changes have been saved successfully.</p>');
$('.submitBtn').removeAttr("disabled");
$('.modal-body').css('opacity', '');
}
}
};
}
});
Let me know if it not works.
try this: in your file.js:
$(document).ready(function () {
$('#submit').click(function () {
var name= $("#inputName").val();
var mail = $("#inputEmail").val();
var img = $("#image_file").val();
$.post("User/user_index_c/edit_profile_c", {send_name:name,send_mail:mail, send_igm:img},
function (data) {
if (data.trim() != "ok") {
alert('error');
}
else{
//action for "success" exemple: alert("send with success!"); and insert a code for clean fields
}
});
});
});
in your controller's method:
$uname = $this->input->post("send_name");
$uemail = $this->input->post("send_mail");
$new_email = $this->input->post("send_igm");
$update_profile_details = $this->userp_m->edit_profile_m($uname,$uemail,$data1,$new_email);
if($update_profile_details == true){
echo 'ok';
}
else
{
echo 'err';
}
I hope I have helped

ajax with jquery ui autocomplete

I have created an autosuggestion list using jquery and WordPress function. My autosuggestion working fine. I am giving my code here
Jquery Code
(function ($) {
$(document).ready(function () {
$('#my_ajax').autocomplete({
// minChars: 1,
source: function(request, response) {
$.ajax({
type: 'POST',
dataType: 'json',
url: devel_ajax.ajaxurl,
data: 'action=my_ajax'+'&name='+request.term,
success: function(data) {
response( $.map( data, function( item ) {
return {
label: item.title,
value: item.title
}
}));
}
});
},
minLength: 3,
});
})(jQuery);
PHP Code
function user_autocomplete($value){
global $wpdb;
$name = $wpdb->esc_like(stripslashes($value));
$users = $wpdb->get_results("SELECT DISTINCT
$wpdb->users.ID
FROM $wpdb->users
WHERE LOWER($wpdb->users.user_login) LIKE LOWER('".$name."%')");
$autocomplete = array();
foreach($users as $key => $user){
$user_info = get_userdata($user->ID);
$firstname = $user_info->first_name;
$lastname = $user_info->last_name;
if(!empty($firstname) || !empty($lastname)){
$username = ucfirst($firstname) . ' '. ucfirst($lastname);
}else{
$username = $user_info->user_login;
}
$email = $user_info->user_login;
$website = $user_info->website;
$autocomplete[$user->ID] = array(
'ID' => $user->ID,
'Name' => $username
'email' => $email
'website' => $website
);
}
return $autocomplete;
}
HTML Code
<form action='' method='POST' role="form" class="bottom-space">
<div class="form-group">
<input id="my_ajax" autofocus="" value="" type="text" name="q" placeholder="my_ajax" style="width:100%;max-width:600px;outline:0" autocomplete="off">
<input id="firstname" name="firstname" type="hidden" value=''>
<input id="lastname" name="lastname" type="hidden" value=''>
<input id="id" name="user_id" type="hidden" value=''>
<input id="email" name="email" type="hidden" value=''>
<input id="website" name="email" type="hidden" value=''>
</div>
<submit type="submit" class="btn btn-default">Submit
Button</submit>
</form>
But the problem is I can not set others hidden input Field. Any kind of help or suggestions highly appreciable.
The code is not tested. But I think this should be work for you. I am giving you some code snippet.
(function ($) {
$(document).ready(function () {
$('#my_ajax').autocomplete({
// minChars: 1,
source: function(request, response) {
$.ajax({
type: 'POST',
dataType: 'json',
url: devel_ajax.ajaxurl,
data: 'action=my_ajax'+'&name='+request.term,
success: function(data) {
response( $.map( data, function( item ) {
var object = new Object();
object.label = item.Name;
object.value = item.Name;
object.ID = item.ID;
object.email = item.email;
object.website = item.website;
return object
}));
// response( $.map( data, function( item ) {
// return {
// label: item.title,
// value: item.title
// }
// }));
}
});
},
select: function (event, ui) {
$("#my_ajax").val(ui.item.value);
$("#firstname").val(ui.item.value);
$("#id").val(ui.item.ID);
$("#email").val(ui.item.email);
$("#website").val(ui.item.website);
}
});
});
})(jQuery);

controller not sending data back to ajax request codeigniter

I have developed a login system using ajax the problem is when i send the ajax request everything is working and validating fine i just need to pass data back to my ajax request I am using echo json_encode("true"); but somehow it is just echoing the value true in the controller and not going back in the view!
HTML
<form onsubmit="return validate()" method="post" action="<?php echo base_url(); ?>admin/admin_login">
<input class="md-input" placeholder="username" type="text" name = 'login_username' id = 'login_username' />
<input class="md-input" placeholder="password" type="password" name= 'login_password' id= 'login_password' />
<button type='submit' class="btn btn-primary btn-block btn-large">Login</button>
</form>
AJAX
<script>
function validate(){
if(!$("#login_username").val()){
alert("username is required");
return false;
}
if(!$("#login_password").val()){
alert("Password is required");
return false;
}
return true;
var data={
"login_username" : $("#login_username").val(),
"login_password" : $("#login_password").val()
};
$.ajax({
type: 'post',
url: '<?=base_url()?>Admin/admin_login',
dataType: 'json',
data:data,
success: function (data) {
if(data=="true"){
alert("ok");
}
else
{
alert("not ok");
}
}
});
}
</script>
admin_login controller
public function admin_login(){
$data = $this->input->post();
$status=$this->admin_validate->validate($data);
if($status){
$session=array(
"admin"=>$this->input->post("login_username"),
);
$this->session->set_userdata($session);
//redirect("Admin/contact");
header('Content-Type: application/json');
echo json_encode("true");
}
else
{
header('Content-Type: application/json');
echo json_encode("false");
//redirect("Admin");
}
}
Now iam going to change the code little
change the HTML form to
<form>
<input class="md-input" placeholder="username" type="text" name = 'login_username' id = 'login_username' />
<input class="md-input" placeholder="password" type="password" name= 'login_password' id= 'login_password' />
<button type='button' onclick="validate()" class="btn btn-primary btn-block btn-large">Login</button>
</form>
and Now change your ajax to
<script>
function validate(){
if(!$("#login_username").val()){
alert("username is required");
return false;
}
if(!$("#login_password").val()){
alert("Password is required");
return false;
}
$.ajax({
type: 'post',
url: '<?php echo base_url()."Admin/admin_login"; ?>',
data:{ "login_username" : $("#login_username").val(), "login_password" : $("#login_password").val() },
success: function (data) {
if(data=="true"){
alert("ok");
}
else
{
alert("not ok");
}
}
});
}
</script>
and your controller to
public function admin_login(){
$data = $this->input->post();
$status=$this->admin_validate->validate($data);
if($status){
$session=array(
"admin"=>$this->input->post("login_username"),
);
$this->session->set_userdata($session);
echo "true";
}
else
{
echo "false";
}
}
Hope this helps you. :)
Have you tried sending true or false without the quotation marks?, if not try creating an array and then passing it to the echo json_encode(); something like:
$result = array();
array_push($result, true);
echo json_encode($result);
on your ajax you will have to read it as follow
if(data[0] == true){
alert("Ok");
}else{
alert("Not OK");
}
Hope it helps
you are returning true in the script so the form is get submitted. no ajax call occurs.
<script>
function validate(){
if(!$("#login_username").val()){
alert("username is required");
return false;
}
if(!$("#login_password").val()){
alert("Password is required");
return false;
}
return true; // HERE THE ISSUE //
var data={
"login_username" : $("#login_username").val(),
"login_password" : $("#login_password").val()
};
$.ajax({
type: 'post',
url: '<?=base_url()?>Admin/admin_login',
dataType: 'json',
data:data,
success: function (data) {
if(data=="true"){
alert("ok");
}
else
{
alert("not ok");
}
}
});
}

Resources