Sending out e-mail and updating table with AJAX in WordPress - javascript

I'm currently making a WordPress plugin where I want to be able to send e-mail to people from a list. I have made the form (id: campaign), and all checkboxes seems to work. The form submit to itself with a query string, so in the same file I have a if-then that check if this query string has some data.
I have made an admin page with a sub form underneath that lists all e-mail addresses:
I want the script to send out e-mails to each e-mail that has been selected, updating the MySQL table that the mail has been sent, and showing a counter on the page (i.e. '#/15 e-mails sent'). I know how to make this script in plain PHP, but my lack of knowledge with AJAX is the problem.
So this is what I want:
The form sending data to itself (same PHP file) - this is working.
Starting the AJAX script based on the selected checkboxes
Sending out e-mails and updating the SQL table based on a timer (to avoid spam)
Showing real-time counter
This is what I have so far:
<div id="feedback"></div>
<?php
add_action('wp_ajax_sendPromo', 'sendPromo');
add_action('wp_ajax_nopriv_sendPromo', 'sendPromo'); // not really needed
?>
<script type="text/javascript">
jQuery('#campaign').submit(ajaxSubmit);
function ajaxSubmit(){
var campaign = jQuery(this).serialize();
jQuery.ajax({
type:"POST",
url: "/wp-admin/admin-ajax.php",
data: campaign,
success:function(data){
jQuery("#feedback").html(data);
}
});
return false;
}
</script>
<?php
function sendPromo(){
global $wpdb;
$recepients = $_GET['recepients_email']; // array of checkboxes
for($i=0; $i < count($recepients); $i++){
mail($recepients[$i], $subject, $message, $headers); // mail is being sent
if($wpdb->update('wp_ap_promo',array(
'sent'=>1
), array( 'email' => '" . $recepients[$i] . "' ))===FALSE){
echo "Error";
}
else {
echo "Successfully sent to '".$recepients[$i]. "', row ID is ".$wpdb->update_id;
}
}
die();
}
One of the problems seems to be that the JS isn't being run because the page is reloading (it is meant to reload, because I want the user to see a plain page with the send counter.

Related

PHP records not inserted to database using Ajax

here is the AJAX request body
Ajax
var date = new Date().toLocaleTimeString();
var text=this.value;
var id=1;
$.ajax({
type: "GET",
url: "StoreMessages.php" ,
data: { room: id, msg:text,sendat:date }
});
PHP Code
if(isset($_GET['room']))
{
$chatroom_name = $_GET['room'];
if(isset($_GET['msg']))
{
$text= $_GET['msg'] ;
if(isset($_GET['sendat']))
{
$local_time= $_GET['sendat']);
insertMessage( $text,$local_time, $chatroom_name);
}
}
}
function insertMessage($message_body,$local_time,$room_id)
{
echo "<script type='text/javascript'>alert('$message_body');</script>";
echo "<script type='text/javascript'>alert('$local_time');</script>";
echo "<script type='text/javascript'>alert('$room_id');</script>";
$conn = new mysqli($GLOBALS['server'], $GLOBALS['user'], $GLOBALS['pass'], $GLOBALS['db_name']);
if($conn==false)
{
die("unable to connect database");
}
$sql="INSERT INTO `message` (`Message_Text`, `Time`, `Conversation_Id`) VALUES ('$message_body', '$local_time', '$room_id')";
if(mysqli_query($conn,$sql)){
echo "record inserted successfully"."<br/>";
}
else{
echo "error".mysqli_error($db_conn);
}
Explanation
ajax call triggers when user typed message and hit enter key ajax data field variable contains value i checked then by setting alert when i checked the the data field variables value by setting alert in php code there only text variable contain value and alertbox didn't appears for other variables acutally i am trying to store live chat to database
The first step to debugging this is is/was diagnosing where the failure occurred. To do this:
Open your developer console
Go to the network tab
Make whatever action triggers the AJAX request
Click the request that appears in the network tab
Go to the response tab*
*If the status code of the request is a 500 that also is an indication that the script is failing on the PHP side. Go to the server and look at the error logs.
From the response we got in the response tab we identify the issue to be the trailing closing parenthesis on this line:
$local_time= $_GET['sendat']);
Additionally you should use parameterized queries. A single quote in any of the fields will break your query.
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
Roughly:
$sql="INSERT INTO `message` (`Message_Text`, `Time`, `Conversation_Id`) VALUES (?, ?, ?)";
Then prepare that, bind the values, and execute the query.
Also I'd send back a JSON object rather than JS code. Take a look at http://php.net/manual/en/function.json-encode.php.

