Remove form submit button and replace with loading gif - javascript

I have a form with a submit button and would like to remove the button and replace it with a loading gif image. I don't want this to happen just on click, since the form is verified I want the button to disappear only when all input fields are correctly filled so that the gif image shows progress. How can I do this?
Note: This is not a event to fire on success either, I want it to be a progress indicator. On success the form fade and display a message: "Thanks for contacting us! We will get back to you very soon..." and the jQuery below already handles this.
Here is the php code:
<?php
// Email address verification
function isEmail($email) {
return preg_match('|^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]{2,})+$|i', $email);
};
if($_POST) {
// Enter the email where you want to receive the message
$emailTo = 'example#gmail.com';
$clientName = addslashes(trim($_POST['name']));
$clientEmail = addslashes(trim($_POST['email']));
$number = addslashes(trim($_POST['number']));
$message = addslashes(trim($_POST['message']));
$subject = 'Query from My Domain';
$sendMessage = 'Hi' . "\n\n";
$sendMessage .= $message . "\n\n";
$sendMessage .= 'From: ' . $clientName . "\n";
$sendMessage .= 'Email: ' . $clientEmail . "\n";
$sendMessage .= 'Contact number: ' . $number . "\n";
$array = array();
$array['nameMessage'] = '';
$array['emailMessage'] = '';
$array['numberMessage'] = '';
$array['messageMessage'] = '';
if($clientName == '') {
$array['nameMessage'] = 'Please enter your full name.';
}
if(!isEmail($clientEmail)) {
$array['emailMessage'] = 'Please insert a valid email address.';
}
if($number == '') {
$array['numberMessage'] = 'Please enter a valid contact number.';
}
if($message == '') {
$array['messageMessage'] = 'Please enter your message.';
}
if($clientName != '' && isEmail($clientEmail) && $message != '') {
// Send email
$headers = "From: " . $clientName . ' <' . $clientEmail . '>' . "\r\n";
$headers .= PHP_EOL;
$headers .= "MIME-Version: 1.0".PHP_EOL;
$headers .= "Content-Type: multipart/mixed;".PHP_EOL;
$headers .= " boundary=\"boundary_sdfsfsdfs345345sfsgs\"";
mail($emailTo, $subject, $sendMessage, $headers);
}
echo json_encode($array);
} else {
header ('location: index.html#contact');
}
?>
and here is the jQuery:
// Contact form
$('.contact-form form').submit(function(e) {
e.preventDefault();
var form = $(this);
var nameLabel = form.find('label[for="contact-name"]');
var emailLabel = form.find('label[for="contact-email"]');
var numberLabel = form.find('label[for="contact-number"]');
var messageLabel = form.find('label[for="contact-message"]');
nameLabel.html('Full name');
emailLabel.html('Email');
numberLabel.html('Contact number');
messageLabel.html('Message');
var postdata = form.serialize();
$.ajax({
type: 'POST',
url: 'sendmail.php',
data: postdata,
dataType: 'json',
success: function(json) {
if(json.nameMessage !== '') {
nameLabel.append(' - <span class="red error-label"> ' + json.nameMessage + '</span>');
}
if(json.emailMessage !== '') {
emailLabel.append(' - <span class="red error-label"> ' + json.emailMessage + '</span>');
}
if(json.numberMessage !== '') {
numberLabel.append(' - <span class="red error-label"> ' + json.numberMessage + '</span>');
}
if(json.messageMessage !== '') {
messageLabel.append(' - <span class="red error-label"> ' + json.messageMessage + '</span>');
}
if(json.nameMessage === '' && json.emailMessage === '' && json.numberMessage === '' && json.messageMessage === '') {
form.fadeOut('fast', function() {
form.parent('.contact-form').append('<h2 class="text-center"><span class="orange">Thanks for contacting us!</span> We will get back to you very soon.</h2>');
});
}
}
});
});

do an ajax .done() after your ajax call to replace the button back

Related

Woocommerce Variations Radio buttons

