I have built this Mailchimp Newsletter sign up plugin. PHP its not my strength so I am not being able to fix the error it has.
I used This Mailchimp wrapper: https://github.com/drewm/mailchimp-api.
My PHP file is:
<?php
include('MailChimp.php'); // path to API wrapper downloaded from GitHub
use \DrewM\MailChimp\MailChimp;
function sm_mailchimp_subscribe()
{
// Settings:
$mcAPIKey = '70000000000000000007e-us00';
$mcListID = '323231214212';
$status = 'subscribed';
// Settings End
$MailChimp = new MailChimp($mcAPIKey);
$email = $_POST['email'];
$fname = $_POST['fname'];
$sname = $_POST['sname'];
$merge_vars = array(
'FNAME' => $fname,
'LNAME' => $sname
);
if (isset($email) and isset($fname) and isset($sname)) {
$result = $MailChimp->post("lists/" . $mcListID . "/members", [
'email_address' => $email,
'merge_fields' => $merge_vars,
'status' => $status,
]);
return json_encode($result);
}
}
if ($_POST['ajax']) {
echo sm_mailchimp_subscribe();
} elseif ($_POST['action'] == 'setCookies') {
echo setCookiesTemp();
}
function setCookiesTemp()
{
setcookie('sm_mailchimp-temp', true, time() + (86400 * 28), '/');
}
function setCookiesPerm()
{
setcookie('sm_mailchimp-perm', true, time() + (86400 * 28 * 24), '/');
}
And here is the JS:
jQuery(function($) {
// From wp_localized
const ajaxURL = ajax_obj.ajax_url;
$(document).ready(function() {
var body = $("body");
var modal = `<div class="sm_mailchimp-modal">
<div class="sm_mailchimp-box">
<button class="sm_mailchimp-close">X</button>
<h3>Join Our Mailing List</h3>
<form name="sm_mailchimp-form" method="post" class="sm_mailchimp-form light">
<p>Subscribe to our newsletter and receive tips for a successful business.</p>
<input type="email" name="email" placeholder="Type Your Email" class="sm_sname">
<div class="sm_mailchimp-message"></div>
<button type="submit">SIGN UP</button>
</form>
</div>
</div>`;
if (!document.cookie.includes("sm_mailchimp-temp=1")) {
$(modal)
.hide()
.appendTo(body);
setTimeout(function() {
$(".sm_mailchimp-modal").fadeIn();
}, 5000);
}
$(".sm_mailchimp-close").click(function() {
closeModal();
});
$(".sm_mailchimp-modal").click(function(e) {
if (e.target == this) {
closeModal();
}
});
function closeModal() {
$(".sm_mailchimp-modal").fadeOut();
$.ajax({
url: ajaxURL,
method: "POST",
data: { action: "setCookies" },
success: function(data) {
console.log("Cookie added as sm_mailchimp-temp=1");
}
});
}
$(".sm_mailchimp-form").submit(function() {
var emailVal, fnameVal, snameVal;
emailVal = $(".sm_email", this).val();
fnameVal = $(".sm_fname", this).val();
snameVal = $(".sm_sname", this).val();
if (emailVal === "" || fnameVal === "" || snameVal === "") {
$(".sm_mailchimp-message").html("Please fill out all the fields!");
return false;
} else {
$(".sm_mailchimp-message").html("Adding your email address...");
var form = $(this);
$.ajax({
url: ajaxURL,
type: "POST",
data: form.serialize() + "&ajax=true",
success: function(msg) {
var message = $.parseJSON(msg),
result = "";
if (message.status === "pending") {
result =
"Success! Please click the confirmation link that will be emailed to you shortly.";
} else if (message.status === "subscribed") {
result =
"Success! You have been subscribed to our mailing list.";
} else {
result = "Oops: " + message.title;
console.log("Error: ", message);
}
$(".sm_mailchimp-message").html(result);
}
});
return false;
}
});
});
});
The error is the following:
Once the Sign Up button is clicked the message "Adding your email address..." shows as it should but then it freezes there. The console shows the following error:
Weirdly, it used to work fine. And without a change it stopped. I built it a couple of months ago.
UPDATE
The error is actually coming from the success: function(msg) { line. The msg is empty. So, when it gets to message.status it cannot read the property of status null.
Question: Why is the success callback returning msg empty?
Related
I am trying to use Ajax that will keep
the inputs that the user has entered but for some reason, it isn't working.
In case of an error, my controller redirects the view with the data of errors,
however, after the page is uploading the form is empty.
I am using the MVC model of Codeigniter.
$("#save").click(function () {
var tnum1 = $("#tnum1").val();
var tnum2 = $("#tnum2").val();
var tnum3 = $("#tnum3").val();
var loc = $("#loc").val();
var dine = $("#dine").val();
var date = $("#date").val();
var time = $("#time").val();
var phone = $("#phone").val();
var fullname = $("#fullname").val();
$.ajax({
type: 'POST',
url: "<?php echo site_url(); ?>" + "/hosting/create",
data: {tnum1:tnum1, tnum2:tnum2, tnum3:tnum3, loc:loc, dine:dine,
date:date, time:time, phone:phone, fullname: fullname},
error: function () {
alert( "Load was performed.");
},
success: function (data) {
if (data === "") {
window.location.href = "<?php echo site_url('hosting/tableMap'); ?>";
}
else {
$("#error").html(data);
}
}
});
});
Controller
public function create() {
$newDate = date("Y-m-d",strtotime($this->input->post('re_date')));
$newTime = date("H:i", strtotime($this->input->post('re_time')));
$data = array(
'num' => $this->input->post('num'),
'location' => $this->input->post('location'),
'diners' => $this->input->post('diners'),
're_date' => $newDate,
're_time' => $newTime,
'phonenumber' => $this->input->post('phonenumber'),
);
$dataclient = array(
'fullname' => $this->input->post('fullname'),
'phonenumber' => $this->input->post('phonenumber'),
);
$error = $this->validation($data,$dataclient);
if ($error) {
$data['error'] = $this->session->set_flashdata('error','<b><u>Failed! </u></b>'.$error.'');
redirect(base_url("/hosting/tableMap"));
} else {
$this->Hosting_model->form_insert($data, $dataclient);
}
}
If you redirect the controller then it will not retain the previous values. Instead save the error in a variable and return it to ajax function.
That is the whole point of ajax - to not redirect or reload a page ie do the task asynchronously.
remove this line-
redirect(base_url("/hosting/tableMap")); // redirecting on error
then in your controller
if ($error) {
// data['error'] = $this->session->set_flashdata('error','<b><u>Failed! </u></b>'.$error.''); // remove this as page will not reload, flashdata wouldn't work
// redirect(base_url("/hosting/tableMap"));
$ajax_data['error'] = 1; // if error exists then value
$ajax_data['validation_error'] = $error;
} else {
$this->Hosting_model->form_insert($data, $dataclient);
$ajax_data['error'] = 0; // if error doesn't exist then value
}
return json_encode($ajax_data); // or echo json_encode($ajax_data);
Now, to prevent default action of form submission that is to redirect page use
$("#save").click(function (e) {
e.preventDefault();
// rest of your code
then in your ajax success:
if (data.error == 0) { // no error
window.location.href = "<?php echo site_url('hosting/tableMap'); ?>";
}
else { // error
$("#error").html(data); // do whatever you want to do with error
// errors can be retrieved from "data.validation_error" -- it will be an array probably sp you'll have to loop through each element
}
I am trying to insert more than one data in db using js ajax but it is not working and when i am trying to inserting only one data it is successfully working
Here is my indexa.php
<html>
<head>
<script type="text/javascript">
function insert() {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else{
xmlhttp = new ActionXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('success_failed_msg').innerHTML = xmlhttp.responseText;
} else {
console.log("faliled");
}
}
parameters = 'first_name='+document.getElementById('firstName').value;
console.log(parameters);
xmlhttp.open('POST','insert.inc.php',true);
xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlhttp.send(parameters);
}
</script>
</head>
<body>
First Name : <input type="text" id="firstName"><br/><br/>
Last Name : <input type="text" id="lastName"><br/><br/>
Username : <input type="text" id="userName"><br/><br/>
Password : <input type="password" id="password"><br/><br/>
Re-type Password : <input type="password" id="retypePassword"><br/><br/>
<input type="button" value="Submit" onclick="insert()">
<div id="success_failed_msg"></div>
</body>
</html>
My include.inc.php
if (isset($_POST['first_name'])) {
$firstname = $_POST['first_name'];
if (!empty($firstname)) {
$insert_select = "INSERT INTO ajax_member_data(`first_name`) VALUES('".mysqli_real_escape_string($db_connect,$firstname)."')";
if ($insert_query_run = mysqli_query($db_connect,$insert_select)) {
echo 'Data inserted successfully';
} else {
echo 'Failed';
}
} else {
echo 'Please enter the value';
}
}
and when I am trying this script it
<script type="text/javascript">
function insert() {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else{
xmlhttp = new ActionXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('success_failed_msg').innerHTML = xmlhttp.responseText;
} else {
console.log("faliled");
}
}
parameters = 'first_name='+document.getElementById('firstName').value'&last_name='+document.getElementById('lastName').value'&username='+document.getElementById('userName').value'&password='+document.getElementById('password').value'&retype_password='+document.getElementById('retypePassword').value;
console.log(parameters);
xmlhttp.open('POST','insert.inc.php',true);
xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlhttp.send(parameters);
}
</script>
my include.inc.php
if (isset($_POST['first_name']) && isset($_POST['last_name']) && isset($_POST['username']) && isset($_POST['password']) && isset($_POST['retype_password'])) {
$firstname = $_POST['first_name'];
$lastname = $_POST['last_name'];
$usrname = $_POST['username'];
$password = $_POST['password'];
$retype_password = $_POST['retype_password'];
if (!empty($firstname) && !empty($lastname) && !empty($usrname) && !empty($password) && !empty($retype_password)) {
$insert_select = "INSERT INTO ajax_member_data(`first_name`,`last_name`,`user_name`,`password`) VALUES('".mysqli_real_escape_string($db_connect,$firstname)."', '".mysqli_real_escape_string($db_connect,$lastname)."', '".mysqli_real_escape_string($db_connect,$usrname)."', '".mysqli_real_escape_string($db_connect,$password)."')";
if ($insert_query_run = mysqli_query($db_connect,$insert_select)) {
echo 'Data inserted successfully';
} else {
echo 'Failed';
}
} else {
echo 'Please enter the value';
}
}
You haven't done concatenation properly. See here,
parameters = 'first_name='+document.getElementById('firstName').value'&last_name='+document.getElementById('lastName').value'&username='+document.getElementById('userName').value'&password='+document.getElementById('password').value'&retype_password='+document.getElementById('retypePassword').value;
^ missing + ^ missing + ^ missing + ^ missing +
It should be,
parameters = 'first_name='+document.getElementById('firstName').value+'&last_name='+document.getElementById('lastName').value+'&username='+document.getElementById('userName').value+'&password='+document.getElementById('password').value+'&retype_password='+document.getElementById('retypePassword').value;
Sidenote: Learn about prepared statements because right now your query is susceptible to SQL injection. Also see how you can prevent SQL injection in PHP.
You are missing plus(+) sign while passing parameter. Please change your code as below:
Old Code:
parameters = 'first_name='+document.getElementById('firstName').value'&last_name='+document.getElementById('lastName').value'&username='+document.getElementById('userName').value'&password='+document.getElementById('password').value'&retype_password='+document.getElementById('retypePassword').value;
New Code:(Added plus(+) sign wherever it was required)
parameters = 'first_name='+document.getElementById('firstName').value + '&last_name='+document.getElementById('lastName').value + '&username='+document.getElementById('userName').value + '&password='+document.getElementById('password').value + '&retype_password='+document.getElementById('retypePassword').value;
If you wrap the input fields with a form and use jQuery serialize could be easier.
Example HTML:
<form>
First Name : <input type="text" id="firstName"><br/><br/>
Last Name : <input type="text" id="lastName"><br/><br/>
Username : <input type="text" id="userName"><br/><br/>
Password : <input type="password" id="password"><br/><br/>
Re-type Password : <input type="password" id="retypePassword"><br/><br/>
<input type="button" value="Submit">
<div id="success_failed_msg"></div>
</form>
Example JS:
//you can use the var sending to avoid
// more than one request at the same time
var sending = false;
$('form').on('submit', function(ev){
ev.preventDefault();
if (!sending) {
$.ajax({
url: 'insert.inc.php',
method: 'post',
dataType: 'json',
data: $('form').serialize(),
cache: false,
beforeSend: function() {
//here you can show an ajax loading icon
sending = true;
},
success: function(response){
//here you can show a success message and check if the
//response is correct
//response object depends on the server side response
if (response.success || response.success === 'true') {
//show success message...
} else {
//show error message...
}
},
error: function(err){
//here you can show an error message
},
complete: function(){
//here you can hide the ajax loading icon
sending = false;
}
});
}
});
Documentation from jQuery:
Ajax http://api.jquery.com/jquery.ajax/
Serialize https://api.jquery.com/serialize/
And you can format a json response from the server side
json_encode (with this you "transform" a php array to a js object) http://php.net/manual/en/function.json-encode.php
header('Content-Type: application/json'); with this the app will know what type of response is given
You can read more about json and ajax here:
http://www.json.org/
https://developer.mozilla.org/en-US/docs/AJAX
And a tutorial about how to see the request on Firefox: https://developer.mozilla.org/en-US/docs/Tools/Network_Monitor
And on Chrome: https://developers.google.com/web/tools/chrome-devtools/network-performance/resource-loading
var sending = false;
$('form').on('submit', function(ev){
ev.preventDefault();
if (!sending) {
$.ajax({
url: 'insert.inc.php',
method: 'post',
dataType: 'json',
data: $('form').serialize(),
cache: false,
beforeSend: function() {
console.log("processing");
sending = true;
},
success: function(response){
if (response.success || response.success === 'true') {
('#success_failed_msg').text(response);
} else {
('#success_failed_msg').text('response failed');
}
},
error: function(err){
('#success_failed_msg').text(err);
},
complete: function(){
console.log('process complete');
sending = false;
}
});
}
});
I have created a simple form consisting of a textarea field, so when user clicks on submit button its linked to a jquery script containing a url executing the process and store the data, but problem is every time i hit submit, ID & created_at data is stored but the data given on textarea is ignored and not stored, never faced this problem before..please help me out!
HTML
<form id="form" name="form" method="POST" action="profile_1.php" class="wizard-big" autocomplete="off" enctype="multipart/form-data" required="">
<div class="form-group col-sm-12">
<textarea type="text" name="status" id="status" placeholder="What's on your mind.." class="form-control" style="height:100px;"></textarea>
</div>
<div class="col-sm-12 form-group">
<input style="width:100%" type="submit" name="submit" id="submit" value="Post" class="btn btn-success">
</div>
</form>
Jquery
$(document).ready(function() {
$("#submit").click(function(e) {
var status = $('form')[0].checkValidity();
if (status) {
var formData = new FormData($('form')[0]);
$.ajax({
url: "form_post.php",
type: "POST",
data: formData,
processData: false,
contentType: false,
async: false,
dataType: "JSON",
success: function(json) {
if (json.error) {
alert(json.error_msg);
e.preventDefault();
} else {
alert("Post updated successfully!");
}
},
error: function(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
});
});
php
<?php
session_start();
define('HOST','localhost');
define('USER','**');
define('PASS','**');
define('DB','**');
$response = array();
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
if(!mysqli_connect_errno()){
$error_flag = false;
/*foreach($_POST as $value){
if(empty($value)){
$error_flag = true;
break;
}
}*/
if(!$error_flag){
//receiving post parameters
$status =$_POST['status'];
// create a new user profile
$sql = "INSERT INTO status (via, status, created_at) VALUES ('".$_SESSION['vault_no']."', '$status', NOW())";
if(mysqli_query($con,$sql)){
$response["error"] = false;
$response['via'] = $via;
echo json_encode($response);
}else{
$response["error"] = true;
$response["error_msg"] = "INSERT operation failed";
echo json_encode($response);
}
}else{
$response["error"] = true;
$response["error_msg"] = "Few fields are missing";
echo json_encode($response);
}
}else{
$response["error"] = true;
$response["error_msg"] = "Database connection failed";
echo json_encode($response);
}
?>
Note: The solution is in the comments for other readers of this question
Maybe this helps you out. You need to change it to your wish offcourse
And save this function, it could be usefull for you in the future.
This function serializes the form as how it should be done.
<script>
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$(function() {
$('form').submit(function() {
var formData = $('form').serializeObject();
$.ajax({
data: formData,
type: 'POST',
url: 'form_post.php',
success: function(result) {
$('#result').html(result);
},
error: function(jqXHR, textStatus, errorThrown) { alert(textStatus); }
});
return false;
});
});
</script>
I am trying to submit a form. In the form, I have a field calles sitename. If the user enters a sitename which is already in the database, it will show the message "That name is already in use" and give some suggestions. Up to this point, it works. But what I want, is to hide the submit button until the user enters a valid value to that field.
Here is my code:
form.php:
<script type="text/javascript">
$(document).ready(function(){
$("#sitename").keyup(function() {
var sitename = $('#sitename').val();
if(sitename=="")
{
$("#disp").html("");
}
else
{
$.ajax({
type: "POST",
url: "check_name.php",
data: "sitename="+ sitename ,
success: function(html){
$("#disp").html(html);
}
});
return false;
}
});
});
</script>
<div class="form-group col-sm-3 col-xs-12">
<button class="btn btn-1 btn-fill" type="submit" id="btn-signup" name="btn-signup">Submit</button>
</div>
check_name.php:
include('dbconnect.php');
if(isset($_POST['sitename']))
{
$sitename=mysql_real_escape_string($_POST['sitename']);
$query=mysql_query("select * from template_users where sitename='$sitename'");
$row=mysql_num_rows($query);
if($row==0)
{
/*echo "<span style='color:white;'>Available</span>";*/
}
else
{
$msg = $sitename.rand ( 1 , 10000 );
$msg1 = $sitename.rand ( 1 , 100 );
echo "<span style='color:antiquewhite;' ><b>Already exist please Use different Site Name such as<br/> $msg<br/>$msg1<br/><b/></span>";
}
}
Try this code,
<script type="text/javascript">
$(document).ready(function(){
$("#sitename").keyup(function() {
var sitename = $('#sitename').val();
if(sitename=="")
{
$("#disp").html("");
}
else
{
$.ajax({
type: "POST",
url: "check_name.php",
data: "sitename="+ sitename ,
success: function(html){
if(html != 'success')
{
$("#disp").html(html);
$("#btn-signup").hide();
}
else
{
$("#btn-signup").show();
}
},
});
return false;
}
});
});
</script>
<div class="form-group col-sm-3 col-xs-12">
<button class="btn btn-1 btn-fill" type="submit" id="btn-signup" name="btn-signup" style="display:none;">Submit</button>
</div>
And in your check_name.php
<?php
include('dbconnect.php');
if(isset($_POST['sitename']))
{
$sitename=mysql_real_escape_string($_POST['sitename']);
$query=mysql_query("select * from template_users where sitename='$sitename'");
$row=mysql_num_rows($query);
if($row==0)
{
echo "success";
}
else
{
$msg = $sitename.rand ( 1 , 10000 );
$msg1 = $sitename.rand ( 1 , 100 );
echo "<span style='color:antiquewhite;' ><b>Already exist please Use different Site Name such as<br/> $msg<br/>$msg1<br/><b/></span>";
}
die;
}
?>
You will need to keep track on the outcome of your PHP script.
Change your code to:
PHP
<?php
include('dbconnect.php');
if(isset($_POST['sitename']))
{
$sitename=mysql_real_escape_string($_POST['sitename']);
$query=mysql_query("select * from template_users where sitename='$sitename'");
$row=mysql_num_rows($query);
if($row==0)
{
echo json_encode([ "status" => 1, "html" => "<span style='color:white;'>Available</span>" ]);
}
else
{
$msg = $sitename.rand ( 1 , 10000 );
$msg1 = $sitename.rand ( 1 , 100 );
echo json_encode([ "status" => 0, "html" => "<span style='color:antiquewhite;' ><b>Already exist please Use different Site Name such as<br/> $msg<br/>$msg1<br/><b/></span>" ]);
}
}
?>
HTML
<script type="text/javascript">
$(document).ready(function () {
$("#btn-signup").hide();
$("#sitename").keyup(function () {
$("#btn-signup").hide();
var sitename = $('#sitename').val();
if (sitename == "")
{
$("#disp").html("");
}
else
{
$.ajax({
type: "POST",
url: "check_name.php",
data: "sitename=" + sitename,
dataType: "json",
success: function (result) {
if (result.status == 1) {
$("#btn-signup").show();
}
$("#disp").html(result.html);
}
});
return false;
}
});
});
</script>
<div class="form-group col-sm-3 col-xs-12">
<button class="btn btn-1 btn-fill" type="submit" id="btn-signup" name="btn-signup">Submit</button>
</div>
That is, hide the button on start, if a user enters something, hide the button and wait till the text is validated. If it is valid, show it. If the user changes the text, then the button will be hidden again.
Please note:
1) mysql_* functions are deprecated since version 5.5 and have been removed in version 7. This on its own is enough indication that you need to move on and use something more secure and actively supported.
2) mysql_real_escape_string and mysqli_real_escape_string are not safe since they don't reliably consider server encoding. If you want to be safe, use real prepared statements (i.e. prepared statements which are prepared on the MySQL server).
I would suggest you to use json to return the data like this:
{
"status": "success",
"html" : "<span style='color:antiquewhite;' ><b>Already exist please Use different Site Name such as<br/> $msg<br/>$msg1<br/><b/></span>"
}
and here's the javascript code:
$(document).ready(function()
{
/** Hide the button first */
$('button').hide();
$('#sitename').on('input', function()
{
var sitename = $('#sitename').val();
if(sitename == '')
{
$("#disp").html("");
}
else
{
$.ajax(
{
type : "POST",
dataType: "json"
url : "check_name.php",
data : "sitename=" + sitename ,
success : function(data)
{
/** When the data is invalid */
if(data.status === 'error')
{
$('button').hide();
$("#disp").html(data.html);
}
else
{
$('button').show();
/** Hide the html when the data is valid */
$("#disp").html('');
}
},
});
}
})
});
And your php code:
<?php
include('dbconnect.php');
header('Content-Type: application/json; charset=utf-8');
if(isset($_POST['sitename']))
{
$sitename = mysql_real_escape_string($_POST['sitename']);
$query = mysql_query("select * from template_users where sitename='$sitename'");
$row = mysql_num_rows($query);
if($row == 0)
{
echo json_encode(['status' => 'success',
'html' => "<span style='color:white;'>Available</span>"]);
}
else
{
$msg = $sitename.rand ( 1 , 10000 );
$msg1 = $sitename.rand ( 1 , 100 );
echo json_encode(['status' => 'error',
'html' => "<span style='color:antiquewhite;' ><b>Already exist please Use different Site Name such as<br/> $msg<br/>$msg1<br/><b/></span>"]);
}
}
?>
$.ajax({
type: "POST",
url: "check_name.php",
data: "sitename="+ sitename ,
success: function(html){
if(html !== "") {
$("#btn-signu").attr("disabled", true);
}
else {
$("#btn-signu").removeAttr("disabled");
}
$("#disp").html(html);
}
});
Check the html param in success callback function.
In form.php change Javascript to:
<script type="text/javascript">
$(document).ready(function(){
//get the button by its ID
var $button = $('#btn-signup');
$("#sitename").keyup(function() {
//hide the button always
$button.hide();
var sitename = $('#sitename').val();
if(sitename=="")
{
$("#disp").html("");
}
else
{
$.ajax({
type: "POST",
url: "check_name.php",
data: "sitename="+ sitename ,
success: function(html){
$("#disp").html(html);
if(!html.length){
//show the submit button if no error html
$button.show();
}
}
});
return false;
}
});
});
</script>
The Button should be initial hidden. If the field can be prefilled, you need to check if the value is not empty before hiding the button.
<div class="form-group col-sm-3 col-xs-12">
<button class="btn btn-1 btn-fill" type="submit" id="btn-signup" name="btn-signup" style="display:none">Submit</button>
</div>
I am using Ajax to post the results from a php form to a database using an API. However when the script runs, I am not getting anything in return stating that it was a success or an error. I can log into the database and see that it has added the entry but I am not getting an alert when it saves to the database.
What I would like the script to do is:
-First save to the database (Done)
-Second: Alert the user that the operation was completed successfully or error
-Third: reset the values in the form if success, keep values if error
Here is what I have tried and have so far:
$(document).ready(function () {
function showSuccess(message) {
$('#success.success').append('<h3 class="alert alert-success">' + message + '</h3>').fadeIn(1000).fadeOut(5000);
}
function showError(message) {
$('#success.success').append('<h3 class="alert alert-danger">' + message + '</h3>').fadeIn(1000).fadeOut(5000);
}
$('form#directory-create').on('submit', function (e) {
//stops the submit action
e.preventDefault();
//format the data into javascript object
var data = $(this).serializeArray();
//calls function to create record, passing participant information as arguments
createRecord(data);
});
function resetStudyInfo() {
//resets all form values to default
$('form#directory-create').find('input:text, input:radio, input:email, input:phone').val('');
return true;
}
function createRecord(data) {
//converts into json data format
var myData = JSON.stringify(data);
console.log(myData);
$.ajax({
//setup option for .ajax func
type: "POST",
url: "directory-create-record.php",
data: {
//user_data : contains all the fields and their data
user_data: myData
},
//shows output message on error or success
success: function () {
showSuccess('Study created successfully, you may now add participants to this study.');
var reset = resetStudyInfo();
return true;
},
error: function () {
showError('Unable to create the study, did you fill out everything?');
return false;
}
});
}
});
PHP side:
require "RestCallRequest.php";
function insertData($data_from_user){
$status = 2;
$url = "xxxx";
$token = "mytokenishere";
$fname = $data_from_user[0]->value;
$lname = $data_from_user[1]->value;
$title = $data_from_user[2]->value;
$school = $data_from_user[3]->value;
$facultystafftrainee = $data_from_user[4]->value;
$email = $data_from_user[5]->value;
$phone = $data_from_user[6]->value;
$record_id = $lname .'_'. $fname;
# an array containing all the elements that must be submitted to the API
$data = "record_id,f_name,l_name,title,school,facultystafftrainee,email,phone,directory_complete\r\n";
$data .= "$record_id,$fname,$lname,$title,$school,$facultystafftrainee,$email,$phone,$status";
$args = array(
'content' => 'record',
'type' => 'flat',
'format' => 'csv',
'token' => $token,
'data' => $data
);
# create a new API request object
$request = new RestCallRequest($url, 'POST', $args);
# initiate the API request
$request->execute();
$result = $request->getResponseBody();
if($result == '1'){
return 1;
}
}
Any help is greatly appreciated. Thank you
When resetting the form values, you have input:email and input:phone, javascript throws a syntax error as you do not need these values, When you remove them your code should work.... Here is the complete working code
$(document).ready(function () {
function showSuccess(message) {
$('#success.success').append('<h3 class="alert alert-success">' + message + '</h3>').fadeIn(1000).fadeOut(5000);
}
function showError(message) {
$('#success.success').append('<h3 class="alert alert-danger">' + message + '</h3>').fadeIn(1000).fadeOut(5000);
}
function resetStudyInfo() {
$('form#directory-create').find('input:text, input:radio').val('');
return true;
}
$('form#directory-create').on('submit', function (e) {
e.preventDefault();
var data = $(this).serializeArray();
createRecord(data);
});
function createRecord(data) {
var myData = JSON.stringify(data);
$.ajax({
type: "POST",
url: "directory-create-record.php",
data: {
user_data: myData
},
success: function () {
showSuccess('Study created successfully, you may now add more participants to this study.');
var reset = resetStudyInfo();
return true;
},
error: function () {
showError('Unable to create the study, did you fill out everything?');
return false;
}
});
}
});