Change the codeigniter view contents without reload - ajax

I have created an email utility which shows the email-ids from which email is received their subject line and date. Every email id has a checkbox alongside it. Whichever checkbox is clicked the email is sent to that email id. My problem is that i want to display "message sent successful" or error message on the same page without reload.
I think, it is possible with ajax, but I don't know how. Here is my view:
<?php echo form_open_multipart('accessmail/sendmail'); ?>
<div>
//here I display my emails
<div>
<div class="table_wrap1">
<div>Subject:</div>
<div><input type="text" required="required" id="subject" name="subject"></div>
</div>
<div class="table_wrap1">
<div>Email:</div>
<div><input type="email" id="replyto" name="replyto"></div>
</div>
<div id="txteditor">
<textarea name="textarea">
</textarea>
<button name="submit" value="process" type="submit">Send</button>
</div>
<?php } ?>
</div>
</form>
And my controller name is "accessmail", method name is "send mail":
public function sendmail()
{
$this->load->library('email');
$count=$this->input->post('mailcount');
$subject = $this->input->post('subject');
$msg = $this->input->post('textarea');
$replyto = $this->input->post('replyto');
//variable for checking whether any email id is selected or not
$status=0;
//for sending email to checked email id's
for($i=0;$i<$count;$i++)
{
// check whether the checkbox for a particular email id is checked or not
if(!$this->input->post('emailid'.$i))
{
continue;
}
else
{
//set the values for this email and send it
$this->email->from('abc#abc.com', 'abc');
$this->email->subject($subject);
$this->email->message($msg);
$idtosend = $this->input->post('emailid'.$i);
$this->email->to($idtosend);
if ($this->email->send())
{
$status++;
}
}
}
//for sending email to email id provide in textbox
if(!empty($replyto))
{
$this->email->from('abc#abc.com', 'Abc');
$this->email->subject($subject);
$this->email->message($msg);
$this->email->to($replyto);
if ($this->email->send())
{
$status++;
}
}
if($status>0)
{
//this message should be displayed on the same page along with other contents of the page
echo "Your message has been sent";
}
if($status==0)
{
//this message should be displayed on the same page along with other contents of the page
echo "Select any Email-id first";
}
}
my problem is the success message should be displayed on the same view preserving the contents of the page. Thanks in advance.