Sql queries doesnt work when inside a php function

So the main problem is, when i make some query just after a post[] or whatever and its just in the main code of the php (not in a function) it works perfectly fine..
But, when i try and have that query inside a php function,it never works, and kinda hiding any other code on the rest of the page... I have a few divs after that php and sql query code, and they just dont show when i try to query through the function..
<script type="text/javascript">
function callPhpVoteAdd(name) {
var result = <?php voteAdd(name); ?>;
alert(result);
return false;
}
</script>
<?php
echo '</br>';
$allsql = "SELECT * FROM voting ORDER BY votes DESC";
$result = mysqli_query($conn, $allsql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$name = $row["name"];
$votes = $row["votes"];
echo '<form method="post">
name: "' .$name. '" - votes: "' .$votes. '" <input type="submit" name="'.$name.'" value="'.$name.'" onclick="callPhpVoteAdd(this.name)"/><br>
</form>';
}
}
function voteAdd($name) {
if($conn->query("UPDATE voting SET votes = votes + 1 WHERE name = '".$name."' ") === TRUE) {
echo "<script>alert('fuck yeah');</script>";
}
echo "shit";
}
So the button pressed calls the js function, which calls the php function
I guess you're misunderstanding the way JS and PHP works. PHP works server side, and JS, in your case, client side. And so, PHP generate the script/page before it's sent to the browser, so when JS runs it, all the <?php ?> are already replaced by static data.
So, to put it shortly and simply, you just can't call a PHP function from JS after your page is loaded, the way you tried to (because the call isn't there anymore - check your source code from your browser).
You need either to :
use a form with an "action" attribute ; this will send the data to server, and call the php script set in "action", where you can handle the sent data, and then reload the page with the new/updated data,
use ajax (almost the same thing : this sends data to server and call a php script to handle them, but instead of reloading the page, the output of the PHP script - with the data you need - will be sent back to JS, to a callback function, where you'll be able to use them to modify the page).

Submit, mysql query + http request to a SMS gateway using JavaScript

I am receiving some data to my confirm.php file. The confirm.php file contains the below code.
I am stuck on the javascript and would really appreciate all input and help.
What I want my javascript to do is: When the user click the submit "Approve & SMS" button, a query is sent to my DB (with customer, tasks and user data) and at the same time a http request is sent to a SMS gateway. After the user has clicked the "Approve & SMS" button, an alert box pops up and when the user click OK in the alert box, I want to redirect the user to my index.php.
Note: I do not need suggestion on the actually mysql query, just on how to make the magic trigger to send a query + the http request with javascript (it do not have to be purely javascript suggestions,, all solutions are welcome as long as they solve my problem).
CONFIRM.PHP
<?php
//check session to get customer
if(!isset($_SESSION['customer'])) {
die('$'."_SESSION['customer'] Session ended");
} else {
$customer = $_SESSION['customer'];
echo $customer;
}
?>
<?php
if(isset($_POST['submit'])) {
// Fetching variables of the form which travels in URL
$tasks = $_POST['tasks'];
$user = $_POST['user'];
?>
SMS API stuff
<?php
//Create $sms_url to send sms to customer
// The necessary variables
$sms_message = ("this is a text");
$sms_url = "http://the.domain/sms/";
$sms_url .= "?message=" . urlencode($sms_message); //messages
$sms_url .= "&recipient=$customer"; // Recipient
$sms_url .= "&from=" . urlencode("name company."); // Sendername
//echo $sms_url;
?>
SOME HTML
<form id="sms_insert_data" action="???" method="POST">
<input class="submit" name="showWordCard" type="submit" value="Approve & SMS"></input>
</form>
JAVASCRIPT
$(document).ready(function(){
$('.submit').click(function(){
var foo = alert('Card created and SMS sent to: <?php echo json_encode($customer); ?>');
window.location = "..//index.php"
});
});
You can use jQuery ajax to send a http request to a php script and/or to your sms gateway.
http://api.jquery.com/jquery.ajax/

PHP inside Javascript in a registration form (for validation)

I'm developing a registration form for my site. Actually when a visitor choose an username, a php query to my MySQL DB is used to control if it's already used and if so, a javascript windowd appear.
Can i use a PHP query inside Javascript for displaing a real-time notice near the form (using HTML5)?
<script>
var username = document.getElementById('username');
var userdb = <? php control_username($username); ?>
var checkUsername = function () {
if (userdb.value == true) {
username.setCustomValidity('Username already used');
} else {
username.setCustomValidity('');
}
};
username.addEventListener('change', checkUsername, false);
</script>
and here there's the php function:
<?php function control_username($username){
$db=connessione_db();
$query = "SELECT username FROM utente WHERE username = '$username';";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
mysql_close();
if($row[0]==$username){
return TRUE;
}
else{
return FALSE;
}
$query=NULL;
}
how can i do?
You can use AJAX or jQuery AJAX to send a request to a php page, Check if the username exists, return the result, and display it using Javascript again.
Here is the jQuery sample:
<script>
$.ajax({
type: 'POST',
url : 'checkUsername.php',
data: {'username' : $('#username').html()},
cache : false,
success: function(data){
if(data == 'exists')
//username exists
alert('username already exists!');
},
error: function(request , status , error){
alert(request.resposeText);
}
});
</script>
and this should be your checkUsername.php file:
<?php
$db=connessione_db();
$query = "SELECT count(*) as count FROM utente WHERE username = '$username'";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
mysql_close();
if($row[count] > 0)
echo 'exists';
else
echo '';
PHP is run on the server, Javascript is run on the client's machine. Once your PHP script has generated a page and sent it to the user, it doesn't run any longer. Your client has no knowledge of a PHP script. It can't directly run, call, or read anything about your PHP script because it resides solely on the server (never on the client's machine). Your client's machine does, however, know about your Javscript since it has been sent along with the page. If you want to access PHP functionality from your page, you can either send a GET/POST call to the server and reload the page, or use AJAX to make the call in the background. Check out Jquery's implementation of AJAX calls, it makes using it pretty simple.
No you can't do it like that. PHP is serverside, Javascript clientside. The moment Javascript is executed is the code working clientside. All PHP code is fixed.
Compare it to the combination of HTML and PHP in an HTML page. It is fixed there as well. Same applies to PHP in Javascript.
Here are some answers from related questions on stackoverflow:
How to put php inside javascript?
How to embed php in javascript?
Here is an example from ajaxref, showing the basics:
http://ajaxref.com/ch3/asyncsend.html
This is another tutorial showing how an ajax call is handled:
http://code.tutsplus.com/articles/how-to-make-ajax-requests-with-raw-javascript--net-4855
I advice you to first understand this process and later on start using a framework like jQuery.

JavaScript events, mixed with PHP?

I have encountered a huge error for an idea I came up with. So I am working on a project, on my main website and we needed to put up a being worked on page, yadayda but I wanted to add the functionality of letting the user send us their email , but after we received that data a pop dialog would show.. But this doesn't work as I would like for it to.
So what I need help with, is actually the PHP and the JavaScript event to make it acknowledge that the message and email was sent, then show the dialog box. Does anyone know how to do this? Or maybe at least how to make a dialog show after a user did something, like entered information rather then just clicking a button? If anyone can help I would ridiculously appreciate it!
If you use jQuery, you can make an AJAX call to your serverside script and use the success callback to initiate the dialog on the client side.
$.ajax({
url: 'ajax/test.php',
data: { name: "WeLikeThePandaz", email: "panda#gmail.com" },
success: function(response) {
if (response.status == "OK"){
// Show dialog
}else{
// Let the user know there were errors
alert(response.error);
}
}
},'json');
Here is the relevant documentation for using the $.ajax method -
http://api.jquery.com/jQuery.ajax/
Your server side PHP code in ajax/test.php can then decipher the data that was sent and assemble a json object to be returned to the jQuery -
<?php
$err= '';
$name = sanitizeString($_POST['name']);
$email = sanitizeString($_POST['email']);
// note the sanitization of the strings before we insert them - always make sure
// to sanitize your data before insertion into your database.
// Insert data into database.
$result = mysql_query('INSERT INTO `user_table` VALUES...');
if (!$result) {
$status = "FAIL";
$err = mysql_error();
}else{
$status = "OK";
}
echo json_encode(array('error'=>$err,'status'=>$status)); // send the response
exit();
?>

Categories

Resources