I'm calling a PHP file from jquery ajax javascript. I could able to see the output of the PHP file in browser. But when called via ajax jquery, i'm not able to print he same output. How can i access it ?
**test.php**
<?php
$dbuser="root";
$dbname="test";
$dbpass="root";
$dbserver="localhost";
// Make a MySQL Connection
$con = mysql_connect($dbserver, $dbuser, $dbpass) or die(mysql_error());
mysql_select_db($dbname) or die(mysql_error());
// Create a Query
$sql_query = "SELECT id, login FROM user";
// Execute query
$result = mysql_query($sql_query) or die(mysql_error());
$jsonArray = array();
while ($row = mysql_fetch_array($result)){
$jsonArrayItem = array();
$jsonArrayItem["id"] = $row["id"];
$jsonArrayItem["login"] = $row["login"];
array_push($jsonArray, $jsonArrayItem);
//echo '<option value='. $row['id'] . '>'. $row['login'] . '</option>';
}
mysql_close($con);
$tableData = array(
"data" => $jsonArray
);
header('Content-Type: application/json');
echo json_encode($tableData,JSON_UNESCAPED_SLASHES);
die();
?>
test.html
<html>
<head>
<title>Example</title>
</head>
<body>
<script src="http://code.jquery.com/jquery-1.11.0.min.js" type="text/javascript">
$.ajax({
url: "test.php",
type: "GET",
dataType: "json",
data: values,
success: function(data){
window.alert(data);
},
error: function(data){
alert("AJAX error!");
}
})
</script>
</body>
</html>
<style>
#container {
text-align: center;
}
a, figure {
display: inline-block;
}
figcaption {
margin: 10px 0 0 0;
font-variant: small-caps;
font-family: Arial;
font-weight: bold;
color: #bb3333;
}
figure {
padding: 5px;
}
img:hover {
transform: scale(1.1);
-ms-transform: scale(1.1);
-webkit-transform: scale(1.1);
-moz-transform: scale(1.1);
-o-transform: scale(1.1);
}
img {
transition: transform 0.2s;
-webkit-transition: -webkit-transform 0.2s;
-moz-transition: -moz-transform 0.2s;
-o-transition: -o-transform 0.2s;
}
</style>
Is something wrong in syntax ? can someone help here ?
Use for example Chrome debug console. Network section, XHR filter, selected URL, response tab. Like this:
1) Press CTRL+I in Chrome
2) Try to follow this:
Related
I'm making a simple Php and javascript project where my css design has some overlay design in it. Now I have a button when clicked it displays an overlay div named "myNav" where a div named "req_form" and form are on it where users can fill out inputs and submit them, then my php code will store those data in my database. I just can't figure out how to replace the div and dislpay success on it after successfully submitting the data in my Php code.
my overlay div
<?php
include 'includes/autoloader.inc.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
function openNav() {
document.getElementById("myNav").style.width="100%";
}
function closeNav(){
document.getElementById("myNav").style.width = "0";
}
</script>
<link rel="stylesheet" type="text/css" href="css/cssticket.css">
</head>
<body>
<button class="button_a" onclick="openNav()">Create Request</button> //OPENS THE OVERLAY DIV
<div id="myNav" class="overlay"> // THIS IS THE OVERLAY DIV
×
<div class="overlay-content">
<div id="req_form" class="inputs"> // THIS IS THE DIV I WANT TO BE REPLACE BY A MESSAGE SUCCESS
<div id="error"></div>
<form id="form" action="includes/enduser.inc.php" method="POST">
<input type="text" name="userrequester" placeholder="name" >
<br>
<label for="reqtype">Request type:</label>
<select name="priority" required>
<option value="">Select</option>
<option value="High">General</option>
<option value="Low">Urgent</option>
</select>
<br>
<label for="itemtype">Item type:</label>
<input type="radio" name="typeitem" value="Borrowed" required><label>Borrowed</label>
<input type="radio" name="typeitem" value="Replace" required></input><label>Replace</label>
<br>
<label>Summary :</label>
<br>
<textarea name="summary" cols="30" rows="10" required ></textarea>
<br>
<button type="submit" name="sendrequest" class="button_a">Submit</button>
</div>
</form>
</div>
</div>
</body>
</html>
here is my php file :
include 'autoloader.inc.php';
$request = new usercontlr;
if (isset($_POST['sendrequest'])) {
$date = date ('F d, Y');
$enduser = $_POST['userrequester'];
$priority = $_POST["priority"];
$itemtype = $_POST["typeitem"];
$summary = $_POST["summary"];
$status = "new";
$request->createticket($enduser, $priority, $itemtype, $status, $summary, $date); // function where my object stores data in my database
What i have tried already is to echo out some javascript that should have change the into a success message after storing the data inside this php file.
echo ' <script type="text/javascript">
document.getElementById('req_form').style.display = "none";
var h1 = document.createElement('h1');
var result = document.createTextNode('Success!');
h1.appendChild(result);
document.getElementById('myNav').appendChild(h1);
</script> ' ;
but when I check the console I got an error (enduser.inc.php:3 Uncaught TypeError: Cannot read property 'style' of null
at enduser.inc.php:3
(anonymous) # enduser.inc.php:3)
Here is also my css if it helps:
.inputs {
padding: 20px;
display: inline-block
}
.overlay {
height: 100%;
width: 0;
position: fixed;
z-index: 1;
top: 0;
left: 0;
background-color: rgb(11, 156, 49);
background-color: rgba(11, 156, 49, 0.9);
overflow-x: hidden;
transition: 0.5s;
}
.overlay-content {
font-family: monospace;
font-size: 15px;
background-color: white;
border-radius: 2%;
position: relative;
top: 25%;
width: 50%;
margin: 0 auto;
text-align: center;
}
.overlay a {
padding: 8px;
text-decoration: none;
font-size: 36px;
color: #818181;
display: block;
transition: 0.3s;
}
.overlay a:hover,
.overlay a:focus {
color: red;
}
.overlay .closebtn {
color: white;
position: absolute;
top: 20px;
right: 45px;
font-size: 60px;
}
#media screen and (max-height: 450px) {
.overlay a {
font-size: 20px
}
.overlay .closebtn {
font-size: 40px;
top: 15px;
right: 35px;
}
}
You will want to create a header() redirect to your original page once you have successfully queried and successfully added your inputs to the DB.
Something like this:
if (isset($_POST['sendrequest'])) {
$date = date ('F d, Y');
$enduser = $_POST['userrequester'];
$priority = $_POST["priority"];
$itemtype = $_POST["typeitem"];
$summary = $_POST["summary"];
$status = "new";
// Pretty sure this can be wrapped in your if statement, may need to test that.
// --> $request->createticket($enduser, $priority, $itemtype, $status, $summary, $date);
if($request->createticket($enduser, $priority, $itemtype, $status, $summary, $date)){
$postMSG = "success"; // sending the success message over url as $_GET
$host = $_SERVER['HTTP_HOST']; // SERVER
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\'); // Directory
$extra = 'ticketformpage.php'; // the page your form is on
header("Location: http://$host$uri/$extra?$postMSG"); // header redirect with url post added
}
Now on the page you wish to display the success message, we check to see if the GET global isset with success $_GET['success'] if it is then we set the variable and display them and add some css.
<?php
$msg = NULL; // we set to NULL for when the message is not needed
if(isset($_GET['success'])){
$msg = "Thank you for submitting through our ticket system.";
}else{
$msg = NULL;
}
NOTE: I added the success in a <span> tag and added padding and border radius, limegreen bg and darkgreen color to associate with success. 10px margin-top for form.
<div id="req_form" class="inputs">
<span class="success"><?=$msg?></span> <!--// add the success variable here-->
<div id="error"></div>
<form id="form" action="inputtest.php" method="POST">
CSS:
form {
margin-top: 10px;
}
.success {
background-color: limegreen;
color: darkgreen;
padding: 10px;
border-radius: 5px;
}
i am trying to make a checkout page with wp-invoice and a custom booking page.
Here is the code i put into my functions.php
function paypalpayment() {
global $wpdb;
$user = wp_get_current_user();
$user_ID = $user->ID;
$shortcode = $wpdb->get_row("SELECT MAX(ap.pending) AS pending, ap.book_datetime, ap.id, ap.hash FROM ea_appointments AS ap "
."INNER JOIN ea_users AS us ON ap.id_users_customer = us.id "
."WHERE us.wp_id ='".$user_ID."'");
$html = '';
if ($shortcode->pending == ''){
$html .= '<h1>Processing Error: Appointment has been deleted. </h1>';
$html .= '<p align="center"><a class="fep-button" style="width: 195px; text-align: center;" href="http://lectiotutoring.co.za/EasyBlue" /> Schedule an appointment</a></p>';
} else {
$html .= '<h2>Fee Policy</h2>';
$html .= '<p>You may reschedule an appointment without charge within 24 hours of your appointment. Cancelation of an appointment within 24 hours can either result in a refund or a credit for your next appointment per your request. You will need to inform Lectio Tutoring on the discussion board about how you would like your cancelation to be handled. If you would like a refund, refunds will be the full amount of the cost of your session minus the PayPal processing fees. There are no refunds for cancelations later than 24 hours in advance. <span class="bigger"><b>If payment is not completed within 10 minutes the appointment will be deleted.</b></span></p>';
date_default_timezone_set('Africa/Johannesburg');
$refreshtime = strtotime($shortcode->book_datetime) - strtotime("-10 minutes");
$html .= '<meta http-equiv="refresh" content="';
$html .= $refreshtime;
$html .= '">';
$html .= '<style>
ul.wpi_checkout_block.wpi_checkout_billing_address {
display: none;
}
ul.wpi_checkout_block.wpi_checkout_customer_information {
display: none;
}
ul.wpi_checkout_block.wpi_checkout_billing_information {
display: none;
}
.wpi_checkout_submit_btn.btn.btn-success.wpi_checkout_process_payment.wpi_paypal {
margin: -1px;
}
input {
margin-top: 10px;
width: 130px;
}
form.wpi_checkout .total_price {
top: 1px;
}
.loader {
border: 4px solid #f3f3f3;
border-radius: 50%;
border-top: 4px solid #3498db;
width: 30px;
height: 30px;
-webkit-animation: spin 2s linear infinite; /* Safari */
animation: spin 2s linear infinite;
}
/* Safari */
#-webkit-keyframes spin {
0% { -webkit-transform: rotate(0deg); }
100% { -webkit-transform: rotate(360deg); }
}
#keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
div#spinner {
margin-left: 160px;
position: absolute;
}
input#stepone {
position: absolute;
margin-top: -2px;
padding: 0px;
}
.bigger {
font-size:125%;
}
</style>';
$html .= '<input type="button" id="stepone" onclick="processpaypal()" value="Process Payment">';
$html .= '<div id="spinner" class="loader" style="display:none"></div>';
$html .= do_shortcode($shortcode->pending);
$html .= '<input type="button" onclick="deletapt()" value="Delete Apt.">';
$html .= '<script>
cancelurl = "http://lectiotutoring.co.za/EasyBlue/index.php/appointments/cancel/' . $shortcode->hash . '";
function deletapt(){
window.location = cancelurl;
}
jQuery(document).ready(function($) {
$("input[name=return]").val("http://lectiotutoring.co.za/payment-success/");
$("input[name=cancel_return]").val(cancelurl);
});
jQuery(document).ready(function($) {
function processpaypal($){
$("#spinner").css("display","block");
$("#stepone").css("display","none");
setTimeout(
function()
{
$(".wpi_checkout_submit_btn").click();
}, 250);
}
});
</script>';
}
return $html;
}
add_shortcode("paypalpay", "paypalpayment");
when i look for errors in my console it shows Uncaught ReferenceError: processpaypal is not defined in this area $html .= '<div id="spinner" class="loader" style="display:none"></div>';
I have converted my jquery to be compatible with wordpress but it does not seem to be working as i get that error as said above, what would be the problem? have i converted my js wrong in this area jQuery(document).ready(function($) {
function processpaypal($){
...comment are not enought i guess
Make your processpaypal function global, move it outside of the document ready. Learn more about scope here
To resolve $ conflict in wordpress, you do this.
a.
var $ = jQuery; // make sure to make it global
b.
//using jQuery instead of $ like so, (like you did it here jQuery(document))
function processpaypal(){
jQuery("#spinner").css("display","block");
jQuery("#stepone").css("display","none");
setTimeout(
function()
{
jQuery(".wpi_checkout_submit_btn").click();
}, 250);
}
Also consider this recommendations:
it's better to use separate css and js files instead of making it inline.
Create separate template file with your html output and include it using output buffering inside your function
date_default_timezone_set('Africa/Johannesburg'); you can put this at the beginning of your functions.php and this function will set timezone globaly for the whole file. reference
I have the following set up in Google tag manager using custom HTML and a PHP code in my directory file to create an exit popup to collect name, company, and email address for a discount. I have it working properly by sending saving the data to the database, however I would like to add an extra function that will send me an email with the same data information (name, company, and email address) to me after they click Sign UP. How do I add this properly.
It must stay in the format with two separate files and in this order to work in google tag manager.
<style>
#ouibounce-modal {
display: none;
}
.overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.4);
background: url(data:;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAYAAABytg0kAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAABl0RVh0U29mdHdhcmUAUGFpbnQuTkVUIHYzLjUuNUmK/OAAAAATSURBVBhXY2RgYNgHxGAAYuwDAA78AjwwRoQYAAAAAElFTkSuQmCC) repeat fixed transparent\9;
z-index: 9998;
color: #fff;
transition: opacity 500ms;
}
.content h2 {
font-size: 19pt;
color: #ed1c24;
}
.popup {
margin: 0px;
padding: 20px;
z-index: 9999;
padding-bottom: 0px;
text-align: left;
height: 350px;
background: #fff;
border-radius: 5px;
width: 225px;
position: fixed;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
color: #000;
}
.popup .closePopupCross {
position: absolute;
top: 20px;
right: 30px;
transition: all 200ms;
font-size: 30px;
font-weight: bold;
text-decoration: none;
color: #333;
}
.form-group {
padding-top: 20px;
}
.help-block {
font-size: 10pt;
color: #C71585;
}
.popup .closePopupLink {
font-size: 11pt;
color: #aaa;
margin-left: 30px;
}
.signUpButton {
background-color: #ed1c24;
border: none;
color: black;
padding: 8px 16px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 14px;
}
.noButton {
background-color: #ccc;
border: none;
color: black;
padding: 9px 16px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 14px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/ouibounce/0.0.11/ouibounce.min.js"></script>
<script>
$(document).ready(function() {
$('body').prepend('<div id="ouibounce-modal"><div class="overlay"></div><div class="popup"><div class="content"><h2>Want 5% off?</h2>Fill out the form to subscribe to our newsletter to get monthly deal days of 5% off or free ground shipping, news, and updates!<form action="/progress.php" method="POST" id="newsletter_popup"><div id="name-group" class="form-group"><label for="name">Full Name: </label><input type="text" class="form-control" name="name" placeholder="Your name"></div><div id="company-group" class="form-group"><label for="company">Company: </label><input type="text" class="form-control" name="company" placeholder="Your Company Name"></div><div id="email-group" class="form-group"><label for="email">Email: </label><input type="text" class="form-control" name="email" placeholder="mail#example.com"></div><br/><button type="submit" class="signUpButton">Sign up</button> <a class="noButton" href="#">No thanks!</a></form></div></div></div>');
$('.closePopupLink, .closeLeavePage, .overlay').click(function() {
$('.overlay, .popup').fadeOut(500);
});
$('#newsletter_popup').submit(function(event) {
$('.form-group').removeClass('has-error');
$('.help-block').remove();
var formData = {
'name' : $('input[name=name]').val(),
'company' : $('input[name=company]').val(),
'email' : $('input[name=email]').val()
};
jQuery.ajax({
type : 'POST',
url : '/progress.php',
data : formData,
dataType : 'json',
encode : true,
async : true
})
.done(function(data)
{
console.log(data);
if(!data.success)
{
if(data.errors.name)
{
$('#name-group').addClass('has-error');
$('#name-group').append('<div class="help-block">' + data.errors.name + '</div>');
}
if(data.errors.name)
{
$('#company-group').addClass('has-error');
$('#company-group').append('<div class="help-block">' + data.errors.name + '</div>');
}
if(data.errors.email)
{
$('#email-group').addClass('has-error');
$('#email-group').append('<div class="help-block">' + data.errors.email + '</div>');
}
}
else
{
$('#newsletter_popup').append('<div class="alert alert-success">' + data.message + '</div>');
//window.location = '/thank-you';
}
})
.fail(function(data) {
console.log(data);
});
event.preventDefault();
});
var _ouibounce = ouibounce(document.getElementById('ouibounce-modal'), {
aggressive: true,
timer: 0,
callback: function() { console.log('ouibounce fired!'); }
});
});
</script>
<?php
//Add email and name to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
// Create connection
$connection = mysqli_connect($servername, $username, $password, $dbname);
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
// validate the variables ======================================================
// if any of these variables don't exist, add an error to our $errors array
if(filter_var($_POST['name'], FILTER_SANITIZE_STRING) === false)
{
$errors['email'] = "The given name isn't valid.";
}
if(filter_var($_POST['company'], FILTER_SANITIZE_STRING) === false)
{
$errors['email'] = "The given company isn't valid.";
}
if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false)
{
$errors['email'] = "The given email isn't valid.";
}
if (empty($_POST['name']))
{
$errors['name'] = "Your name is required for signing up.";
}
if (empty($_POST['company']))
{
$errors['company'] = "Your Company name is required for signing up.";
}
if (empty($_POST['email']))
{
$errors['email'] = "You email is required for signing up.";
}
// return a response ===========================================================
// if there are any errors in our errors array, return a success boolean of false
if (!empty($errors))
{
// if there are items in our errors array, return those errors
$data['success'] = false;
$data['errors'] = $errors;
}
else
{
// if there are no errors process our form, then return a message
// DO ALL YOUR FORM PROCESSING HERE
// THIS CAN BE WHATEVER YOU WANT TO DO (LOGIN, SAVE, UPDATE, WHATEVER)
// show a message of success and provide a true success variable
//Check if emailadres isn't allready in our database
$sql = "SELECT name, email FROM newsletter WHERE email = '".$_POST['email']."'";
$result = mysqli_query($connection, $sql);
//When the email doesn't exist in the database
if(mysqli_num_rows($result) == 0)
{
$data['success'] = true;
$data['message'] = 'Success!';
//Add name and email to the database
$sql = "INSERT INTO newsletter (name, company, email) VALUES ('".$_POST['name']."', '".$_POST['company']."','".$_POST['email']."')";
mysqli_query($connection, $sql);
}
else
{
$errors['email'] = "Email address is already added to the database!";
$data['success'] = false;
$data['errors'] = $errors;
}
mysqli_close($connection);
}
// return all our data to an AJAX call
echo json_encode($data);
You can use function mail with variable $message as a string
$message = $_POST['name'].' '.$_POST['company'].' '.$_POST['email'];
mail($to, $subject, $message, $headers);
I would like to know how I can define CSS element dimensions before they are rendered eg. not using offset and jQuery
Can I echo php into where the width/height or position values are? eg.
<?php
$width = 290px;
$altwidth = 290;
?>
<style>
.widget {
width: <?php echo $width; ?>;
}
.altwidget {
width: <?php echo $altwidth; ?>px;
}
Would any of these work, is it completely wrong?
Similarly how would I apply JavaScript dimensions using a variable?
$(document).ready(function(){
$('.widget').css('width', <?php echo $width; ?>);
$('.altwidget').css('width', <?php echo $altwidth; ?>);
});
Your code will also works if it is written in php file.
Yes it will work, but you will have to make 290px a string for $width ( e.g. $width = "290px";), or better yet go with the $altwidth way and leave the px part out of the variable.
See below for how to dynamically set dimensions from JavaScript once the page has loaded. I have added some CSS for the example.
<html>
<head>
<?php
$width = "290px"; // Quotes added
$altwidth = 290;
?>
<style>
.widget {
width: <?php echo $width; ?>;
height: 100px;
color: white;
background: green;
cursor: pointer;
}
.altwidget {
width: <?php echo $altwidth; ?>px;
height: 100px;
color: white;
background: red;
cursor: pointer;
}
</style>
<script type="text/javascript">
var newWidgetWidth = '200';
var newAltWidgetWidth = '400';
</script>
</head>
<body>
<div class="widget" onclick="this.style.width = newWidgetWidth + 'px';">
Shrink me
</div>
<div class="altwidget" onclick="this.style.width = newAltWidgetWidth + 'px';">
Grow me
</div>
</body>
</html>
just would like to know how i can stop the position:absolute element to stop floting over the wapper div
html
<?php
echo "<div class='pinWrapper'>";
echo "<h2>New Arrivals</h2>";
echo "<br />";
$all_products = get_all_products();
while ($product = mysql_fetch_array($all_products))
{
echo "<div class='block'>";
echo "<a href='?page=product&itm=" . urlencode($product["Id"]) . "'>";
$Id = $product['Id'];
$limit = 1;
$img_set= get_images_by_id($Id, $limit);
while ($img = mysql_fetch_array($img_set))
{
echo "<img src='sto/" . $img["image_name"] ."'>";
}
echo "</a>";
echo "<a href='?page=product&itm=" . urlencode($product["Id"]) . "'>" . $product['item_name'] . "</a>";
echo "<div class='hpDis'>" . $product['sm_description'] . "</div>";
echo "</div>";
echo "<div class='clear'></div>";
}
echo "</div>";
?>
CSS
.pinWrapper {
position: relative;
margin: 0 auto;
width:720px;
}
.block{
position: absolute;
background: #eee;
padding: 1px;
width: 210px;
border: 1px solid #ddd;
-webkit-transition: all 1s ease-in-out;
-moz-transition: all 1s ease-in-out;
-o-transition: all 1s ease-in-out;
-ms-transition: all 1s ease-in-out;
transition: all 1s ease-in-out;
}
.block img {
width: 200px;
height: auto;
}
Javascript
var colCount = 0;
var colWidth = 0;
var margin = 20;
var windowWidth = 800;
var blocks = [];
$(function(){
$(window).resize(setupBlocks);
});
function setupBlocks() {
//windowWidth = $(window).width();
colWidth = $('.block').outerWidth();
blocks = [];
console.log(blocks);
colCount = Math.floor(windowWidth/(colWidth+margin*2));
for(var i=0;i<colCount;i++){
blocks.push(margin);
}
positionBlocks();
}
function positionBlocks() {
$('.block').each(function(){
var min = Array.min(blocks);
var index = $.inArray(min, blocks);
var leftPos = margin+(index*(colWidth+margin));
$(this).css({
'left':leftPos+'px',
'top':min+'px'
});
blocks[index] = min+$(this).outerHeight()+margin;
});
}
// Function to get the Min value in Array
Array.min = function(array) {
return Math.min.apply(Math, array);
};
Live example here
Any help is greatly appreciated.
If you want the wrapper div to enclose the ".block" elements, you must remove
position: absolute;
and add instead:
display: inline-block;
margin: 32px;
You might as well remove the ".clear" elements.
add z-index:-999; and that will stop it from being above anything else