unable to show success message after submitting a form using ajax - javascript

I am sending email using ajax after when ajax form is submitted.
Here is my php controller code:
If i keep the email sending code inside this function then the SUCCESS message is not showing on the html page. But if i remove the Email sending code from that function then SUCCESS message is showing.
public function sendedits()
{
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<li class="errorlist">', '</li>')->set_rules('menu_name', 'Title', 'trim|required|min_length[2]|max_length[255]|xss_clean');
//user is logged in proceed the next work
if (!$this->form_validation->run())
{ //False
$this->_status['status'] = "error";
$this->_status['message'] = $this->load->view('commonfiles/ajax_error_display_1', '', TRUE);
}
else if ($this->form_validation->run() && $this->input->post('myId')=='')//myId=just for checking robot or human
{ //TRUE block
$fname=$this->input->post('menu_name');
$sendersemail=$this->input->post('changes_made');
$intrested_message=$this->input->post('content');
$config['protocol'] = 'smtp';
$config['smtp_host'] = 'ssl://smtp.googlemail.com';
$config['smtp_port'] = 465;
$config['smtp_user'] = 'asdsdsd#gmail.com';
$config['smtp_pass'] = 'sdsfsdfsdfsdfsds';
$this->load->library('email', $config);
$this->email->set_newline("\r\n");
//$this->email->from($sendersemail, $fname);
$this->email->to('ssdd#myemil.com');
$this->email->subject('User Edited article of : '.$fname);
$message = '<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<table cellspacing="0" cellpadding="0" style="border-collapse:collapse;width:98%;background-color:whitesmoke" border="1">
<tbody>
<tr>
<td colspan=2><h2> '.$fname.'</h2></td>
</tr>
<tr>
<td width=50%>First Name </td>
<td width=50%>'.$fname.'</td>
</tr>
<tr>
<td width=50%>Email </td>
<td width=50%>'.$sendersemail.'</td>
</tr>
<tr>
<td width=50%>Message </td>
<td width=50%>'.$intrested_message.'</td>
</tr> </tbody> <table> </body></html> ';
$this->email->message($message);
$this->email->send();
$this->_status['message'] = 'Thankyou for your edits. We will review it before publishing.';
$this->_status['status'] = "success";
}
echo json_encode($this->_status);
}
Ajax function for submitting the form
<script type='text/javascript'>
$(document).ready(function() {
var _status = $('#status');
$('#sub2').click(function(e) {
_status.html('');
var postData = $('#form_id').serializeArray();
var formURL = $('#form_id').attr("action");
$.ajax({
url: formURL,
type: "POST",
data: postData,
dataType: "json",
success: function(dat) {
if (dat.status === 'success') {
_status.html('<span class="success">' + dat.message + '</span>');
}
else if (dat.status === 'fail') {
}
else
{
_status.html('<span class="err">' + dat.message + '</span>');
}
},
error: function(e) {
alert("Ooops! Try again later or else sends us message regarding this issue. Thankyou!");
}
});
});
});
</script>

So Im guessing this is using the phpmailer library, do you have that installed (it might come as default depending on your platform)
The first thing that I can see is that $sendersemail is not defined. Try inserting a string instead of the variable. The phpmailer library is terrible for cactching errors, I can never figure out how to tell where the errors are either!
If that doesnt work, try outputting to the console after the line you think is giving you the error. If you use:
echo("email sent");
Then you should see it in the browser console as the code is being processed. Hopefully you can see where the error is coming from then.

Related

How To Pass Dynamically Added Table Rows Form Values to Javascript Using Post to Send Database

