Echoing php into javascript variable not working - javascript

So I have it set so when I click a button it creates an XMLHttpRequest object which is used to get the data I want.
onclick button runs
function allcontactstable() {
var url = "php_scripts/allcontactstable.php";
tablerequest.open("GET", url, true);
tablerequest.onreadystatechange = inserttable;
tablerequest.send(null);
}
php is
$mysql = mysql_connect("localhost", "admin", "");
$db = mysql_select_db("arw29");
$query = "Select `firstname`, `lastname`, `email` from `contacts`";
$result = mysql_query($query);
$output = null;
$output .= '<table>';
while($row = mysql_fetch_assoc($result)){
$output .= '<tr>';
$output .= '<td>'.$row['firstname'].'</td>';
$output .= '<td>'.$row['lastname'].'</td>';
$output .= '<td>'.$row['email'].'</td>';
$output .= '</tr>';
}
$output .= '</table>';
echo $output;
mysql_close();
and the callback function is
function inserttable() {
if (tablerequest.readyState == 4) {
if (tablerequest.status == 200) {
var response = tablerequest.responseText;
document.getElementById("main").innerHTML = response;
}
else {
alert("Error: " + tablerequest.statusText);
}
}
}
What the result is that the div on my webpage does not contain the formatted table like I was expecting, and instead contains the string
'
'; while($row = mysql_fetch_assoc($result)){ $output .= ''; $output .= ''.$row['firstname'].''; $output .= ''.$row['lastname'].''; $output .= ''.$row['email'].''; $output .= ''; } $output .= ''; echo $output; mysql_close(); ?>'
Tried searching and could not find anything that related to this.

Related

php send mail how to send mail with file attachment [duplicate]

