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();
}
}
?>
Related
index.php
<script>
$(document).ready(function(){
$("#login").click(function(e){
e.preventDefault();
email = $("#cs-username-1").val();
password = $("#cs-login-password-1").val();
if(email=='' || password=='')
{
$("#loginsuccess").html("<p id='red'>All fields are mandatory!<p>");
}
else
{
$.ajax({
type:"POST",
data:{"email":email,"password":password},
url:"login.php",
success: function(data)
{
if (typeof data !== 'object') {
data = JSON.parse(data);
}
if (data.redirect) {
window.location.replace(data.redirect);
} else {
$("#loginsuccess").html('<p id="red">' + data.error + '</p>');
}
}
});
}
});
});
</script>
login.php
<?php
include("config.php");
$email = mysqli_real_escape_string($con, $_POST['email']);
$password = md5($_POST['password']);
$sql = mysqli_query($con,"select student_id from student where email='".$email."' and password='".$password."' and status='1'");
if (mysqli_num_rows($sql) > 0)
{
$results = mysqli_fetch_array($sql);
$_SESSION['student'] = $results['student_id'];
if (!isset($_POST))
{
header ("Location: dashboard.php");
}
else
{
echo json_encode(array('redirect' => "dashboard.php"));
}
}
else
{
echo json_encode(array('error' => 'Wrong email or password or may be your account not activated.'));
}
?>
dashboard.php
<?php
session_start();
echo $_SESSION['student'];
/*if(!isset($_SESSION['student']))
{
header("location: index.php");
}*/
include('assets/db/config.php');
?>
In this code I am simply create login module. Here, what happen I am create login via jQuery where I have login.php file and I am storing student_id inside the session variable but when I redirect to dashboard.php and echo $_SESSION['student'] then it throw an error i.e. Notice: Undefined index: student in C:\xampp\htdocs\test\dashboard.php on line 3 I don't know why where am I doing wrong? Please help me.
Thank You
Please start the session in login.php file :
include("config.php");
session_start();
$email = mysqli_real_escape_string($con, $_POST['email']);
$password = md5($_POST['password']);
Or put the session_start in config.php file
I'm developing a website using php. I have some problems. I want to know know how to get modified table values while running the php page without refreshing the page.
<html>
<?php
function fun_get_user_name() {
$host_name = "localhost";
$db_user_name = "root";
$password = "";
$database_name = "database_name";
$connect = mysqli_connect($host_name, $db_user_name, $password, $database_name);
$query = "SELECT * FROM `users` ";
$result = mysqli_query($connect, $query);
$output = "";
while ($row = mysqli_fetch_array($result)) {
$output = $output."<br/>"..$row[0];
}
}
?>
<script>
function js_function() {
result = "<?php echo fun_get_user_name; ?>";
document.getElementById('div_body_users').innerHTML = result;
}
window.setInterval(function() {
js_function();
}, 1000);
</script>
<body>
<div id="div_body_users">
</div>
</body>
</html>
when I made a change in phpmyadmin table the change didn't affect the page. But I expected the updated table.
So move the fun_get_user_name to another file and then in a setInterval do a n ajax call to that file.
$.get( "users.php", function( data ) {
$( ".result" ).html( data );
alert( "Load was performed." );
});
For more info on ajax request look at this link
https://api.jquery.com/jquery.get/
On user.php you just need to add fun_get_user_name
You can do it with using ajax, here changed with your ajax url and database connection details.
<html>
<?php
function fun_get_user_name()
{
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
$sql = "SELECT * FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}
}
if($_GET['ajax']==1){
$data=fun_get_user_name();
echo $data;
exit(0);
}
?>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script>
$(document).ready(function(){
setInterval(js_function,1000);
function js_function()
{
$.ajax({
url: "http://localhost/test2/test.php?ajax=1",
data: '',
cache: false,
processData: false,
contentType: false,
type: 'POST',
success: function (result) {
document.getElementById('div_body_users').innerHTML=result;
}
});
}
});
</script>
<body>
<div id="div_body_users">
</div>
</body>
</html>
You for update page without page refresh you have to use AJAX along with setInterval function.
Please check below link
https://www.w3schools.com/asp/asp_ajax_intro.asp
I didn't find an answer so im asking you guys.
window.location.reload() constantly reloads without a break.
I'm trying to make something that checks if the form has no input in it, and if doesn't I want it to make an alert, it's working but it reloads constantly. Here's my code:
<?php
$from = $_POST['email_adress'];
$subject = $_POST['subject'];
$select = $_POST['select'];
$message2 = $_POST['message2'];
$name = $_POST['firstname'];
$name2 = $_POST['lastname'];
if ($_POST['firstname'] == "") {
echo '<script language="javascript">';
echo 'alert("First Name is Mandatory.");';
echo 'window.location.reload("contactus.html");';
echo '</script>';
exit;
}
elseif ($_POST['subject'] == "") {
echo '<script language="javascript">';
echo 'alert("Subject is Mandatory.");';
echo 'window.location.reload("contactus.html");';
echo '</script>';
exit;
}
elseif ($_POST['email_adress'] == "") {
echo '<script language="javascript">';
echo 'alert("Email Adress is Mandatory.");';
echo 'window.location.reload("contactus.html");';
echo '</script>';
exit;
}
elseif ($_POST['message2'] == "") {
echo '<script language="javascript">';
echo 'alert("A Message is Mandatory.");';
echo 'window.location.reload("contactus.html");';
exit;
echo '</script>';
exit;
} else {
header("Location: contactus.html");
$email_subject = "A submittion form";
$to ="sudaiguy1#gmail.com";
$headers = "From: sudaiguy1#gmail.com";
$email_body = 'You have been contacted by $name $name2 and his email is $from. \n The message he wanted to say was in the general subject of $select and more specifically $subject and the message is $message2';
mail($to,$email_subject,$email_body, $headers);
}
?>
Maybe this can be an inspiration?
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
$is_redirect = isset($_SESSION['to']);
if ($is_redirect && !is_mail_valid($_SESSION)) {
$to = $_SESSION['to'];
$subject = $_SESSION['subject'];
$body = $_SESSION['body'];
}
$_SESSION = array();
} else {
if (is_mail_valid($_POST)) {
$to = $_POST['to'];
$subject = $_POST['subject'];
$body = $_POST['body'];
mail($to, $subject, $body);
} else {
$_SESSION = $_POST;
}
header("Location: index.php");
exit;
}
function is_mail_valid($mail) {
global $errors;
global $valid;
$errors = array();
if (trim($mail['to']) == FALSE) { $errors['empty_to'] = TRUE; }
if (trim($mail['subject']) == FALSE) { $errors['empty_subject'] = TRUE; }
if (trim($mail['body']) == FALSE) { $errors['empty_body'] = TRUE; }
$valid = empty($errors);
return $valid;
}
?>
<?php if (!$valid) { ?>
<script type="text/javascript">
<?php if ($errors['empty_to']) {?>
alert('To: cannot be empty')
<?php } ?>
<?php elseif ($errors['empty_subject']) {?>
alert('Subject: cannot be empty')
<?php } ?>
<?php elseif ($errors['empty_body']) {?>
alert('Body: cannot be empty')
<?php } ?>
</script>
<?php } ?>
<form method="post">
<div>
<label for="to">To</label>
<input id="to" type="email" name="to" value="<?php echo $to;?>" />
</div>
<div>
<label for="subject">Subject</label>
<input id="subject" type="text" name="subject" value="<?php echo $subject;?>" />
</div>
<div>
<label for="body">Body</label>
<textarea id="body" name="body"><?php echo $body;?></textarea>
</div>
<div>
<input type="submit" value="Send">
</div>
</form>
Basically you start using session using session_start()
On POST:
If you don't have an error:
send the mail
redirect to the conctactus page.
If you have an error:
save the input in the session
redirect to the contact us page
On GET:
If you have nothing in session or the mail in session is valid, just render the html.
If you have something in session and that data is invalid, render the html, render the alert script, and set the "value" attributes of the input to maintain the user's input values.
Clear the session data.
This solution requires that you change your contactus.html to contactus.php in order to use sessions.
<?php
// to use a session, you must start it
session_start();
// variable to store any error message
$error = null;
$from = $_POST['email_adress'];
$subject = $_POST['subject'];
$select = $_POST['select'];
$message2 = $_POST['message2'];
$name = $_POST['firstname'];
$name2 = $_POST['lastname'];
if ($_POST['firstname'] == "") {
$error = "First Name is Mandatory.";
} elseif ($_POST['subject'] == "") {
$error = "Subject is Mandatory.";
} elseif ($_POST['email_adress'] == "") {
$error = "Email Adress is Mandatory.";
} elseif ($_POST['message2'] == "") {
$error = "A Message is Mandatory.";
}
if ($error) {
// store the error in a session so that you can use it on another page
$_SESSION['error'] = $error;
} else {
$email_subject = "A submittion form";
$to ="sudaiguy1#gmail.com";
$headers = "From: sudaiguy1#gmail.com";
$email_body = 'You have been contacted by $name $name2 and his email is $from. \n The message he wanted to say was in the general subject of $select and more specifically $subject and the message is $message2';
mail($to,$email_subject,$email_body, $headers);
}
// regardless of whether there is an error or not, it always goes to Contact Us page
header("Location: contactus.php");
exit;
?>
Then in your contactus.php, you would have
<?php
// resume session again
session_start();
?>
<!-- somewhere in your HTML code -->
<?php if (isset($_SESSION['error'])) : ?>
<div class="error-message"><?php echo $_SESSION['error'] ?></div>
<?php endif ?>
<?php
// you probably will want to remove the error afterwards
unset($_SESSION['error']);
?>
If you can't do that, then this solution will not work and you'll have to resort to AJAX (where you send back your error message via the response you get back from your AJAX response).
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>
I want to add comment on pressing enter and want to store it to my database with the specific t_id for it so that i can show it on the page after submission but when i enter text and press enter it does nothing.and i am also suspicious about my add_comment.php fule query because t_id is forgien key in comments table and primary in topics i am at very beginer level in jquery,php and ajax...Any Help will be appreciated.
Here is my Jquery From Send.php
$(document).ready(function(){
$('a').on('click',function(e){
$('#Comments').html('<textarea id="D_Comment" name="D_Comment"></textarea>');
$('a').on('input',function(ev){
$('#Enter_Comments').on('click',function(event){
var d_comnt = $('#D_Comment').val();
if (event.which == 13) {
alert("You Hit Enter");
e.preventDefault();
$.ajax({
url : "ajax/add_comment.php",
type : "POST",
data : {D_Comment : d_comnt},
success : function(data){
console.log(data);
},
error : function(data){
alert(data);
}
});
}
});
// ev.preventDefault();
// return false;
});
//e.preventDefault();
return false;
});
});
and my html from send.php on same page with php showing post from database
<section id="Main_Content">
<?php
mysql_connect("localhost","root","") or die("Could not coonnect");
mysql_select_db("forum") or die("could not select db");
$last_id = mysql_real_escape_string($_GET['t_id']);
$sql = "SELECT * FROM Topics WHERE t_id = '".$last_id."'";
$query = mysql_query($sql);
$row = mysql_fetch_assoc($query);
echo "<article>";
// echo $row['t_id'];
echo "<h2>".$row['name']."</h2>"."<br/>";
//echo "<a href='#'>".$row['date']."</a>";
// echo "<a href='#'>".$row['date']."</a>";
echo "<p> Posted on ".$row['date']."</p>"."<br/>" ;
echo "<p>".$row['detail']."</p>"."<br/>" ;
echo "<a href='t_id=".$row['t_id']."' id='Enter_Comments'>"."Enter Comment". "</a>";
echo "</article>";
?>
<div id="Comments"></div>
</section>
and my add_comment.php fiel is
<?php
mysql_connect("localhost","root","") or die("Could not coonnect");
mysql_select_db("forum") or die("could not select db");
$d_cmnt = mysql_real_escape_string($_POST['D_Comment']);
$t_id = mysql_real_escape_string($_GET['t_id']);
$sql = "INSERT INTO comments (comment,t_id,date) VALUES('$d_cmnt','$t_id',Now())";
$query = mysql_query($sql);
if ($query) {
echo "Success";
}
else{
echo "Error";
}
?>