I had the hooks below that's working perfectly to change the Products variations select to radio buttons while creating variations using custom attributes.
I added new products variations using the Global Attributes but it seems that the hook is not compatible with it.
am looking for a way to make it compatible with both since I already have 200 products using the custom attributes and want to start using global attributes for the new products.
function variation_radio_buttons($html, $args)
{
$args = wp_parse_args(apply_filters('woocommerce_dropdown_variation_attribute_options_args', $args) , array(
'options' => false,
'attribute' => false,
'product' => false,
'selected' => false,
'name' => '',
'id' => '',
'class' => '',
'show_option_none' => __('Choose an option', 'woocommerce') ,
));
if (false === $args['selected'] && $args['attribute'] && $args['product'] instanceof WC_Product)
{
$selected_key = 'attribute_' . sanitize_title($args['attribute']);
$args['selected'] = isset($_REQUEST[$selected_key]) ? wc_clean(wp_unslash($_REQUEST[$selected_key])) : $args['product']->get_variation_default_attribute($args['attribute']);
}
$options = $args['options'];
$product = $args['product'];
$attribute = $args['attribute'];
$name = $args['name'] ? $args['name'] : 'attribute_' . sanitize_title($attribute);
$id = $args['id'] ? $args['id'] : sanitize_title($attribute);
$class = $args['class'];
$show_option_none = (bool)$args['show_option_none'];
$show_option_none_text = $args['show_option_none'] ? $args['show_option_none'] : __('Choose an option', 'woocommerce');
$label = wc_attribute_label($args['attribute'], $args['product']);
if (empty($options) && !empty($product) && !empty($attribute))
{
$attributes = $product->get_variation_attributes();
$options = $attributes[$attribute];
}
$html = '<select id="' . esc_attr($id) . '" class="d-none ' . esc_attr($class) . '" name="' . esc_attr($name) . '" data-attribute_name="attribute_' . esc_attr(sanitize_title($attribute)) . '" data-show_option_none="' . ($show_option_none ? 'yes' : 'no') . '">';
$html .= '<option value="">' . esc_html($show_option_none_text) . '</option>';
if (!empty($options))
{
if ($product && taxonomy_exists($attribute))
{
// Get terms if this is a taxonomy - ordered. We need the names too.
$terms = wc_get_product_terms($product->get_id() , $attribute, array(
'fields' => 'all'
));
foreach ($terms as $term)
{
if (in_array($term->slug, $options))
{
$html .= '<option value="' . esc_attr($term->slug) . '" ' . selected(sanitize_title($args['selected']) , $term->slug, false) . '>' . esc_html(apply_filters('woocommerce_variation_option_name', $term->name)) . '</option>';
}
}
}
else
{
foreach ($options as $option)
{
// This handles < 2.4.0 bw compatibility where text attributes were not sanitized.
//$selected = sanitize_title( $args['selected'] ) === $args['selected'] ? selected( $args['selected'], sanitize_title( $option ), false ) : selected( $args['selected'], $option, false );
//if (sanitize_title($option) == $current){
//$selected = 'selected';
//}
$selected = '';
$html .= '<option value="' . esc_attr($option) . '" ' . $selected . '>' . esc_html(apply_filters('woocommerce_variation_option_name', $option)) . '</option>';
}
}
}
$html .= '</select>';
$radios = '<div class="radio-group">';
if (!empty($options))
{
if ($product && taxonomy_exists($attribute))
{
$terms = wc_get_product_terms($product->get_id() , $attribute, array(
'fields' => 'all',
));
foreach ($terms as $term)
{
if (in_array($term->slug, $options, true))
{
$radios .= '<input id="' . strtolower($option) . '" type="radio" name="' . esc_attr($name) . '" value="' . esc_attr($term->slug) . '" onClick="jQuery("#' . esc_attr($name) . '").val(' . esc_attr($term->slug) . ').trigger("change");" ' . checked(sanitize_title($args['selected']) , $term->slug, false) . '><label for="' . esc_attr($term->slug) . '">' . esc_html(apply_filters('woocommerce_variation_option_name', $term->name)) . '</label>';
}
}
}
else
{
foreach ($options as $option)
{
// $checked = sanitize_title($args['selected']) === $args['selected'] ? checked($args['selected'], sanitize_title($option), false) : checked($args['selected'], $option, false);
//if (sanitize_title($option) == $current){
//$checked = 'checked="checked"';
//}
$checked = '';
$radios .= '<input id="' . strtolower(sanitize_title($option)) . '" type="radio" name="' . esc_attr($name) . '" value="' . esc_attr($option) . '" id="' . sanitize_title($option) . '" onClick="changeTrigger(\'#' . strtolower($attribute) . '\',\'' . esc_attr($option) . '\',\'' . esc_attr($label) . '\');" ' . $checked . '><label for="' . sanitize_title($option) . '">' . esc_html(apply_filters('woocommerce_variation_option_name', $option)) . '</label>';
$allAttribute[] = strtolower($attribute);
}
}
}
$radios .= '</div>';
return $html . $radios;
}
add_filter('woocommerce_dropdown_variation_attribute_options_html', 'variation_radio_buttons', 20, 2);
function variation_check($active, $variation)
{
if (!$variation->is_in_stock() && !$variation->backorders_allowed())
{
return false;
}
return $active;
}
add_filter('woocommerce_variation_is_active', 'variation_check', 10, 2);
if (!function_exists('shop_attributes_in_loop'))
{
function shop_attributes_in_loop()
{
global $product;
//Getting product attributes
$product_attributes = $product->get_attributes();
if (!empty($product_attributes))
{
//Getting product attributes slugs
$product_attribute_slugs = array_keys($product_attributes);
?>
<script>
function resetAttr(c,d){
var attr = c;
jQuery('input[name=attribute_'+c+']').attr('disabled',false);
jQuery('input[name=attribute_'+c+']').attr('checked',false);
jQuery('#' + c + '-selected').html('');
jQuery('#' + c + '-section').removeClass('d-none');
jQuery('#' + c + ' option[value=""]').prop('selected', true);
if(d){
jQuery('#' + c).trigger('change');
}
<?php
foreach ($product_attribute_slugs as $product_attribute_slug)
{
$attribute_name = str_replace('pa_', '', $product_attribute_slug); // Removing "pa_" from attribute slug
//echo 'jQuery(\'#'.$attribute_name.'\').trigger(\'change\');';
?>
var allvalues = [];
jQuery('select#<?php echo $attribute_name; ?>').find('option').each(function() {
if(jQuery('select#<?php echo $attribute_name; ?>').val() == ""){
if(jQuery(this).attr('disabled', false)){
var theValue = jQuery(this).val();
allvalues.push(theValue);
}
}
});
jQuery('input[name="attribute_<?php echo $attribute_name; ?>"]').each(function () {
var theRadio = jQuery(this).val();
var check = allvalues.includes(theRadio);
if(check == false){
jQuery(this).attr('disabled', true);
}else{
jQuery(this).attr('disabled', false);
}
});
<?php
}
?>
}
function changeTrigger(a,b,c){
a = a.replace(/\s+/g, "-");
jQuery(a + ' option[value="' + b + '"]').prop('selected', true);
jQuery(a + '-selected').html('<div class="selected-variable"><span>'+c.replace(/#/, "").toUpperCase()+': '+b+' </span><a class="var-del" onClick="resetAttr(\''+a.replace(/#/, "")+'\',true)"><div class="close-x"></div></a></div>');
jQuery(a + '-section').addClass('d-none');
jQuery('input[name=attribute_'+a.replace(/#/, "")+']').attr('disabled',true);
jQuery(a).trigger('change');
<?php
foreach ($product_attribute_slugs as $product_attribute_slug)
{
$attribute_name = str_replace('pa_', '', $product_attribute_slug); // Removing "pa_" from attribute slug
//echo 'jQuery(\'#'.$attribute_name.'\').trigger(\'change\');';
?>
var allvalues = [];
jQuery('select#<?php echo $attribute_name; ?>').find('option').each(function() {
if(jQuery('select#<?php echo $attribute_name; ?>').val() == ""){
resetAttr('<?php echo $attribute_name; ?>',false);
/*jQuery('input[name=attribute_<?php echo $attribute_name; ?>]').attr('checked',false);*/
if(jQuery(this).attr('disabled', false)){
var theValue = jQuery(this).val();
allvalues.push(theValue);
}
}
});
jQuery('input[name="attribute_<?php echo $attribute_name; ?>"]').each(function () {
var theRadio = jQuery(this).val();
var check = allvalues.includes(theRadio);
if(check == false){
jQuery(this).attr('disabled', true);
}else{
//jQuery(this).attr('disabled', false);
}
});
<?php
}
echo "}</script>";
}
}
}
add_action('woocommerce_before_add_to_cart_button', 'shop_attributes_in_loop');

How do I insert $data and $param into body of email

I am not a programmer and using phprunner to create page to send an email to selected records.
I have used some pre-existing code via this link
https://phprunner.com/phprunner/docs/email_selected_users.htm
and a modification to it on stackoverflow (Thanks [Micheal.M][1]). I need to input the 'from' 'subject' and 'body' via a form. The 'subject' and 'from' parts works fine.
But how can I get the $params["emailBody"] and the $data["FirstName"] both to appear in the 'body' of the email?
'FirstName' field is from a table called Students_ALL.
Can someone please guide me? I have tried for two days and cannot figure it out. Please find the code below: THANK YOU SO MUCH in advance - Mayo
SERVER
if( $params["emailBody"] ||$params["emailSubject"] || $params["emailFrom"] )
{
$emails = array();
while( $data = $button->getNextSelectedRecord() )
{
// Send only if email field not empty
if( $data["Email1"] ) {
// This no longer should be an array of emails
$from = $params["emailFrom"];
$email = $data["Email1"];
$subject = $params["emailSubject"];
$body = $params ["emailBody"];
// Email will be sent for each record
$arr = runner_mail(array('to' => $email, 'subject' => $subject, 'from' => $from, 'htmlbody' => $body));
}
}
$result["txt"] = "Emails were sent.";
if (!$arr["mailed"])
{
$errmsg = "Error happened:
";
$errmsg.= "File: " . $arr["errors"][0]["file"] . "
";
$errmsg.= "Line: " . $arr["errors"][0]["line"] . "
";
$errmsg.= "Description: " . $arr["errors"][0]["description"] . "
";
$result["txt"] = $errmsg;
}
}
CLIENT BEFORE
if ( proxy["emailUsers"] === true ) {
params["emailFrom"] = proxy["emailFrom"];
params["emailBody"] = proxy["emailBody"];
params["emailSubject"] = proxy["emailSubject"];
proxy["emailUsers"] = false;
return true;
}
var selBoxes = pageObj.getSelBoxes( pageid ),
args = {
modal: true,
header: "Input from, subject and body",
html: '<div>'
+ '<div>From: <input type="text" id="emailFrom"s style="margin: 5px 0"></div>'
+ '<div>Subject: <input type="text" id="emailSubject"s style="margin: 5px 0"></div>'
+ '<div>Body: <textarea id="emailBody"></textarea></div>'
+ '</div>',
footer: '' + Runner.lang.constants.TEXT_SAVE + ''
+ '' + Runner.lang.constants.TEXT_CANCEL + '',
afterCreate: function( win ) {
$("#emailUsersSave").on("click", function( e ) {
var context = win.body();
proxy["emailUsers"] = true;
proxy["emailFrom"] = $("#emailFrom", context).val();
proxy["emailBody"] = $("#emailBody", context).val();
proxy["emailSubject"] = $("#emailSubject", context).val();
$('[id="' + ctrl.id + '"]').click();
e.preventDefault();
win.destroy();
});
$("#emailUsersCancel").on("click", function( e ) {
e.preventDefault();
win.destroy();
});
}
};
if ( selBoxes.length == 0 || !confirm('Do you really want to email these records?') ) {
return false;
}
Runner.displayPopup( args );
return false;
CLIENT AFTER
var message = result["txt"] + " !!!";
ctrl.setMessage(message);
[1]: https://stackoverflow.com/users/2432106/michal-m

localstorage data not persisting between pages

I am attempting to build a website to assist with recording times of events during ems calls. I have replicated our protocols and am using localstorage to record when and what event happens. When the incident is over, all the events that have been clicked are displayed on a report page where the information can be sent via email.
Everything seems to work, however, if another page is opened, the localstorage seem to clear and only the buttons clicked on the most recent page appear. I need every button clicked recorded for the report.
This is my JS:
//GO BACK BUTTON
function goBack() {
window.history.back();
}
// DATE FORMATER
function convertDate() {
var d = new Date();
var a = [(d.getMonth() + 1),
(d.getDate()),
(d.getFullYear()),
].join('-');
var b = [(d.getHours()),
(d.getMinutes()),
(d.getSeconds()),
].join(':');
return (b + ' ' + a);
}
///////////////////button////////////////////////
$(document).ready(function () {
var report = {};
var myItem = [];
$('button').click(function () {
var itemTime = convertDate() + " ___ " ;
var clickedBtnID = $(this).text() + " # " ;
item = {
ITEM: clickedBtnID,
TIME: itemTime ,
};
myItem.push(item);
localStorage.report = JSON.stringify(myItem);
});
});
And this is part of the report page:
<script>
window.onload = function () {
var areport = JSON.stringify(localStorage.report);
console.log(areport);
areport = areport.replace(/\\"/g, "");
areport = areport.replace(/{/g, "");
areport = areport.replace(/}/g, "");
areport = areport.replace(/[\[\]']+/g, "");
areport = areport.replace(/,/g, "");
areport = areport.replace(/"/g, "");
console.log(areport);
document.getElementById('result').innerHTML = areport;
};
</script>
<body>
<div class="container-fluid">
<h1>Report</h1>
<?php
if (isset($_POST["send"])) {
$incident = $_POST['incident'];
$name = $_POST['name'];
$address = $_POST['address'];
$dob = $_POST['dob'];
$gender = $_POST['gender'];
$reportData = $_POST['reportData'];
if ($incident == '') {
echo $incident = 'No incident number entered.';
echo '<br>';
} else {
echo $incident . '<br>';
}
if ($name == '') {
echo $name = 'No name entered.';
echo '<br>';
} else {
echo $name . '<br>';
}
if ($address == '') {
echo $address = 'No address entered.';
echo '<br>';
} else {
echo $address . '<br>';
}
if ($dob == '') {
echo $dob = 'No birthdate entered.';
echo '<br>';
} else {
echo $dob . '<br>';
}
if ($gender == '') {
echo $gender = 'No gender entered.';
echo '<br>';
} else {
echo $gender . '<br>';
}
if ($reportData == null) {
echo $reportData = 'No report entered.';
echo '<br>';
} else {
echo $reportData . '<br>';
}
//mail
$headers = "From: CCEMP.info <ccemlbaw#server237.web-hosting.com> \r\n";
$reEmail = $_POST['reEmail'];
$reEmail1 = $_POST['reEmail1'];
//$areport = json_decode($_POST['localStorage.report']);
$msg = "Incident: " . $incident . "\n" . "Name: " . $name . "\n" . "Address:
". $address . "\n" . "DOB: " . $dob . "\n" . "Gender: " . $gender . "\n" .
$reportData;
mail($reEmail, 'Incident:' . $incident, $msg, $headers);
mail($reEmail1, 'Incident:' . $incident, $msg, $headers);
}//end of submit
?>
Here is a sample button:
<div class="dropdown">
<button class="btn btn-secondary dropdown-toggle" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">General Truama</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
<a class="dropdown-item" >Continue Assessment</a>
<a class="dropdown-item" href="GATA.php">Go to Truama</a>
</div>
</div>
Thanks.
You are not using localStorage, just setting .report on global localStorage variable. You would see this issue if you used strict mode ("use strict"; at top of the js file).
instead use:
localStorage.setItem("report", JSON.stringify(myItem));
and to get the item
localStorage.getItem("report");
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
This does not set the item to localStorage. In fact, localStorage.report is undefined.
localStorage.report = JSON.stringify(myItem);
This does.
localStorage.setItem('report', JSON.stringify(myItem));
I wasn't adding the localStorage from the previous page to the new one.
var myItem = [];
$(document).ready(function () {
$('button').click(function () {
var itemTime = convertDate() + " ___ " ;
var clickedBtnID = $(this).text() + " # " ;
var item = {
ITEM: clickedBtnID,
TIME: itemTime ,
};
myItem.push(item);
localStorage.setItem('report', JSON.stringify(myItem));
console.log(myItem);
});
var areport = localStorage.getItem("report");
myItem.push(areport);
});

PHP/JS Contact Form - Validation

I cannot get this form to work. Everything I do it just comes up with an error and also says that the phone number isn't valid but when I look at the code I can't really see why it isn't working.
P.S. I don't really have any understanding of PHP or JS so I don't really know what I'm looking for when it comes to errors.
Thank you for any help.
Here's the HTML
<form action="contact.php" method="post" id="cform" name="cform">
<ul id="homehireus" class="hireform contactform">
<li>
<label>Name:<span class="required">*</span></label>
<input name="name" id="name" type="text" value="" tabindex="1">
</li>
<li>
<label>Phone:</label>
<input name="phone" id="phone" type="text" value="" tabindex="2">
</li>
<li>
<label>Email:<span class="required">*</span></label>
<input name="email" id="email" type="text" value="" tabindex="3">
</li>
<li>
<label>Subject:</label>
<input name="subject" id="subject" type="text" value="" tabindex="4">
</li>
<li>
<label>Message:<span class="required">*</span></label>
<textarea name="message" id="message" tabindex="5"></textarea>
</li>
<li>
<input type="button" id="send-message" value="Send Details To iPhone Repairs" tabindex="6">
<div id="output" class="contactpage-msg"></div>
</li>
</ul>
</form>
PHP
<?php
$send_email_to = "naomi.deluca#me.com";
function send_email($name,$email,$phone,$subject,$message)
{
global $send_email_to;
if($message=='message')$message='';
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= "From: ".$email. "\r\n";
$message = "<strong>Email = </strong>".$email."<br>";
$message .= "<strong>Name = </strong>".$name."<br>";
$message .= "<strong>Phone = </strong>".$phone."<br>";
$message .= "<strong>Message = </strong>".$message."<br>";
#mail($send_email_to, $subject, $message,$headers);
return true;
}
function validate($name,$email,$phone,$message,$subject)
{
$return_array = array();
$return_array['success'] = '1';
$return_array['name_msg'] = '';
$return_array['email_msg'] = '';
$return_array['phone_msg'] = '';
$return_array['message_msg'] = '';
$return_array['subject_msg'] = '';
if($email == '')
{
$return_array['success'] = '0';
$return_array['email_msg'] = 'email is required';
}
else
{
$email_exp = '/^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(!preg_match($email_exp,$email)) {
$return_array['success'] = '0';
$return_array['email_msg'] = 'Enter valid email.';
}
}
if($name == '')
{
$return_array['success'] = '0';
$return_array['name_msg'] = 'Name is required';
}
else
{
$string_exp = "/^[A-Za-z .'-]+$/";
if (!preg_match($string_exp, $name)) {
$return_array['success'] = '0';
$return_array['name_msg'] = 'Enter valid Name.';
}
}
if($phone == '')
{
$return_array['success'] = '0';
$return_array['phone_msg'] = 'Phone is required';
}
else
{
$string_exp = "/^[A-Za-z .'-]+$/";
if (!preg_match($string_exp, $phone)) {
$return_array['success'] = '0';
$return_array['phone_msg'] = 'Enter valid Phone.';
}
}
if($subject == '')
{
$return_array['success'] = '0';
$return_array['subject_msg'] = 'Subject is required';
}
if($message == '')
{
$return_array['success'] = '0';
$return_array['message_msg'] = 'Message is required';
}
else
{
if (strlen($message) < 2) {
$return_array['success'] = '0';
$return_array['message_msg'] = 'Enter valid Message.';
}
}
return $return_array;
}
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$message = $_POST['message'];
$subject = $_POST['subject'];
$return_array = validate($name,$email,$phone,$message,$subject);
if($return_array['success'] == '1')
{
send_email($fname,$email,$phone,$subject,$message);
}
header('Content-type: text/json');
echo json_encode($return_array);
die();
?>
JS
$(document).ready(function () {
$('div#output').hide();
//bind send message here
$('#send-message').click(sendMessage);
$('button.close').live('click', function () {
$(this).parent().find('p').html('');
$(this).parent().hide();
});
});
/* Contact Form */
function checkEmail(email) {
var check = /^[\w\.\+-]{1,}\#([\da-zA-Z-]{1,}\.){1,}[\da-zA-Z-]{2,6}$/;
if (!check.test(email)) {
return false;
}
return true;
}
function sendMessage() {
// receive the provided data
var name = $("input#name").val();
var email = $("input#email").val();
var subject = $("input#subject").val();
var phone = $("input#phone").val();
var message = $("textarea#message").val();
message = 'message';
// check if all the fields are filled
if (name == '' || phone == '' || email == '' || subject == '' || message == '') {
$("div#output").show().html('<button type="button" class="close" data-dismiss="alert-close">x</button><p class="alert-close">You must enter all the fields!</p>');
return false;
}
// verify the email address
if (!checkEmail(email)) {
$("div#output").show().html('<button type="button" class="close" data-dismiss="alert">x</button><p>Please enter a valid Email Address</p>');
return false;
}
// make the AJAX request
var dataString = $('#cform').serialize();
$.ajax({
type: "POST",
url: 'contact.php',
data: dataString,
dataType: 'json',
success: function (data) {
if (data.success == 0) {
var errors = '<ul><li>';
if (data.name_msg != '')
errors += data.name_msg + '</li>';
if (data.email_msg != '')
errors += '<li>' + data.email_msg + '</li>';
if (data.phone_msg != '')
errors += '<li>' + data.phone_msg + '</li>';
if (data.message_msg != '')
errors += '<li>' + data.message_msg + '</li>';
if (data.subject_msg != '')
errors += '<li>' + data.subject_msg + '</li>';
$("div#output").removeClass('alert-success').addClass('alert-error').show().html('<button type="button" class="close" data-dismiss="alert">x</button><p> Could not complete your request. See the errors below!</p>' + errors);
}
else if (data.success == 1) {
$("div#output").removeClass('alert-error').addClass('alert-success').show().html('<button type="button" class="close" data-dismiss="alert">x</button><p>You message has been sent successfully!</p>');
}
},
error: function (error) {
$("div#output").removeClass('alert-success').addClass('alert-error').show().html('<button type="button" class="close" data-dismiss="alert">x</button><p> Could not complete your request. See the error below!</p>' + error.statusText);
}
});
return false;
}
The regular expression that validate the name is the same as the one who validate the phone number, quite weird isn't it?
To validate every kind of phone number, you just have check if $phone contains only digit with ctype_digit().
How about using
/^[0-9]+$/ instead of /^[A-Za-z .'-]+$/ at $string_exp = "/^[A-Za-z .'-]+$/";?
Or
if (preg_match($string_exp, $phone)) { instead of if (!preg_match($string_exp, $phone)) {
Your regex that you use to validate phone numbers:
/^[A-Za-z .'-]+$/
Doesn't accept digits. Given that a phone number typically has digits in it, this regex is most likely invalid in this context.
Your regex for validating phone number isn't correct.
Replace the line:
$string_exp = "/^[A-Za-z .'-]+$/";
With
$string_exp = "/^(\d[\s-]?)?[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?\d{3}[\s-]?\d{4}$/i";
The above regular expression accepts phone numbers in following formats:
555-555-5555
5555425555
555 555 5555
1(519) 555-4444
1 (519) 555-4422
1-555-555-5555
1-(555)-555-25555

Cannot retrieve json string from php using ajax

I can't retrieve json string data from my php script using ajax call.
Here is my ajax script :
$.ajax({
type: "POST",
async: false,
dataType: "json",
url: "database/clientpanel/logs/search_call_log.php",
data: {
from: from,
to: to,
sel: sel
},
cache: false,
success: function(data){
$("#app_panel").append(data.html);
$('.inv_date').hide();
}
});
and this is my php script:
<?php
//wall ===================================================
session_start();
include("../../dbinfo.inc.php");
$from = $_POST['from'];
$to = $_POST['to'];
$sel = $_POST['sel'];
// connect to the database
$client_id = $_SESSION['clientid'];
$out = 0;
$in = 0;
$ext =0;
$min = 0;
$sec = 0;
$results = array(
'html' => $html
);
$html = " ";
if($sel == "all"){
$query=" select * from call where client='$client_id' ORDER BY date_time DESC";
$result = $mysqli->query($query);
}else{
$query=" select * from tele_panel_call where (client='$client_id' AND date_time BETWEEN '$from' AND '$to') ORDER BY date_time DESC";
$result = $mysqli->query($query);
}
if ($result->num_rows > 0){
while ($row = $result->fetch_object())
{
$from = $row->from;
$to = $row->to;
$html .= '<div style="width:590px;height:15px;background: url(img/clientimg/wrap-white.png)repeat;padding: 5px 5px 5px 5px;margin-bottom:5px;">';
$query_from=" select * from tele_agent_dialer where (client='$client_id' AND (dialer='$from' OR dialer='$to'))";
$result_from = $mysqli->query($query_from);
$row_from = $result_from->fetch_assoc();
$dialer = $row_from['dialer'];
if($dialer == $from){
$image = 'outgoing';
$out = $out+1;
}
if($dialer == $to){
$image = 'incoming';
$in = $in+1;
}
if($dialer != $to & $dialer != $from){
$image = 'extension';
$ext = $ext+1;
}
$html .= '<img src="img/clientimg/'; $html .= $image; $html .= '.png" style="float:left;margin-right:10px;height:15px">';
$html .= '<div style="float:left;margin-right:5px;width:135px;height:30px;overflow:hidden;"><b>From: </b>';
if( preg_match( '/^\d(\d{3})(\d{3})(\d{4})$/', $from, $matches ) )
{
$from = '('. $matches[1] . ') ' .$matches[2] . '-' . $matches[3];
}
$html .= $from;
$html .= '</div>
<div style="float:left;margin-right:5px;width:125px;height:30px;overflow:hidden;">
<b>To: </b>';
if( preg_match( '/^\d(\d{3})(\d{3})(\d{4})$/', $to, $matches ) )
{
$to = '('. $matches[1] . ') ' .$matches[2] . '-' . $matches[3];
}
$html .= $to;
$html .= '</div>
<div style="float:left;width:160px;margin-right:5px;height:30px;overflow:hidden;">
<b>Date/Time: </b>'; $html .= $row->date_time;
$html .= '</div>
<div style="float:left;width:100px;margin-right:5px;height:30px;overflow:hidden;">
<b>Duration: </b>';
$duration = $row->duration;
preg_match("#(\d+):(\d+)#", $duration, $matches );
$min = $min + $matches[1];
$sec = $sec + $matches[2];
$html .= $duration;
$html .= '</div>';
$html .= '</div>';
}
}else{
echo "No results to display!";
}
$jsonString = json_encode($results);
echo $jsonString;
$mysqli->close();
?>
Can someone please tell me what I'm doing wrong here? My php script doesn't have any errors when I check the page itself.
Also it's good to add proper header for json data output (at the begining of the script for example).
header("Content-Type: application/json");
As for query results, you should debug it. Try to print the query and run it in Phpmyadmin (or other database administration tool)

Categories

Resources