This question already has answers here:
Send attachments with PHP Mail()?
(16 answers)
Closed 3 years ago.
I'm working on file attachment here mail function is working fine I'm getting all fields through mail accept file upload field is not coming. I have tried using Content-Type: multipart/mixed and some other methods but unable to achieve the desired output. I have servey and find the different answer and tried but still facing the same issue. Can anyone suggest to me according to my script how should I get the file attachment.
HTML
<input id="file-upload" name="upload" type="file" required>
PHP mail function
<?php
// Receiver mail id
$mail_to = 'yourmail#gmail.com';
// Mail Subject
$subject = 'title';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if ( isset($_POST['name']) ) {
$name = $_POST['name'];
}
if (isset($_POST['phone'])) {
$phone = $_POST['phone'];
}
if (isset($_POST['company'])) {
$company = $_POST['company'];
}
if(isset($_POST['message'])) {
$message = $_POST['message'];
}
if(isset($_POST['industry'])) {
$industry = $_POST['industry'];
}
if(isset($_POST['job'])) {
$job = $_POST['job'];
}
if(isset($_POST['upload'])) {
$upload = $_POST['upload'];
}
// Message body
$msg = '<html><body><p>';
$msg .= '<b> Name : </b>' . $name . '<br/>';
if($_POST["phone"] != "") {
$msg .= '<b> Phone : </b>' . $phone . '<br/>';
}
if($_POST["company"] != "") {
$msg .= '<b> Company : </b>' . $company . '<br/>';
}
if($_POST["message"] != "") {
$msg .= '<b> Message : </b>' . $message . '<br/>';
}
if($_POST["industry"] != "") {
$msg .= '<b> Industry : </b>' . $industry . '<br/>';
}
if($_POST["job"] != "") {
$msg .= '<b> Job Role : </b>' . $job . '<br/>';
}
if($_POST["upload"] != "") {
$msg .= '<b> Upload : </b>' . $upload . '<br/>';
}
$msg .= '</p>';
$msg .= '</body></html>';
// Mail headers
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$headers .= 'From: yourmail#gmail.com' . "\r\n";
if( mail( $mail_to, $subject, $msg, $headers )) {
echo "Thank You!";
} else {
die("Error!");
}
}
?>
I had tried like this here only file coming other fields not coming in the mail. what I'm missing here.
<?php
// Receiver mail id
$mail_to = 'yourmail#gmail.com';
// Mail Subject
$subject = 'project';
$path = 'assets/file';
$filename = 'myfile';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if ( isset($_POST['name']) ) {
$name = $_POST['name'];
}
if (isset($_POST['phone'])) {
$phone = $_POST['phone'];
}
if (isset($_POST['company'])) {
$company = $_POST['company'];
}
if(isset($_POST['message'])) {
$message = $_POST['message'];
}
if(isset($_POST['industry'])) {
$industry = $_POST['industry'];
}
if(isset($_POST['job'])) {
$job = $_POST['job'];
}
if(isset($_POST['upload'])) {
$upload = $_POST['upload'];
}
// Message body
$msg = '<html><body><p>';
$msg .= '<b> Name : </b>' . $name . '<br/>';
if($_POST["phone"] != "") {
$msg .= '<b> Phone : </b>' . $phone . '<br/>';
}
if($_POST["company"] != "") {
$msg .= '<b> Company : </b>' . $company . '<br/>';
}
if($_POST["message"] != "") {
$msg .= '<b> Message : </b>' . $message . '<br/>';
}
if($_POST["industry"] != "") {
$msg .= '<b> Industry : </b>' . $industry . '<br/>';
}
if($_POST["job"] != "") {
$msg .= '<b> Job Role : </b>' . $job . '<br/>';
}
if($_POST["upload"] != "") {
$msg .= '<b> Upload : </b>' . $upload . '<br/>';
}
$msg .= '</p>';
$msg .= '</body></html>';
$file = $path.$filename;
$content = file_get_contents( $file);
$content = chunk_split(base64_encode($content));
$uid = md5(uniqid(time()));
$uploadname = basename($file);
$replyto = 'test';
$headers = "From: ".$subject." <".'yourmail#gmail.com'.">\r\n";
$headers .= "Reply-To: ".$replyto."\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
$msg = "--".$uid."\r\n";
$msg .= "Content-type:text/plain; charset=iso-8859-1\r\n";
$msg .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$msg .= $msg."\r\n\r\n";
$msg .= "--".$uid."\r\n";
$msg .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n";
$msg .= "Content-Transfer-Encoding: base64\r\n";
$msg .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
$msg .= $content."\r\n\r\n";
$msg .= "--".$uid."--";
if( mail( $mail_to, $subject, $msg, $headers )) {
echo "Thank You!";
} else {
die("Error!");
}
}
?>
You can send like this.
$file_type = 'pdf';
$file_name = 'invoice.pdf';
$encoded_content = chunk_split(base64_encode($document));
$boundary = md5("random"); // define boundary with a md5 hashed value
//header
$headers = "MIME-Version: 1.0\r\n"; // Defining the MIME version
$headers .= "From: Fr. Muller\r\n"; // Sender Email
$headers .= "Content-Type: multipart/mixed;\r\n"; // Defining Content-Type
$headers .= "boundary = $boundary\r\n"; //Defining the Boundary
//plain text
$body .= "--$boundary\r\n";
$body .= "Content-Type: text/plain; charset=ISO-8859-1\r\n";
$body .= "Content-Transfer-Encoding: base64\r\n\r\n";
//attachment
$body .= "--$boundary\r\n";
$body .="Content-Type: $file_type; name=".$file_name."\r\n";
$body .="Content-Disposition: attachment; filename=".$file_name."\r\n";
$body .="Content-Transfer-Encoding: base64\r\n";
$body .="X-Attachment-Id: ".rand(1000, 99999)."\r\n\r\n";
$body .= $encoded_content; // Attaching the encoded file with email
mail($to_email, $subject, $body, $headers);
you have to use the $_FILES tag to get the uploaded file instead of post tag
$_FILES["upload"]["tmp_name"]
below link help you on the same
https://www.w3schools.com/php/php_file_upload.asp
for sending the attachment you can use the PHPMailer
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
$email = new PHPMailer();
$email->SetFrom('you#example.com', 'Your Name'); //Name is optional
$email->Subject = $subject;
$email->Body = $msg;
$email->AddAddress( $mail_to );
$file_to_attach = $_FILES["upload"]["tmp_name"]
$email->AddAttachment( $file_to_attach , 'NameOfFile.pdf' );
return $email->Send();
Send attachments with PHP Mail()?

Json foreach loop is outputting the word object instead of its contents