Yeah, that's a typical Ajax thing. But unfortunately that's a bit too big to just deliver you the answer (or I am too lazy, but you would benefit the most out of it, by figuring this out yourself).
My suggestion is, that you learn jQuery and Ajax (if you don't know that already).
For your problem, you specifically want to send the mails to your PHP-Function sendmail() via Ajax. This function either returns a Success- or an Errormessage (with json_encode() around it, that's how I'd do it). The Ajax-function then displays the message.
This is neither tested nor should be the final solution... just a hint:
The PHP Function:
<?php
function sendmail()
{
$mails = $_POST['mails'];
$countEmails = count($mails);
$success = 0;
foreach ($mails as $mail) {
// Check and send mails here
if ($this->email->send()) {
$success++;
}
}
if ($success < $countEmails) {
echo json_encode('One or more E-Mails were not sent');
return;
}
echo json_encode('E-Mails successfully sent');
}
Ajax Function (don't forget to include jquery):
$('#id_of_your_send_mails_button').bind('click', function(evt) {
evt.preventDefault();
$.ajax({
type: 'post',
url: 'path/to/sendmail',
dataType: 'json',
data: {
mails: $('#id_of_your_form').serialize();
},
success: function (data) {
$('#id_of_your_status_div').html(data);
}
});
});
Again, this is just pseudocode-ish stuff, to get you to it, but you have to do the learning on your own.
Hope that helps a bit.
EDIT
You might also try:
$('#id_of_your_send_mails_button').bind('click', function(evt) {
evt.preventDefault();
$.ajax({
type: 'post',
url: 'path/to/sendmail',
dataType: 'json',
data: {
name: $('#id_of_your_name_field').val(),
email: $('#id_of_your_name_field').val() // and so forth
},
success: function (data) {
$('#id_of_your_status_div').html(data);
}
});
});

Related

How to validate onkeyup event without again and again sending post request to route in larravel

validate Activity function with Ajax code
$(document).on('keyup','#activity_name',function () {
var error_activity = '';
var activity = $('#activity_name').val();
var _token = $('input[name="_token"]').val();
$.ajax({
type : 'post',
url : '{{ url('checkactivity') }}',
data :{activity:activity, _token:_token},
success:function (result) {
if(result == 'unique'){
$('#activity_status').html('<lable class="text-sucess" style="color: blue"></lable>');
$('#activity').removeClass('has-error');
$('#activity_btn').attr('disabled',false);
}
else
{
$('#activity_status').html('<lable class="text-danger">Try Another!</lable>');
$('#activity').addClass('has-error');
$('#activity_btn').attr('disabled','disabled');
}
}
});
});
My input field and here he is always call an event Onkeyup when ever i enters a single word in my input field and on each word he is sending a post request.
<div class="form-group">
<label for="checkbox">Group</label>
<select class="form-control form-control-sm" id="activitygroup" name="activitydeleverable">
<option>Select</option>
#foreach(App\Groups::all() as $group_name)
<option value="{{ $group_name->id }}">{{ $group_name->name }}</option>
#endforeach
</select>
</div>
<button type="submit" id="activity_btn" onclick="insertactivity()" class="btn btn-info">Insert</button>
here is my Controller Function
function checkactivity(Request $request){
$data = Activities::whereName($request->activity)->first();
if (!is_null($data)){
echo 'not_unique';
}
else
{
echo 'unique';
}
}
My code is work perfect, but i have a problem. On each single word my onkeyup Event Ajax send a post request to db and check data is available in db or not. but i have to stop this to doing again and again Post request. it's may do slow my system so i have to solve this please solve this logical issue i have to stop this Post requests or need only one post request.
You can see no of request in image
You will find all the information regarding your desired solution in this solved question:
How to delay the .keyup() handler until the user stops typing?
proper way of doing ajax request is use make it single at a time.
var req = null;
$(document).on('keyup','#activity_name',function () {
var error_activity = '';
var activity = $('#activity_name').val();
var _token = $('input[name="_token"]').val();
if (req != null) req.abort();
req = $.ajax({
type : 'post',
url : '{{ url('checkactivity') }}',
data :{activity:activity, _token:_token},
success:function (result) {
if(result == 'unique'){
$('#activity_status').html('<lable class="text-sucess" style="color: blue"></lable>');
$('#activity').removeClass('has-error');
$('#activity_btn').attr('disabled',false);
}
else
{
$('#activity_status').html('<lable class="text-danger">Try Another!</lable>');
$('#activity').addClass('has-error');
$('#activity_btn').attr('disabled','disabled');
}
}
});
});
try to make it delay method.
function delay(fn, ms) {
let timer = 0
return function(...args) {
clearTimeout(timer)
timer = setTimeout(fn.bind(this, ...args), ms || 0)
}
}
$('#input').keyup(delay(function (e) {
console.log('Time elapsed!', this.value);
}, 500));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> </script>
<label for="input">Try it:
<input id="input" type="text" placeholder="Type something here..."/>
</label>

Ajax calling situation on asynchorous call

I am stuck with my specific problem.
I want to return false if the data comes using ajax.
Here is my code:
<script>
function verifydom(form)
{
var domnam = form.domname.value;
if (domnam == "")
{
alert("Please enter the Domain Name");
form.domname.focus();
return false;
}
else if(domnam.indexOf('.gov.in') <= 0){
alert("Please enter valid domain name");
form.domname.focus();
return false;
}
else{
$.ajax({
type: "get",
url: "calling.php",
data: "domnam="+domnam,
success: function(msg){
if(msg!== ""){
alert(msg);
}
}
});
return false;
}
return true;
}
</script>
<form name="frmDelegate" action="dlgdetail.php" method="POST"
onsubmit="return verifydom(document.frmDelegate);" autocomplete="off">
input type="text" name="domname" id= "domname"
onkeyup="showResult(this.value);"/> <input type="hidden"
id="chkmsg" value=""/>
<input type="submit" value="Go" name="submit" />
</form>
The ajax call under 'else condition' would return some error message, So if an error comes, I want the form not to be submitted.
Okay, the problem is 'Else will work every time whether Ajax gives a message or not.
How can I overcome this situation?
Rather than blank message I would prefer to return a JSON message from the calling.php file.
$arr = array( "status" => "error", "message" => "error found");
echo json_encode($arr);
By doing this you are easily allowed to check whether the error is there or not. If JSON have any message then you should check by below code.
$.ajax({
type: "get",
url: "calling.php",
data: "domnam="+domnam,
success: function(msg){
var data = jQuery.parseJSON(msg);
if(data.status == "error"){ // no need to check strictly
return false;
}
}
});

ASP MVC 3: Client Validation not working properly when submitting a form using AJAX

I have the following scenario, I have a for that I'm submitting using ajax using the following code:
$("#cmdAjaxSave").click(function (evt) {
evt.preventDefault();
var $form = $('#frmItem');
if ($form.valid()) {
ajaxSave();
}
});
function ajaxSave() {
if (!onBeforeSubmit()) return; //item is not valid, so the ajax call should not be executed
//var token = $('[name=__RequestVerificationToken]').val();
popup('ajaxSplash');
$.ajax({
type: "POST",
url: '#Url.Action("Index")',
data: $("#frmItem").serialize(),
success: function (html) {
//console.log(html);
$("#formDiv").empty();
$("#formDiv").append(html);
initItemPage();
alert("Item was saved successfully");
},
error: function () { popup('ajaxSplash'); onFailure(); }
});
}
The problem I'm seeing here is that even though "frmItem" is returning "true" when I arrive clientside the ModelState is not valid. Specifically for three properties, which actually has the correct value.
Digging into the code made by the developer who originally coded this I found that for instance this property:
#Html.TextBoxFor(model => model.Item.Service.CPC_BW, htmlAttributes: new { #class = "Text", #onkeyup = "validItem();", #id = "SrvCPCBlk" })
Is actually defined like this:
private double _CPC_BW;
[Required]
[Range(0, 100000, ErrorMessage = "CPC value required")]
public string CPC_BW { get { return String.Format("{0:F}", _CPC_BW); } set { _CPC_BW = Convert.ToDouble(value); } }
I think he did it because TextBoxFor does not offers an obvious way to format a number and even though it looks fishy I don't know how could this be causing the error.
The Html of the form is rendered like this
<div id="itemPopUpForm">
#{Html.EnableClientValidation();}
<div id="formDiv">
#{ Html.RenderPartial("ItemData", Model, new ViewDataDictionary() { { "Machines", ViewBag.Machines }, { "WarehouseList", ViewBag.WarehouseList }, { WebConstants.FORM_ID_KEY, #ViewData[WebConstants.FORM_ID_KEY] } }); }
</div>
</div>
The partial view contains the form that is submited in the ajax request.
I think you should try and clear the model state then test whether its valid...
Its a common issue.
ModelState.Clear();
ModelState.IsValid();

Ajax request returns every html element of the page

i am a new bie to Ajax and currently making a form submission using php and ajax(for a wordpress plugin). My js code is
$("#submit").click(function(){
var form_data = $('.myform').serialize();
$.ajax({
type: "POST",
url: "main_form.php",
data: form_data,
success: function(html){
$('div#ajax_output').html(html);
}
});
return false;
});
and my entire page structure looks like
<div class="header"> ....</div>
<div class="navigation"> ....</div>
< ?php
if($_post) {
//form validation codes
if(condition true) echo "Success message";
else echo "Error";
}
?>
<div id="ajax_output"></div>
<form class="myform">
//form elements
</form>
//And the above javascript here(that click fn)
Now my problem is, as i am submitting the form data to the same page(it is unavoidable and cannot make it separate), the ajax returns inside <div id="ajax_output"></div> all the page contents header, navigation, etc including echo "Success message".
Can any one tell me how to output only php validation result?
output buffering may help you
<?php // insert that at the beginning of the page
ob_start();
?>
<div class="header"> ....</div>
<div class="navigation"> ....</div>
<?php
if($_post) {
//form validation codes
if(condition true) echo "Success message";
else echo "Error";
ob_end_clean();
exit(1);
} else {
echo ob_get_clean();
}
?>
<div id="ajax_output"></div>
<form class="myform">
//form elements
</form>
//And the above javascript here(that click fn)
You'd better restructure code, though. I.e. move processing of post data to the beginning of the page and then just exit if it should be processed.
Usually, such problems are solved on server side, not in javascript.
I mean, server should return correct html part w/o heading, navigation, etc., client should not parse all that stuff to get what it needs.
You may return after checking the form data, or do the form validation in another action.
The code example is not complete, but you can get the gist of it hopefully!
Add a variable to post data.
Javascript:
$("#submit").click(function(){
var form_data = $('.myform').serialize();
form_data.isAjax = true;
$.ajax({
type: "POST",
url: "main_form.php",
data: form_data,
success: function(html){
$('div#ajax_output').html(html);
}
});
return false;
});
PHP:
<?php
if(array_key_exists("isAjax", $_POST) {
if($_post) {
//form validation codes
if(condition true) {
echo "Success message";
}
else {
echo "Error";
}
}
}
else {
$mainPage = '<div class="header"/>>';
$mainPage += '<div class="navigation"/>';
$mainPage += '<div id="ajax_output"/>';
$mainPage += '<form class="myform"/>';
$mainPage += '<javascript />';
echo $mainPage;
}

Advice on my jQuery Ajax Function

So on my site, a user can post a comment on 2 things: a user's profile and an app. The code works fine in PHP but we decided to add Ajax to make it more stylish. The comment just fades into the page and works fine.
I decided I wanted to make a function so that I wouldn't have to manage 2 (or more) blocks of codes in different files. Right now, the code is as follows for the two pages (not in a separate .js file, they're written inside the head tags for the pages.):
// App page
$("input#comment_submit").click(function() {
var comment = $("#comment_box").val();
$.ajax({
type: "POST",
url: "app.php?id=<?php echo $id; ?>",
data: {comment: comment},
success: function() {
$("input#comment_submit").attr("disabled", "disabled").val("Comment Submitted!");
$("textarea#comment_box").attr("disabled", "disabled")
$("#comments").prepend("<div class=\"comment new\"></div>");
$(".new").prepend("<?php echo $_SESSION['username']; ?><p class=\"commentdate\"><?php echo date("M. d, Y", time()) ?> - <?php echo date("g:i A", time()); ?></p><p class=\"commentpost\">" + comment + "</p>").hide().fadeIn(1000);
}
});
return false;
});
And next up,
// Profile page
$("input#comment_submit").click(function() {
var comment = $("#comment_box").val();
$.ajax({
type: "POST",
url: "profile.php?username=<?php echo $user; ?>",
data: {comment: comment},
success: function() {
$("input#comment_submit").attr("disabled", "disabled").val("Comment Submitted!");
$("textarea#comment_box").attr("disabled", "disabled")
$("#comments").prepend("<div class=\"comment new\"></div>");
$(".new").prepend("<?php echo $_SESSION['username']; ?><p class=\"commentdate\"><?php echo date("M. d, Y", time()) ?> - <?php echo date("g:i A", time()); ?></p><p class=\"commentpost\">" + comment + "</p>").hide().fadeIn(1000);
}
});
return false;
});
Now, on each page the box names will always be the same (comment_box and comment_submit) so what do you guys think of this function (Note, the postComment is in the head tag on the page.):
// On the page, (profile.php)
$(function() {
$("input#comment_submit").click(function() {
postComment("profile", "<?php echo $user ?>", "<?php echo $_SESSION['username']; ?>", "<?php echo date("M. d, Y", time()) ?>", "<?php echo date("g:i A", time()); ?>");
});
});
Which leads to this function (which is stored in a separate file called functions.js):
function postComment(page, argvalue, username, date, time) {
if (page == "app") { var arg = "id"; }
if (page == "profile") { var arg = "username"; }
var comment = $("#comment_box").val();
$.ajax({
type: "POST",
url: page + ".php?" + arg + "=" + argvalue,
data: {comment: comment},
success: function() {
$("textarea#comment_box").attr("disabled", "disabled")
$("input#comment_submit").attr("disabled", "disabled").val("Comment Submitted!");
$("#comments").prepend("<div class=\"comment new\"></div>");
$(".new").prepend("" + username + "<p class=\"commentdate\">" + date + " - " + time + "</p><p class=\"commentpost\">" + nl2br(comment) + "</p>").hide().fadeIn(1000);
}
});
return false;
}
That's what I came up with! So, some problems: When I hit the button the page refreshes. What fixed this was taking the return false from the function and putting it into the button click. Any way to keep it in the function and have the same effect?
But my real question is this: Can any coders out there that are familiar to jQuery tell me techniques, coding practices, or ways to write my code more efficiently/elegantly? I've done a lot of work in PHP but I know that echoing the date may not be the most efficient way to get the date and time.
So any tips that can really help me streamline this function and also make me better with writing jQuery are very welcome!
I would first make my forms have all the data so that if the user doesn't have javascript the page still will work:
<form action="profile.php" id="comment_form">
<input type="hidden" name="username" value="<?php echo $user; ?>" />
<textarea id="comment_box" name="comment"></textarea>
<input type="submit" id="comment_submit" value="Submit" />
</form>
<form action="app.php" id="comment_form">
<input type="hidden" name="id" value="<?php echo $id; ?>" />
<textarea id="comment_box" name="comment"></textarea>
<input type="submit" id="comment_submit" value="Submit" />
</form>
Then your javascript can be:
$('#comment_form').submit(function(e){
e.preventDefault();
var form = $(this),
submit = $("#comment_submit").attr("disabled", "disabled");
$("#comment_box").attr("disabled", "disabled");
$.ajax({
type: "POST",
url: form.attr('action'),
data: form.serialize(),
success: function(comment) {
submit.val("Comment Submitted!");
$("<div class=\"comment new\"></div>").prependTo("#comments")
.prepend(comment)
.hide()
.fadeIn(1000);
}
});
});
I would have my ajax request that submits the comment return the html formated comment rather then build it in javascript so that I don't have to update the template in two places. I am also using the submit event on the form rather then the click event on a button since it caches forms getting submitted by other ways then clicking a button.
To address your big overarching question, I'd suggest getting a copy of jQuery In Action from your local library as well as a good JavaScript book (do a search in SO to find a couple).

Resources