I am using Laravel.
I have dynamic rows and each row has own form with individual values.
I am trying to pass each row form with values when submit the button to Javascript.
To retrieve data in Server.I don't want to refresh page because I am using Modal.
Here is my Code
<table id="selectedWagesTable" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Worker</th>
<th>Balance</th>
<th>Confirm</th>
</tr>
</thead>
<tbody>
#foreach($items as $item)
<tr>
<td class="standartTable2">
<?php echo $item['worker_id'] ?>
</td>
<td class="standartTable2">
£ <?php echo $item['balance'] ?>
</td>
<td class="standartTable2">
{{ Form::open(['id'=>item['workerId'],'name' => item['workerId']]) }}
{{ Form::hidden('workerId', $item['workerId'],['id' => $item['workerId'])}}
{{ Form::hidden('balance', $item['balance'],['id' => $item['balance']])}}
{{ Form::submit('Click To Confirm',
array(
'class'=>'btn btn-sm btn-success',
'id'=>'submitButton',
'oncontextmenu'=>'return false',
)) }}
{{ Form::close() }}
</td>
</tr>
#endforeach
</tbody>
Script
<script type="text/javascript">
$(document).ready(function(){
$("#submitButton").click(function(e){
e.preventDefault();
$.get('hpoAccounts',function(data){
console.log(data);
});
});
$("#submitButton").click(function(e) {
e.preventDefault();
var workerId = $('#workerId').val();
var balance = $('#balance').val();
$.post('hpoAccounts',{
workerId:workerId,
balance:balance
},
function(response,status){
console.log(response);
});
});
});
What you want to achieve could be done using jQuery library
Since you have several forms, you need to add a submit listener to all of them ( $("form").submit ).
To prevent the REFRESH we need to send the data using ajax ( $.ajax ) and prevent default SUBMIT behavior ( e.preventDefault() ).
Note also that we add the listeners to the forms after all the HTML document is ready ( $(document).ready ).
Below code should work after you provide the POST URL.
$(document).ready(function() {
$("form").submit(function(e){
var formData = $(this).serializeArray();
$.ajax({
url : 'your post resource', // put here the URL resoruce where you want POST the data
type: "POST",
data : formData,
success:function(data, textStatus, jqXHR)
{
alert('Do something after data sent!');
},
error: function(jqXHR, textStatus, errorThrown)
{
alert('There was an error!');
}
});
e.preventDefault(); //prevent default action which will prevent also the REFRESH
});
});
I have solved my problem using Javascript.
I removed form and simply added one button to last column.With Javascript when I clicked the button I can pull the values from each row.
<td class="standartTable2">
<button type="button" class="btn btn-success hit">Confirm Payment</button>
</td>
Script
<script type="text/javascript">
$(document).ready(function(){
$(".hit").click(function(){
this.disabled = true;
// nth-child(2) first-child last-child
var hpos_id=$(this).parent().siblings(":first").text();
var balance=$(this).parent().siblings(":nth-child(3)").text();
var dataArray = {hpos_id: hpos_id, balance: balance};
$.ajax({
url : '/confirmPayment', // put here the URL resoruce where you want POST the data
type: "POST",
data : dataArray,
success:function(data, textStatus, jqXHR)
{
//All good
},
error: function(jqXHR, textStatus, errorThrown)
{
alert('There was an error!');
}
});
});
});

Sending php generated form data via Ajax from Dialog box

Hi Guys any help on this? I have a dialog box triggered by a button click that calls my php script to generate a form which needs to be filled and submitted. I want to do the sending and conformation via Ajax. I have been recoding and researching for a few days but nothing on StackExchange or other websites help me with it.
Here's the code:
Dialog box snippet;
$k('#CreateTable').click(function(e){
e.preventDefault();
var Call = $k('#CreateTable').attr('value');//.attr('id');
var util = $k(this).attr('id');//.attr('id');
$k('#dialog').dialog({
autoOpen: false,
title: 'Running Utility for: '+Call,
modal: true,
width: 450,
close: function(event, ui) {
$k("#dialog").dialog('destroy');//event.target
}//END CLOSE
}).dialog('open');
var utility = { 'utility' : util };
$k.ajax({
type: "post",
url: "inc/runUtilities.php",
dataType: "html",
data: utility,
success: function(data) {
$k('#DlgTxt').html(data).fadeIn('slow');
}
});
//return false;
});//END DIALOG
The PHP snippet;
$show .= "<form id='cContact' name='cContact' method='post'>";
// action='".$_SERVER['REQUEST_URI']."'
$show .= '<table align="center" width="425" border="0">
';
$query = "SHOW COLUMNS FROM `".$_SESSION['WorkTable']."`";
if($output = mysqli_query($this->MySQLCxn->MySQLCxn, $query))
{
$columns = array();
while($row = mysqli_fetch_assoc($output))
{
if($row['Field'] == 'id') {}
else
$show .= '
<tr>
<td width="175"><div align="right">'.#$row['Field'].':</div></td>
<td width="155">
<input type="text" name="'.#$row['Field'].'" placeholder="'.#$row['Field'].'" />
</td>
<td width="115"> </td>
</tr>
';
}
}
$show .= '
<tr>
<td>Submit </td><td>
<button type="button" id="cContactSbmt" onclick="doSubmitForm(this); return false;" name="cContactSbmt" value="cContactSbmt">Create contact</button>
<!-- <input type="submit" class="button" value="Save" name="submit"> -->
</td> <td> </td>
</tr>
</table></form>
<div id="thanks">
</div>
';
And the JQuery that i am currently using trying to have it call my php to process the form being sent.
var $j = jQuery.noConflict();
(function($j){
$j(document).ready(function() {
$j("#cContactSbmt").click(function(e){//'click',
e.preventDefault();
alert('cContactSbmt clicked...');
$j.ajax ({
type:"POST",
url:"inc/runUtilities.php",
data: $j(this).serialize(),
success: function(msg){
$j("#thanks").html(msg)
$j(this).modal('hide');
},
error: function(){
alert("failure");
}
});
});
});
})($j);
For some reason its not working nothing showing up in the console as well.
again: i have a dialog box that gets populated via Ajax with a php generated from that needs to get submitted to another php script that is to process it and reply to the dialogs.
Any suggestions?
your php ist not outputting ("echoing") anything. you need to echo whatever you want to return to your ajax-call.
update: plus for debugging try to log the returned data in every success callback, for example:
success: function(data) {
console.log(data);
}
You may need to add an echo to the end of your php snippet..
echo $show;
This echoed html will then be available in your ajax function in the success callback function... as the variable "data"
success: function(data) {
$k('#DlgTxt').html(data).fadeIn('slow');
}
Also you may need to use jQuery .on() in your click function..to submit the form..
http://api.jquery.com/on/
$j("body").on("click", "#cContactSbmt", function(){
});
Hope this helps....
Hi Guys so I got it working with the following changes:
On the form;
<button id="cContactSbmt" onClick="doContactsCreate(\'#cContact\')" type="button" class="form-submit" name="cContactSbmt" value="cContactSbmt">Create contact</button>
I added the onclick method with a callback to a function doContactsCreate(\'#cContact\'), which has the id of the form passed to it.
function doContactsCreate(obj)
{
alert(obj+': cContactSbmt clicked...');
/* */
var frmData = $k(obj).serialize();
$k.ajax ({
type:"POST",
url:"inc/runUtilities.php",
data: frmData,
success: function(data){
$k("#thanks").html(data);
console.log(data);
$k(obj).modal('hide');
},
error: function(){
alert("failure");
}
});
}
I've just enclosed the JQuery code in this function definition and placed it outside the
(function($k){
$k(document).ready(function() {
//rest of JQuery code
})($k);
Don't know why but i think that was the main problem

Passing result from AJAX call to PHP script

I'm working on my first HTML form that performs an AJAX HTTP POST using jQuery. When a user makes a change to an input text field and tabs out of the field it triggers the AJAX script which in turn calls a PHP script which performs a database update.
The AJAX call can be successful but the database update could be unsuccessful (e.g. database related error) - I would like to insert the result of the PHP script into an alert. I can echo out any errors in in my PHP script, but I'm not sure how to get that into the appropriate alert.
Here's my Javascript:
<script type="text/javascript">
$(document).ready(function() {
$("#storeManager").change(function(){
var storeManager = $("#storeManager").val();
$.post('editProject.php', { storeManager: storeManager, id: '1E1DDA14-D2C6-4FC8-BA5F-DBCCC7ABAF7F' }, function(data) {
$("#managerRow").addClass("success");
}).fail(function () {
// no data available in this context
$("#managerRow").addClass("danger");
$("#ajaxAlert").addClass("alert alert-danger");
});
});
});
</script>
Here's the HTML table that contains the input field that triggers the AJAX call:
<table class="table table-striped table-bordered table-hover">
<tbody>
<tr>
<td>Store</td>
<td>Acme Widgets Inc</td>
</tr>
<tr>
<td>Retailer</td>
<td>Acme Corp</td>
</tr>
<tr>
<td>Store ID</td>
<td>9876543</td>
</tr>
<tr>
<td>State</td>
<td>NSW</td>
</tr>
<tr class="" id="managerRow">
<td>Manager</td>
<td>
<input type="text" class="form-control" id="storeManager" name="storeManager" value="Peter Johns">
</td>
</tr>
<tr>
<td>Phone</td>
<td>9222 3456</td>
</tr>
</tbody>
</table>
<div class="" id="ajaxAlert" role="alert"></div>
What I would like to do is, if there is any error from the editProject.php script that it stores in a $error variable and can echo out, to then insert this into the ajaxAlert and add a class: alert:
<div class="alert alert-danger" id="ajaxAlert" role="alert">The error from the database update from the php script appears here</div>
I'm new to jQuery and AJAX and everything I've tried hasn't updated the alert with the new class and alert text and I can't seem to find a similar to example that demonstrates this.
You can use the append() in jquery. Try using
fail(function () {
// no data available in this context
$("#managerRow").addClass("danger");
//append error to the div using its ID
$('#ajaxAlert').append('error from database');
});
Try this: instead of .fail();
var storeManager = $("#storeManager").val();
$.post('editProject.php', { storeManager: storeManager, id: '1E1DDA14-D2C6-4FC8-BA5F-DBCCC7ABAF7F' }, function(data) {
alert(data);
},function (xhr, data, jx) {
// the error function should be mentioned like this with comma after success fucntion
console.log(xhr);//for console logging the error...
alert(xhr);//NOW you will get data and alert will show...
});
index.php
----php start---------
if(isset($_POST['name'])){
$dbc = mysqli_connect('','','','');
$sql = "UPDATE accounts set name='".$_POST['name']." WHERE email='".$_POST['mail']."' LIMIT 1";
if(mysqli_query($dbc, $sql) === true)){
echo 'success'; exit();
}else{
echo 'connection error'; exit();
}
}
----php end ---------
<script>
function test(){
var formDATA = {
'name': $('#input_name').val(),
'mail': $('#input_mail').val()
};
$.ajax({
type: 'POST',
url: 'index.php',
data: formDATA,
success: function(response){
if(response == 'success'){
$('#result').html('Your Update Was Complete');
}else{
$('#result').html();
}
}
});
}
</script>
<input id="input_mail" type="text" value="">
<input id="input_name" type="text" value="">
<button onclick="test();">Test Ajax</button>
<div id="result"></div>
Try something simple, this is a very basic version of ajax and php all in one page. Since the button triggers the function you don't even need a form (doesn't mean you shouldn't use one). But i left it simple so you could follow everything.
Sorry when i added php open and closing tags it didn't show up as code. Also don't forget to include your jquery resources.
WARNING: DO NOT DO QUERIES LIKE THE EXAMPLE, THIS IS A HUGE SECURITY RISK!

Reference to dynamically loaded element

There are folowing code:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<div id="Block"></div>
<script type="text/javascript">
function Request(Mode)
{
jQuery.ajax
({
url: "Script.php",
type: "POST",
dataType: "html",
data: "Mode=" + Mode,
success: function(responce)
{
if (responce == '1')
{
document.getElementById("MessageField").innerHTML = "Message text";
}
else
{
document.getElementById("Block").innerHTML = responce;
}
},
error: document.getElementById("Block").innerHTML = "Request error."
});
}
Request("load form");
</script>
</body>
</html>
And php-script returning html-form or value '1':
<?php
if ($_POST['Mode'] == 'load form')
echo
"
<form id = 'AuthForm' method = 'post' action = ''>
<table border = 1>
<tr>
<td id = 'MessageField'>
&nbsp
</td>
</tr>
<tr>
<td>
<input type = 'submit' name='B1' id='B1' value='Show message' onclick = 'Request()'>
</td>
</tr>
</table>
</form>
";
else echo "1";
?>
Javascript function outputs html-form or changes innerHTML of it's table cell with id="MessageField".
The form appears as supposed, but pressing button I get error:
Uncaught TypeError: Cannot set property 'innerHTML' of null
Script can not execute string:
document.getElementById("MessageField").innerHTML = "Message text";
Why? MessageField already exists when script tries to change it. o_O
There is no element in your given snippet that has the id "Block"

How to display an alert box?

The following code actually submits and with the same i need to display an alert box showing message has been sent.
Code :
<input type="button" class="Jdvs_Btn" onclick="send_reply('SEND_REPLY', <? echo $clsSurvey->feedback_id?>);" value="SEND" style="font-weight:bold;width:95px;height:30px;float:left; margin-right:5px;" />
And the Javascript
Code:
if(action == "SEND_REPLY")
{
if( frm.email.value == "" )
{
alert("Please fill your email.");
frm.email.focus();
return false;
}
else if( validateEmailAddress(frm.email.value) == false )
{
alert("Please fill a valid email.");
frm.email.focus();
return;
}
else if ((tinymce.EditorManager.get('content_to_send').getContent()) == '')
{
alert("Please enter content to send.");
return;
}
else
{
frm.form_action.value = action;
frm.submit();
alert('Message Sent Successfully');
}
}
The code for mailing is:
This is where the validation and other are done, i need to display an alert box here
Code:
function sendReply()
{
echo $this->feedback_id;
$this->checkAndUpdateReply($this->feedback_id,$this->content_to_send);
$Message = nl2br($this->content_to_send);
$mailMessage = "
<html>
<head>
<title>constant('_SHORT_PRODUCT_NAME') - Feedback Mail</title>
</head>
<body>";
$Message = nl2br($this->content_to_send);
$mailMessage.= $Message."
<table border='0' cellpadding='0' cellspacing='0'width='100%'>
<tr>
<td style='$css_class' align='left'><br/>Email: "._EMAIL_INFO."</td>
</tr>
<tr>
<td style='$css_height' align='left'><br /><b>Note</b>:- This is an automatically generated email , Please dont reply back to this mail.</td>
</tr>
</table>
</body>
</html>";
$mailSubject= constant('_SHORT_PRODUCT_NAME').' - FeedBack Reply';
$clsEmailTempalte = new clsEmailTemplate($connect, "");
$clsEmailTempalte->sendMail($mailSubject,$mailMessage,$this->email);
}
At the end of your send_reply javascript function just do an alert("Mail Sent");
If you're using ajax (e.g. with jQuery) you'll need to add your alert to the callback.
For jQuery:
var jqxhr = $.ajax( "example.php" )
.done(function() {
alert( "success" );
})
In your javascript function send_reply just add the line
alert("Message sent");
should work.
Just put alert("message has been sent"); at the end of your js function.
If I were doing this (using jQuery). I would call the php file that sends the email using ajax like so:
Your HTML:
<input type='button' id='submit_form' data-id='<? echo $clsSurvey->feedback_id?>' />
Your Javascript:
$('#submit_form').click(function(e){
// To stop the form submitting on button click if you want it to...
e.preventDefault();
// Send the id via post to the mailscript
$.ajax({
url: 'mailscript.php',
type: 'POST'
data: {
id: $(this).attr('data-id')
}
}).done(function(data){
// Use data if you want to return something from the script and add to the message maybe?
alert('Add your message in here');
});
});
Then just add your mailing php inside the mailscript.php (or whatever you want to call it). whenever your script has completed it's job, the done function will fire showing your alert.

Categories

Resources