I have a login page, that sends a ajax request to the server when someone tries to log in. The ajax, goes to the server, cause they get logged in I've been able to confirm. But the problem is it seems my jQuery isn't receiving the JSON.
The function in my controller is:
public function login(){
$this->load->model('users_model');
if((!!$this->input->post('email')) || (!!$this->input->post('password'))){
$ret = $this->users_model->login($this->input->post('email'), $this->input->post('password'));
echo json_encode(array('status' => "OK", 'msg' => 'Logged in!')); //also tried return
}else{
echo json_encode(array('status' => 'FAIL', "msg" => 'Invalid Email or Pass'));
}
}
and the AJAX function is:
<script type="text/javascript">
$(document).ready(function() {
$("#login").ajaxForm(function(json) {
alert(json);
if(json.status == true) {
alert(json.msg);
//window.location = '<?php echo base_url(); ?>';
} else {
alert("Problem");
$(".error_msg").html(json.msg);
};
});
});
</script>
if I alert the json variable, it's blank, and if I do json.msg it say undefined. So... what do I have to do to get this to give the callback, a json object, or an object of any kind? Please explain it so I understand the problem, not just how to fix it. Thanks a lot!
EDIT:
Here's the form too:
<span class="error_msg"></span></br>
<form id="login" action="<?php echo base_url(); ?>users/login" method="POST" enctype="multipart/form-data">
Email: <input name="email" type="text"/></br>
Password: <input type="password" name="password"></br>
<input type="submit"/>
</form>
Ah, I think I understand.
Is this the plugin you are using? http://www.malsup.com/jquery/form/#api
In that case, use ajaxSubmit, not ajaxForm.
Other examples online do something like this:
$(document).ready(function() {
$('#login').submit(function() {
$("#login").ajaxSubmit({
success: function(json) {
alert(json);
if(json.status == true) {
alert(json.msg);
//window.location = '<?php echo base_url(); ?>';
} else {
alert("Problem");
$(".error_msg").html(json.msg);
}
}
});
return false;
});
});
Related
I have this test page on a website - https://piclits.com/test-slideshow/
It displays a bunch of images/PICLITS and grabs them randomly from a folder 12 at a time into a slideshow.
I want to email the main image without refreshing the page (which would bring up 12 new images) from the email button which opens up a popup to add email addresses.
All is good - I can grab the image and mail it but the script does something wacky where it flashes on the page and then hangs up at admin-ajax.php rather than just staying on the page and sending the email.
My Form:
<div class="ajax-form-container" style="float: left">
<form id="ajaxformid" action="" method="POST">
<p>Email this PIC-LIT to a friend.<br />You may include multiple emails if you separate them with a comma.</p>
<ul style="list-style-type: none;">
<li>Email: <textarea name="piclit_email" id="piclit_email" rows="4" cols="50" autofocus=""></textarea><input type="hidden" name="founder_piclit" id="founder_piclit" value=""></li>
<li><input type="hidden" name="piclit_bcc" class="piclit_bcc" value="0"></li>
<li>bcc: <input type="checkbox" name="piclit_bcc" class="piclit_bcc" value="1">
<?php wp_nonce_field( 'fiveb_ajax_nonce', 'fiveb_nonce_field' ); ?></li>
<li><input type="submit" name="submit" value="Send"></li>
</ul>
</form>
<div id="ajax_success" style="display: none">Email sent.</div>
<div id="ajax_error" style="display: none">There was an error. Sorry your email was not sent.</div>
</div>
Javascript
<script>
jQuery('#ajaxformid').submit(function(e) {
e.preventDefault();
var piclit_email = jQuery( "#piclit_email" ).val();
if (piclit_email == '')
alert("Please fill in all fields to send an email.");
else {
var founder_piclit = jQuery( "#founder_piclit" ).val();
// alert (founder_piclit);
var piclit_bcc = jQuery('.piclit_bcc').val();
var formData = {
piclit_email: piclit_email,
founder_piclit: founder_piclit,
piclit_bcc: piclit_bcc,
action: 'fiveb_ajax_mail',
};
jQuery.ajax({
type : 'POST',
url : '<?php echo admin_url( 'admin-ajax.php' ); ?>',
dataType : 'json',
data : formData,
}).done(function(data) {
console.log(data);
}).fail(function(data) {
console.log(data);
});
}
});
</script>
and php:
function fiveb_function() {
$subject = 'View A Founder PIC-LIT from piclits.com';
$piclit_email = strval($_REQUEST['piclit_email']);
$founder_piclit = strval($_REQUEST['founder_piclit']);
$piclit_bcc = strval($_REQUEST['piclit_bcc']);
if ($piclit_bcc) {
$headers[] = 'Bcc: '.$piclit_email;
}
$message = '<html><head><title>Founder PIC-LIT</title></head><body><table border="0" cellspacing="2" cellpadding="20" bgcolor="#ffffff" width="100%"><tbody><tr><td></td><td width="600"><p style="text-align: center">Hello!<br />View A Founder PIC-LIT from piclits.com.</p></td><td></td></tr><tr><td></td><td><img src="'.$founder_piclit.'" alt="Founder PIC-LIT" width="600" style="display:block;width:100%" /></td><td></td></tr></tbody></table></body></html>';
$headers[] = 'From: PIC-LITS <hello#piclits.com>';
$headers[] = 'Content-Type: text/html; charset=UTF-8';
if ($bcc) $sent_mail = wp_mail( "", "$subject", $message, $headers );
else $sent_mail = wp_mail( "$piclit_email", "$subject", $message, $headers );
if ($sent_mail) {
echo ('email sent');
die();
} else {
echo ('There was an error. Sorry your email was not sent.');
die();
}
}
add_action("wp_ajax_fiveb_function", "fiveb_function");
add_action("wp_ajax_nopriv_fiveb_function", "fiveb_function");
Seems like I am so close but I cannot get the script to stop hanging up on admin-ajax.php. Any help would be so appreciated! Maybe it has something to do with my popup? I am out of ideas
Your code will look like this.
Note - Form action should be blank.
<form action="" method="POST" id="ajaxformid">
</form>
wp_enqueue_script( 'custom-js', get_stylesheet_directory_uri().'/assets/js/custom.js', array(), '1.0.0', 'true' );
wp_localize_script( 'custom-js', 'fiveb_ajax_mail', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
add_action("wp_ajax_fiveb_ajax_mail", "fiveb_ajax_mail");
add_action("wp_ajax_nopriv_fiveb_ajax_mail", "fiveb_ajax_mail");
function fiveb_ajax_mail()
{
$formdata = $_post['formdata'];
wp_mail($to,$subject,$message,$header);
return 'true';
wp_die();
}
//add below js in custom.js file
$('#ajaxformid').submit(function (e) {
e.preventDefault();
jQuery.ajax({
type: "post",
dataType: "json",
url: fiveb_ajax_mail.ajax_url,
data : {action: "fiveb_ajax_mail","formdata":"your form data variable place here"},
success: function(msg){
console.log(msg);
}
});
}
In my local system, it is working fine.
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");
}
}
});
}
I am newer to ajax. I want to add two fields using ajax and codeigniter.. When i click the submit button the two fields are added but the alert message is not showing also the page is not refreshing. Can any one solve my issue.. Thanks in advance..
This is my Form
<form action="" id="suggestionsform" method="post">
<div class="form-group">
<label for="suggname">Name</label>
<input type="text" class="form-control" name="suggname" id="suggname" placeholder="Enter Your Name" required="required">
</div>
<div class="form-group">
<label for="suggmessage">Suggestion</label>
<textarea class="form-control" rows="4" name="suggmessage" id="suggmessage"
placeholder="Enter Your Suggestions"></textarea>
</div>
<button type="submit" class="btn btn-default" id="suggestions">Submit</button>
</form>
This is my ajax codeing
<script>
// Ajax post
$(document).ready(function() {
$("#suggestions").click(function(event) {
event.preventDefault();
var name = $("#suggname").val();
var suggestion = $("#suggmessage").val();
$.ajax({
type: "POST",
url: "<?php echo site_url('Helen/addSuggestion')?>",
dataType: 'json',
data: {name: name, suggestion: suggestion},
success: function(data) {
if (data=='true')
{
alert("Thank you for your Suggestion");
}
}
});
});
});
</script>
Controller Coding
public function addSuggestion()
{
$data=array(
'name' => $this->input->post('name'),
'messages' => $this->input->post('suggestion'),
'date' => now()
);
$data=$this->Helen_model->setSuggestion($data);
echo json_encode($data);
}
Model Coding
public function setSuggestion($data){
$this->db->insert('messages', $data);
return $this->db->insert_id();
}
You can achieve like this..
Model
Return true status if insert successful.
public function setSuggestion($data){
$res = $this->db->insert('messages', $data);
if($res){
$result = array('status'=>true,'message'=>'successful');
}
else
{
$result = array('status'=>false,'message'=>'failed');
}
return $result;
}
JS
Check status in success function
<script>
// Ajax post
$(document).ready(function() {
$("#suggestions").click(function(event) {
event.preventDefault();
var name = $("#suggname").val();
var suggestion = $("#suggmessage").val();
$.ajax({
type: "POST",
url: "<?php echo site_url('Helen/addSuggestion')?>",
dataType: 'json',
data: {name: name, suggestion: suggestion},
success: function(response) {
data = eval(response);//or data = JSON.parse(response)
if (data.status ===true)
{
alert("Thank you for your Suggestion");
}
}
});
});
});
</script>
Try to use echo '{"status": "success"}; on your controller response.
That i see on your script you are shown database response.
I'd made a form using CI and have a native form_validation() library to validate each fields input, I using jQuery post to callback the input to check whether each fields is valid, how if I want each error to populate into form_error() next to each field instead of validation_errors()?
Please refer to below:
view:
<script>
$("#btnregister").click(function() {
var parameters = $("#reg_form").serialize();
$.post(baseurl+'pages/registration', parameters, function(data) {
if(data == "ok") {
//show success message
}else{
$("#error").html(data);
}
}, "html");
});
</script>
<div id="error"></div>
<form id="reg_form" method="post">
<p>
<label for="reg_username">Username</label><br />
<input type="text" id="reg_username" name="reg_username" value="<?php echo set_value('reg_username'); ?>">
<?php echo form_error('reg_username'); ?>
</p>
<p>
<label for="reg_email">Email</label><br />
<input type="text" id="reg_email" name="reg_email" value="<?php echo set_value('reg_email'); ?>">
<?php echo form_error('reg_email'); ?>
</p>
<p><input type="button" id="btnregister" value="Register"></p>
</form>
</div>
Controller:
public function registration(){
$this->load->library('form_validation');
$this->form_validation->set_rules('reg_username', 'Username', 'trim|required|min_length[4]|max_length[15]|xss_clean|is_unique[users.username]');
$this->form_validation->set_rules('reg_email', 'Email', 'trim|required|valid_email|is_unique[users.email]');
if($this->form_validation->run() == FALSE){
echo validation_errors();
}else{
// insert to db
echo "ok";
}
}
Thanks for help.
You'll have to build your own error array. It would be nice if we could access the
Form_validation's $_error_array but unfortunately it's protected and there's no access method for it.
I'm going to change your controller to output a json response to make this easier:
public function registration()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('reg_username', 'Username', 'trim|required|min_length[4]|max_length[15]|xss_clean|is_unique[users.username]');
$this->form_validation->set_rules('reg_email', 'Email', 'trim|required|valid_email|is_unique[users.email]');
if ($this->form_validation->run())
{
$response['status'] = TRUE;
}
else
{
$errors = array();
// Loop through $_POST and get the keys
foreach ($this->input->post() as $key => $value)
{
// Add the error message for this field
$errors[$key] = form_error($key);
}
$response['errors'] = array_filter($errors); // Some might be empty
$response['status'] = FALSE;
}
// You can use the Output class here too
header('Content-type: application/json');
exit(json_encode($response));
}
Now your ajax success callback can read the status and errors keys of the response. You can loop through data.errors and add each one to the input field:
$("#reg_form").submit(function() {
var form = $(this);
$.post(baseurl+'pages/registration', form.serialize(), function(data) {
if (data.status == true) {
//show success message
}else{
$.each(data.errors, function(key, val) {
$('[name="'+ key +'"]', form).after(val);
});
}
}, "json");
});
Another easy way is to post the form to itself, and have your ajax response reload the entire form - that way the messages and validation filters will be taken care of server-side.
I'm trying to make a HTML contact form. Here's my code
`Get in Touch
<p class="success-sending-message">Thank you, your message has been sent!</p>
<p class="error-sending-message">There has been an error, please try again.</p>
<div id="contact-form">
<form action="" id="contactForm" class="styled" method="post">
<label for="contact_name">Name</label>
<input type="text" tabindex="3" id="contact_name" name="contact_name" value="" class="requiredField textbox" />
<label for="contact_email">Email</label>
<input type="text" tabindex="4" id="contact_email" name="contact_email" value="" class="requiredField email textbox" />
<label for="contact_subject">Subject</label>
<input type="text" tabindex="5" id="contact_subject" name="contact_subject" value="" class="requiredField textbox" />
<label for="contact_message">Your Message</label>
<div class="textarea-wrap">
<textarea cols="65" rows="9" tabindex="6" id="contact_message" name="contact_message" class="requiredField"></textarea>
</div>
<div class="form-section">
<button class="button" tabindex="7" type="submit" id="born-submit" name="born-submit">Send Message</button>
<input type="hidden" name="submitted" id="submitted" value="true" />
<span class="sending-message"><img src="css/images/loading-light.gif" /> Sending...</span>
</div>
</form>
</div>`
And here's my validation script
$(window).load(function() {
/* Ajax Contact form validation and submit */
jQuery('form#contactForm').submit(function() {
jQuery(this).find('.error').remove();
var hasError = false;
jQuery(this).find('.requiredField').each(function() {
if(jQuery.trim(jQuery(this).val()) == '') {
if (jQuery(this).is('textarea')){
jQuery(this).parent().addClass('input-error');
} else {
jQuery(this).addClass('input-error');
}
hasError = true;
} else if(jQuery(this).hasClass('email')) {
var emailReg = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if(!emailReg.test(jQuery.trim(jQuery(this).val()))) {
jQuery(this).addClass('input-error');
hasError = true;
}
}
});
if(!hasError) {
jQuery(this).find('#born-submit').fadeOut('normal', function() {
jQuery(this).parent().parent().find('.sending-message').show('normal');
});
var formInput = jQuery(this).serialize();
var contactForm = jQuery(this);
jQuery.ajax({
type: "POST",
url: jQuery(this).attr('action'),
data: formInput,
success: function(data){
contactForm.parent().fadeOut("normal", function() {
jQuery(this).prev().prev().show('normal'); // Show success message
});
},
error: function(data){
contactForm.parent().fadeOut("normal", function() {
jQuery(this).prev().show('normal'); // Show error message
});
}
});
}
return false;
});
jQuery('.requiredField').blur(function() {
if(jQuery.trim(jQuery(this).val()) != '' && !jQuery(this).hasClass('email')) {
if (jQuery(this).is('textarea')){
jQuery(this).parent().removeClass('input-error');
} else {
jQuery(this).removeClass('input-error');
}
} else {
if (jQuery(this).is('textarea')){
jQuery(this).parent().addClass('input-error');
} else {
jQuery(this).addClass('input-error');
}
}
});
jQuery('.email').blur(function() {
emailReg = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if(emailReg.test(jQuery.trim(jQuery(this).val())) && jQuery(this).val() != '') {
jQuery(this).removeClass('input-error');
} else {
jQuery(this).addClass('input-error');
}
});
jQuery('.requiredField, .email').focus(function(){
if (jQuery(this).is('textarea')){
jQuery(this).parent().removeClass('input-error');
} else {
jQuery(this).removeClass('input-error');
}
});
});
My form is working properly, After filling details It is showing me "Thank you, your message has been sent!" But where is this message going, I don't have any of the process.php file and all. I want that email should be send to my email id.
Bonjour ... Look in the firebug or chrome developper tools console to see the post trace.
In your php file, you can put echos or var_dump to be sure all it's ok.
Another thing ... the form action is empty.
Currently there's no where it is going. Give where it needs to go in the action="" attribute of the <form>. And also, in the actioned URL, typically, a PHP file, give this code:
<?php
if (count($_POST))
{
$name = $_POST["contact_name"];
$email = $_POST["contact_email"];
$subject = $_POST["contact_subject"];
$message = $_POST["contact_message"];
$mail = "Name: $name\nEmail: $email\nSubject: $subject\nMessage: $message";
if (mail("mymail#domain.com", "New Mail from Contact Form", $mail))
die ("OK");
else
die ("Fail");
}
?>
Also, you need to make a small correction in your JavaScript AJAX Call. Replace this way:
jQuery.ajax({
type: "POST",
url: jQuery(this).attr('action'),
data: formInput,
success: function(data){
if (data == "OK")
contactForm.parent().fadeOut("normal", function() {
jQuery(this).prev().prev().show('normal'); // Show success message
});
else
alert ("Message not sent!");
},
error: function(data){
contactForm.parent().fadeOut("normal", function() {
jQuery(this).prev().show('normal'); // Show error message
});
}
});
Test if your server supports SMTP through PHP Script
Create a small file, which has this content, say mail.php:
<?php
var_dump(mail("yourmail#gmail.com", "Testing Message", "This mail was sent from PHP Script."));
?>
And try to access the file and see what you are getting. Please update the same in your question.