I am writing a program that send bulk email to our registered users via ajax.
I want echo every loop response when it is completed and it goes to next condition.
For Example:-
I have list of 100 Emails in database. When i submitted the request to program it will start sending emails.
Prog. works something like :
<?php
foreach($emails as $email){
$status = $this->sendMail($email);
if($status == true)
{
echo "Mail Sent";
}else{
echo "Not Sent";
}
}
?>
Now i want to print "Mail Sent"/"Not Sent" again and again for every loop.
Output:-
Mail Sent
Mail Sent
Mail Sent
Not Sent
Mail Sent
Sending..
EDIT
My PHP Code is:-
<?php
public function send_message() {
$sendTo = $this->input->post('send_to');
$template = $this->input->post('template');
$subject = $this->input->post('subject');
switch ($sendTo) {
case 1:
$users = $this->getAllEmails();
break;
case 2:
$users = $this->getRegisteredUsersEmails();
break;
case 3:
$users = $this->getTemproryUsersEmails();
break;
case 4:
$users = $this->getSubscribersEmails();
break;
}
$status = $this->sendMail($users, $template, $subject);
echo "Mail Sent";
}
private function sendMail($users, $template, $subject) {
$this->load->library('parser');
$status = array();
$i = 0;
foreach ($users as $user) {
$message = $this->parser->parse('email_templates/' . $template, array('email' => $user->email, 'name' => ($user->name != '') ? "Hi " . $user->name : "Hello"), TRUE);
$response = $this->mail->send(config_item('sender_mail'), config_item('sender_name'), $user->email, $subject, $message);
$status[$i]['email'] = $user->email;
$status[$i]['status'] = ($response == 1) ? 1 : 0;
$i++;
}
return $status;
}
?>
My Ajax Code :-
<script type="text/javascript">
$("#send_mail").submit(function(){
$.ajax{
url:"<?php echo base_url('promotion/send_message'); ?>",
type:"post",
data:$(this).serialize(),
success:function(data){
$("#status").html(data);
}
}
});
</script>
You have to do your loop with javascript/jquery rather than PHP. To have no overflow on server-side you should probably only call the function on success by using recursion. This way it will be synchronous.
jQuery
var emails = [
'lorem#stackoverflow.com',
'ipsum#stackoverflow.com',
'foo#stackoverflow.com'
];
index = 0;
var sendMail = function(email){
$.ajax({
url:"sendMail.php",
type: "POST"
data: { emailId: email}
success:function(response) {
index++;
document.write(response);
if(emails[index] != undefined){
sendMail(emails[index]);
}
}
});
}
sendMail(emails[index]);
PHP
$status = $this->sendMail($$_POST['email']);
$msg = $status ? "Mail Sent" : "Not Sent";
echo $msg;
I want to print the response when each time "$this->mail->send" function is called in "sendMail()"
As your code above, $status should be return in ajax function like a json object array.so I try this one ...
private function sendMail($users, $template, $subject) {
$this->load->library('parser');
$status = array();
$i = 0;
foreach ($users as $user) {
$message = $this->parser->parse('email_templates/' . $template, array('email' => $user->email, 'name' => ($user->name != '') ? "Hi " . $user->name : "Hello"), TRUE);
$response = $this->mail->send(config_item('sender_mail'), config_item('sender_name'), $user->email, $subject, $message);
$status[$i]['email'] = $user->email;
$status[$i]['status'] = ($response == 1) ? 1 : 0;
$i++;
}
echo json_encode($status);
}
Ajax Code
<script type="text/javascript">
$("#send_mail").submit(function(){
$.ajax{
url:"<?php echo base_url('promotion/send_message'); ?>",
type:"post",
dataType : "json",
data:$(this).serialize(),
success:function(data){
$.each(data,function(i,v){
$("#status").append(v.status);
}
}
}
});
</script>
Related
I have cut this down to be a simple as possible. I create a typeahead variable that works perfectly.
but I need to pass two other variables $php_var1 and $php_var2 that are unrelated to the typeahead. The PHP variables are defined in
start.php. The typeahead script calls search_script.php then calls cart.php. cart.php is were I will need the two PHP variables to
be passed to. Thanks in advance for any help
start.php
<?php
$php_var1 = "my php variable 1";
$php_var2 = "my php variable 2";
?>
<script>
$(document).ready(function() {
var php_var1 = <?php echo $php_var1; ?>;
var php_var2 = <?php echo $php_var2; ?>;
$('#my_input').typeahead({
source: function(query, result) {
$.ajax({
url: "search_script.php",
method: "POST",
data: {
query: query
},
dataType: "json",
success: function(data) {
result($.map(data, function(item) {
return item;
}));
}
})
},
updater: function(item) {
location.href = 'cart.php?shop_name=' + item
return item
}
});
});
</script>
<form action="cart.php" action="post">
<input type="text" id="my_input" placeholder="Typeahead Search" />
</form>
search_script.php
<?php
$php_var1 = isset($_REQUEST['php_var1']) ? $_REQUEST['php_var1'] : "empty";
$php_var2 = isset($_REQUEST['php_var2']) ? $_REQUEST['php_var2'] : "empty";
$connect = mysqli_connect($servername, $username, $password, $dbname);
$request = mysqli_real_escape_string($connect, $_POST["query"]);
$query = " SELECT * FROM all_shops WHERE p_shop_name LIKE '%".$request."%'";
$result = mysqli_query($connect, $query);
$data = array();
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
$data[] = $row["p_shop_name"];
}
echo json_encode($data);
}
?>
cart.php
$php_var1 = isset($_REQUEST['php_var1']) ? $_REQUEST['php_var1'] : "empty";
$php_var2 = isset($_REQUEST['php_var2']) ? $_REQUEST['php_var2'] : "empty";
echo $php_var1;
echo $php_var2;
?>
You need quotes around the php output in order to generate javascript strings
var php_var1 = "<?php echo $php_var1; ?>";
var php_var2 = "<?php echo $php_var2; ?>";
Stackoverflow is an excellent resource, but sometimes you don't get the answer, so you need to persevere and keep trying. I worked on this all day yesterday and just couldn't figure it out. Woke up this AM and it came to me. The answer is as follows. In the typeahead script change the following line
location.href = 'cart.php?shop_name=' + item
to
location.href = 'cart.php?shop_name=' + item + '&php_var1=<?php echo $php_var1 ?>' + '&php_var2=<?php echo $php_var2 ?>'
I want to send data from php to php and in same time I also want to send data from js to php. I have one index.php which contains php and js part. In enrolled.php I want to collect my data. SQL injection or other security problems are not important. I do not get any error but it does not save to database.
Small part of index.php
<!DOCTYPE html>
<html lang="en">
<head>
//smt....Not important
</head>
<body>
//smt....Not important
<div id="dom-target" style="display: none;">
<?php
include_once "connection.php";
session_start();
$username = $_SESSION['username'];//coming from previous page.
echo htmlspecialchars($username); //for sending variable from php to js.
?>
</div>
<script type = "text/javascript">
$('#addmore').click(function(){
var subjectone = $('#selectedsubjectone :selected').val();
var courseone = $('#courseListone').val();
var gradeone = $('#selectedGradeOne :selected').val();
var div = document.getElementById("dom-target");
var username = div.textContent;//these lines help to gett data from php
document.getElementById("usernamee").innerHTML = username;//for checking
$.ajax({
type: "POST",
url: "addenrolled.php",
data: {
// Send the username (js, not php)
username: username,
subject: subjectone,
course: courseone,
grade: gradeone
}, success: function(data) {
alert("sucess");
}
});
});
</script>
</body>
</html>
enrolled.php
<?php
include_once "connection.php";
$nick = $_POST['username'];
$subject=$_POST['subject'];
$course=$_POST['course'];
$grade=$_POST['grade'];
echo "$nick -- $subject -- $course -- $grade"; //for checking
$prep = $con->prepare("INSERT INTO enrolledtable ('nickname', 'subject', 'course', 'grade') VALUES(?,?,?,?)");
$prep->bind_param("ssss", $nick, $subject, $course, $grade);
$send = $prep->execute();
if ($send == TRUE) {
echo "Courses added successfully";
header('Location: index.php');
exit();
} else {
echo "Error: " . $con->error;
header('Location: index.php');
exit();
}
?>
Change your jQuery to this
<script>
$(document).ready(function(){
$('#addmore').click(function(){
var subjectone = $('#selectedsubjectone :selected').val();
var courseone = $('#courseListone').val();
var gradeone = $('#selectedGradeOne :selected').val();
$.post('enrolled.php', {subjectone: subjectone, courseone: courseone, gradeone: gradeone, addmore: "yes"}, function(response){
console.log(response);
})
});
});
</script>
Then in your PHP modify the prepare statement to the following
$prep = $conn->prepare("INSERT INTO enrolledtable (`nickname`, `subject`, `course`, `grade`) VALUES(?,?,?,?)");
$prep->bind_param("ssss", $nick, $subject, $course, $grade);
$send = $prep->execute();
enrolled.php
<?php
session_start();
include_once "connection.php";
if (isset($_POST['addmore'])) {
$nick = $_SESSION['username'];
$subject=$_POST['subjectone'];
$course=$_POST['courseone'];
$grade=$_POST['gradeone'];
// //echo "$nick -- $subject -- $course -- $grade"; //for checking
$prep = $conn->prepare("INSERT INTO enrolledtable (`nickname`, `subject`, `course`, `grade`) VALUES(?,?,?,?)");
$prep->bind_param("ssss", $nick, $subject, $course, $grade);
$send = $prep->execute();
if ($send == TRUE) {
echo "Courses added successfully";
// header('Location: index.php');
exit();
} else {
echo "Error: " . $con->error;
//header('Location: index.php');
exit();
}
}
?>
This question already has answers here:
Make jQuery AJAX Call to Specific PHP Functions
(3 answers)
Closed 6 years ago.
I've read all the topics about my question but cannot solve my problem. I want to get php function result using jQuery AJAX.
function fetch_select(){
val_name = $('#name').val();
$.ajax({
type: 'POST',
url: 'include/get_db.inc.php',
data: {
name: val_name,
},
success: function (response) {
document.getElementById('higtchart_medie_gen').innerHTML=response;
columnChart( JSON.parse(response));
}
});
}
function columnChart(data_v){
if(data_v.length >0){
$(function () {
$('#higtchart_medie_gen').highcharts({
chart: {
type: 'column'
},
......
#name is id for select tag.
My code for get_db.inc.php is:
<?php
function test_name () {
$ret = [];
if(isset($_POST['name'])){
$name = $_POST['name'];
$sql = "SELECT
......
WHERE ID = $name ";
$result = $conn->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()) {
$ret [] = [$row['NAME'] . ' ' . $row['LASTN'], floatval($row['AVGG'])];
}
}
}
if(count($ret) >1) echo json_encode($ret);
else echo 'Not working';
}
?>
How can I call test_name function from Ajax code?
Thank you very much!
You do almost correct but only one mistake is you forget to invoke the function. What you do is just send the data to this file.
So, to fixed this. Just add test_name() to your get_db.inc.php
<?php
function test_name () {
$ret = [];
if(isset($_POST['name'])){
$name = $_POST['name'];
$sql = "SELECT
......
WHERE ID = $name ";
$result = $conn->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()) {
$ret [] = [$row['NAME'] . ' ' . $row['LASTN'],floatval($row['AVGG'])];
}
}
}
if(count($ret) >1) echo json_encode($ret);
else echo 'Not working';
}
test_name()
?>
Also it will be better to check isset outside the function.
function test_name ($name) {
$ret = [];
$sql = "SELECT
......
WHERE ID = $name ";
$result = $conn->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()) {
$ret [] = [$row['NAME'] . ' ' . $row['LASTN'],floatval($row['AVGG'])];
}
}
if(count($ret) >1) echo json_encode($ret);
else echo 'Not working';
}
if(isset($_POST['name'])){
test_name($_POST['name'])
}
This will make your function to be pure. It will easier to debug later and it will not invoke if you don't have $_POST['name'].
I'm having trouble returning a status message from a php file to an ajax function in an html file. When go to submit I get [Object object] on the screen. From what I understand json_encode would be able to return the object $answer with its value. Am I missing something here?
php
<?php
require_once 'dbconfig.php';
require_once('FirePHPCore/fb.php');
ob_start();
$answer = new stdClass;
if(isset($_POST))
{
$uname;
$pword;
//email = ema
$ema;
$answer->result = "successful";
$answer->text = "";
foreach($_POST as $key => $value)
{
if($key == 'u')
{
$uname = $value;
}
else if($key == 'p')
{
$pword = $value;
}
else if($key == 'em')
{
$ema = $value;
}
}
}
else
{
$answer->result = "Error";
$answer->text = "Error Message";
}
$check = mysqli_query($con, "SELECT username FROM users WHERE username = '$uname'") or die(mysql_error());
$check2 = mysqli_num_rows($check);
if ($check2 != 0) {
$answer->text = "sorry username taken";
$ansr = json_encode($answer);
echo $ansr;
die('Sorry, the username is already in use.');
}
exit(0);
?>
ajax in my html file
$.ajax({
type: "POST",
url: "registration.php",
dataType: "json",
data : { u: un, p:p1, e:em },
cache: !1,
beforeSend: function(){
$("#submit").hide();
$('#status').text('please wait ...');
},
complete: function(){
$("#submit").show();
},
success: function(answer){
if(answer.result == "successful")
{
$("#status").html(answer.text);
}
else
{
$("#status").html(answer.result);
}
},
error: function(answer){
$("#status").text(answer);
}
});
any advice or hints would be appreciated.
Thanks #RamRaider !
Using die() right after using json_encode invalidated the data.
I wrote the ajax in the JavaScript function. That code is
function getValidate(checkID)
{
alert(checkID);
$.ajax({
type: 'post',
url: 'checkval.php',
datatype: 'json',
data: {checkID : checkID},
success: function (response) {
if (response === "OK"){
alert("Validation Successed.");
}else if(response === "NG"){
alert("Check Already Exists.");
}
},
error : function(err, req) {
alert("Error Occurred");
}
});
}
this code is outputs only "Error Occurred".
the connected php script is
<?php
echo("welcome");
$check = $_POST['checkID'];
$host = 'localhost';
$database = 'database';
$username = 'root';
$password = 'root';
$dbc = mysqli_connect($host,$username,$password,$database);
$checkno = $check;
$sql = "select claimno from check_details where checkno = $checkno";
$result = mysqli_query($dbc,$sql);
$rows = mysqli_num_rows($result);
if($rows != 0)
{
echo "NG";
}
else
{
echo "OK";
}
?>
at a time of calling the JavaScript function php file not executed......
please give me the idea to success it...........
Try this :
if($rows != 0)
{
$return = "NG";
}
else
{
$return = "OK";
}
echo json_encode($return);
Also you set datatype to json so response data must be json type
$.ajax({ dataType:"json"});
In php, store result in one variable and return json_encode
<?php
echo("welcome");
$check = $_POST['checkID'];
$host = 'localhost';
$database = 'database';
$username = 'root';
$password = 'root';
$dbc = mysqli_connect($host,$username,$password,$database);
$checkno = $check;
$sql = "select claimno from check_details where checkno = '$checkno'"; //use single quote
$result = mysqli_query($dbc,$sql);
$rows = mysqli_num_rows($result);
if($rows != 0)
{
$res = "NG";
}
else
{
$res = "OK";
}
echo json_encode($res);
?>
You are getting error occurred, because of below code. Try logging something meaningful to triag this.
error : function(err, req) {
alert("Error Occurred");
}
Please try below code to get a clue of the error
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
Reference: Take a look at this query
It seems that the php script is not working well.
Debug it with try and catch and see what output is comming.