I am attempting to send the foreach loop through json and then display with innerHTML. There aren't any errors. The issue I am having is that the output is display:
[object Object]
Instead of what is in the foreach loop.
How do I get the output to be the $html lines that are within the foreach loop?
try {
$sql_recentProjects = "
SELECT *
FROM project_gallery
ORDER BY date_added ASC
LIMIT 5
";
if ($recentProjects_stmt = $con->prepare($sql_recentProjects)) {
$recentProjects_stmt->execute();
$recentProjects_rows = $recentProjects_stmt->fetchAll(PDO::FETCH_ASSOC);
$recProj_arr = array();
foreach ($recentProjects_rows as $recentProjects_row) {
$precProjName = $recentProjects_row['p_name'];
$recProjImg = $recentProjects_row['p_img'];
//$project_img = substr($project_img, 2);
$displayRecProjImg = '<img src="/php'.$recProjImg.'" alt="'. $precProjAlt .'" class="projectDisplayImg">';
$html = '';
$html .= '<div class="recentProjectCont">';
$html .= '<div class="recentProjectImg">';
$html .= $displayRecProjImg;
$html .= '</div>';
$html .= '<div class="recProjInfoCont">';
$html .= '<div class="">';
$html .= $precProjName;
$html .= '</div>';
$html .= '</div>';
$html .= '</div>';
$recentProjData = array('html' => $html);
//$proj_arr[] = $data;
}
}
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
echo json_encode(['recentProjectData' => $recentProjData]);
JS
function ajaxCallCatalogs() {
$.ajax({
url: 'php/projects/projectGallerySelect.php',
datatype: 'json',
success: function (data) {
//console.log(data);
obj = JSON.parse(data);
recentProjectData = obj.recentProjectData; //Recent 5 Projects submitted to gallery
document.getElementById('recentProjectWrap').innerHTML = recentProjectData;
}
});
}
ajaxCallCatalogs();
setInterval(ajaxCallCatalogs, 150000);
(Read the comments of the OP to know why I posted this answer)
You have two options... the easiest way, but more restrictive method is this:
try {
$sql_recentProjects = "
SELECT *
FROM project_gallery
ORDER BY date_added ASC
LIMIT 5
";
if ($recentProjects_stmt = $con->prepare($sql_recentProjects)) {
$recentProjects_stmt->execute();
$recentProjects_rows = $recentProjects_stmt->fetchAll(PDO::FETCH_ASSOC);
$recProj_arr = array();
$html = ''; // MOVE THIS OUTSIDE THE LOOP
foreach ($recentProjects_rows as $recentProjects_row) {
$precProjName = $recentProjects_row['p_name'];
$recProjImg = $recentProjects_row['p_img'];
//$project_img = substr($project_img, 2);
$displayRecProjImg = '<img src="/php'.$recProjImg.'" alt="'. $precProjAlt .'" class="projectDisplayImg">';
$html .= '<div class="recentProjectCont">';
$html .= '<div class="recentProjectImg">';
$html .= $displayRecProjImg;
$html .= '</div>';
$html .= '<div class="recProjInfoCont">';
$html .= '<div class="">';
$html .= $precProjName;
$html .= '</div>';
$html .= '</div>';
$html .= '</div>';
//$proj_arr[] = $data;
}
// SET THIS AFTER YOU GET ALL ROWS INTO THE STRING
$recentProjData = array('html' => $html);
}
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
echo json_encode(['recentProjectData' => $recentProjData]);
Or, you can do this, which will truly separate the rows into more consumable data, but means you need to re-code your JS to output it proper (loop through the data via JS):
try {
$sql_recentProjects = "
SELECT *
FROM project_gallery
ORDER BY date_added ASC
LIMIT 5
";
if ($recentProjects_stmt = $con->prepare($sql_recentProjects)) {
$recentProjects_stmt->execute();
$recentProjects_rows = $recentProjects_stmt->fetchAll(PDO::FETCH_ASSOC);
$recProj_arr = array( 'html' => array() ); // SET UP THE ARRAY
foreach ($recentProjects_rows as $recentProjects_row) {
$precProjName = $recentProjects_row['p_name'];
$recProjImg = $recentProjects_row['p_img'];
//$project_img = substr($project_img, 2);
$displayRecProjImg = '<img src="/php'.$recProjImg.'" alt="'. $precProjAlt .'" class="projectDisplayImg">';
$html = '';
$html .= '<div class="recentProjectCont">';
$html .= '<div class="recentProjectImg">';
$html .= $displayRecProjImg;
$html .= '</div>';
$html .= '<div class="recProjInfoCont">';
$html .= '<div class="">';
$html .= $precProjName;
$html .= '</div>';
$html .= '</div>';
$html .= '</div>';
$recentProjData['html'][] = $html; //ADD TO THE ARRAY, INSTEAD OF OVERWRITING IT
//$proj_arr[] = $data;
}
}
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
echo json_encode(['recentProjectData' => $recentProjData]);

append php echo in javascript

This is image want to make selct2 function... thanks .append($(<?php echo $property_address1;?>)) this is my javascript code that i want to append.. this is select2 function actually i want multiple select2 onchange fucntion is required...
public function test($id = null)
{
$this->layout->set(
array(
'property_address1' => $this->mdl_quotes->property_address1()
)
);
$this->load->model('mdl_quotes');
$this->layout->buffer('content', 'quotes/test');
$this->layout->render();
}
My controller function
function property_address1()
{
$query = $this->db->query('SELECT host,price,city,property_thumbnail, apartments_type, contactnumber, contactperson,photographlinks,emailid, propertyaddress FROM tbl_contacts')->result();
$output = '<select id="neww" class="property_add_ form-control">';
foreach ($query as $row)
{
//echo $row->location;
$output .= "<option value='". $row->propertyaddress ."'";
$output .= " data-propertyaddress='" . $row->propertyaddress ."'" ;
$output .= " data-host_name='" . $row->host ."'" ;
$output .= " data-apartments_type ='" . $row->apartments_type."'" ;
$output .= " data-city ='" . $row->city."'" ;
$output .= " data-property_thumbnail='" . $row->property_thumbnail."'" ;
$output .= " data-price='" . $row->price."'" ;
$output .= " data-contactperson='" . $row->contactperson ."'" ;
// $output. = $row->pincode.", ".$row->city.", ".$row->location;
$output .= " data-photographlinks='" . $row->photographlinks ."'" ;
$output .= " data-emailid='" . $row->emailid ."'" ;
$output .= " data-contactnumber='". $row->contactnumber . "'>" ;
$output .= $row->host . ' , '.$row->propertyaddress . ' ,'.$row->price. ' ,'.$row->apartments_type. ' , '. $row->contactperson . ' , ' . $row->contactnumber. "</option>";
}
$output .= '</select>';
//var_dump($output);
return $output;
}

Jquery Clone select not working properly

In my code of wordPress I am trying to clone <select> box with its options it works but the problem is all of its option went outside ending select tag </select> I am not confirm whats wrong with it
Preview Image
HTML Output: https://jsfiddle.net/h5voq4nt/
PHP Code
$output .= '<label for="_jwppp-video-url-' . $number . '">';
$output .= '<strong>' . __( 'Media URL', 'jwppp' ) . '</strong>';
$output .= '<a class="question-mark" href="http://www.ilghera.com/support/topic/media-formats-supported/" title="More informations" target="_blank"><img class="question-mark" src="' . plugins_url('jw-player-7-for-wp-premium') . '/images/question-mark.png" /></a></th>';
$output .= '</label> ';
$output .= '<p>';
$output .= '<input type="text" id="_jwppp-video-url-' . $number . '" name="_jwppp-video-url-' . $number . '" style="margin-right:1rem;" placeholder="' . __('Video (YouTube or self-hosted), Audio or Playlist', 'jwppp') . '" ';
$output .= ($video_url != 1) ? 'value="' . esc_attr( $video_url ) . '" ' : 'value="" ';
$output .= 'size="60" />';
$output .= '<input type="text" name="_jwppp-' . $number . '-main-source-label" id ="_jwppp-' . $number . '-main-source-label" class="source-label-' . $number . '" style="margin-right:1rem;';
$output .= '" value="' . $main_source_label . '" placeholder="' . __('Label (HD, 720p, 360p)', 'jwppp') . '" size="30" />';
$output .= '<select style="margin-top: 0; margin-left: 0.8rem;" id="_jwppp-video-ad-' . $number . '" name="_jwppp-video-ad-' . $number . '" />';
$output .= '<option name="NoAds" value="NoAds"';
$output .= ($ads_client == 'NoAds') ? ' selected="selected"' : '';
$output .= '>No Ads</option>';
$output .= '<option name="AdCode1" value="AdCode1"';
$output .= ($ads_client == 'AdCode1') ? ' selected="selected"' : '';
$output .= '>Ad Code 1</option>';
$output .= '<option name="AdCode2" value="AdCode2"';
$output .= ($ads_client == 'AdCode2') ? ' selected="selected"' : '';
$output .= '>Ad Code 2</option>';
$output .= '<option name="AdCode3" value="AdCode3"';
$output .= ($ads_client == 'AdCode3') ? ' selected="selected"' : '';
$output .= '>Ad Code 3</option></select>';
JQuery Code
<script>
(function($) {
$(document).ready(function() {
var number = <?php echo $number; ?>;
var $url = $('#_jwppp-video-url-' + number).val();
var $ads = $('#_jwppp-video-ad-' + number).val();
var $ext = $url.split('.').pop();
var $arr = ['xml', 'feed', 'php', 'rss'];
//CHANGE PLAYLIST-HOW-TO
var tot = $('.jwppp-input-wrap:visible').length;
if(tot > 1) {
$('.playlist-how-to').show('slow');
var string = [];
$('.order:visible').each(function(i, el) {
string.push($(el).html());
})
$('.playlist-how-to code').html('[jw7-video n="' + string + '"]');
} else {
$('.playlist-how-to').hide();
}
$('.jwppp-more-options-' + number).hide();
if($.inArray($ext, $arr)>-1) {
$('.more-options-' + number).hide();
};
$('#_jwppp-video-url-' + number).on('change',function() {
var $url = $('#_jwppp-video-url-' + number).val();
var $ads = $('#_jwppp-video-ad-' + number).val();
var $ext = $url.split('.').pop();
var $arr = ['xml', 'feed', 'php', 'rss'];
if($.inArray($ext, $arr)>-1) {
$('.more-options-' + number).hide();
$('.jwppp-more-options-' + number).hide();
} else {
$('.more-options-' + number).show();
}
});
});
})(jQuery);
</script>
In PHP code has
$output .= '<select style="margin-top: 0; margin-left: 0.8rem;" id="_jwppp-video-ad-' . $number . '" name="_jwppp-video-ad-' . $number . '" />';
this has an end slash (/), please remove it.

setInterval: Why isn't it resetting?

Why doesn't this code work to turn off setInterval? I click an element to start it, and it begins fine (fading in and out a div #content on 5 second intervals). I click an element to stop it, and it just continues to fade in and out on the week=current, even though it loads the proper week initially.
It does not matter whether I separate the function from the jQuery encapsulation. Any help appreciated.
$out .= '<script type="text/javascript">'."\n";
$out .= '$(document).ready(function () {'."\n";
$out .= ' $("span.archives").click(function () {'."\n";
$out .= ' $("#content").load("update.php?week=" + this.id);'."\n";
$out .= ' if (this.id == \'current\') {'."\n";
$out .= ' StartStop(\'on\');'."\n";
$out .= ' } else {'."\n";
$out .= ' StartStop(\'off\');'."\n";
$out .= ' }'."\n";
$out .= ' });'."\n";
$out .= ' function StartStop(txt) {'."\n";
$out .= ' if (txt == \'on\') {'."\n";
$out .= ' var refresh = setInterval(function() {'."\n";
$out .= ' $("#content").fadeOut("slow", function() {'."\n";
$out .= ' $("#content").load("update.php?week=current", function() {'."\n";
$out .= ' $("#content").delay(250).fadeIn("slow");'."\n";
$out .= ' });'."\n";
$out .= ' });'."\n";
$out .= ' }, 5000);'."\n";
$out .= ' } else {'."\n";
$out .= ' clearInterval(refresh);'."\n";
$out .= ' }'."\n";
$out .= ' }'."\n";
$out .= '});'."\n";
$out .= '</script>'."\n";
refresh is defined locally within StartStop, its value isn't saved between calls to StartStop.
Try defining it outside of it, for example:
var refresh;
function StartStop(txt) {
refresh = setInterval(/* ... */);
}
Also, you may want to clear the previous refresh before creating a new one:
if (txt == 'on') {
if(refresh) clearInterval(refresh);
refresh = setInterval(/* ... */);
}

Categories

Resources