LARAVEL: how to send Email data from view to controller - javascript

I need to send email But Not getting email address in userController
from add.blade.php to userController#add.php
this is the code of add.blade.php file:
<div class="modal-content">
<div class="modal--blocks">
<div class="small--heading">
<form class="col s12">
<div class="input-field">
<div class="chips"></div>
</div>
<div class="input-field-btn">
<button class="btn waves-effect waves-light" type="button" id="send_email">Send Email</button>
</div>
</form>
</div>
</div>
</div>
and this is the scripte in add.blade.php file:
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="css/materialize/js/materialize.min.js"></script>
$(document).on('click', '#send_email', function(){
var testEmail = /^[A-Z0-9._%+-]+#([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
var instance = M.Chips.getInstance($('.chips'));
var email_address = instance.chipsData;
alert(instance);
alert(email_address);
// alert(email_address);
$.each(email_address, function(i, value){
if (!testEmail.test(value.tag)){
instance.deleteChip(i);
}
});
$("#send_email").text("processing..");
$("#send_email").prop('disabled', true);
var artist_id = "{{$artist->artist_id}}";
var request = $.ajax({
url: "{{url('/label/artist/weeklyreport/send')}}",
method: "POST",
data: { _token: $('meta[name="csrf-token"]').attr('content'), email:email_address, artist_uuid:artist_id}
});
request.done(function(resp) {
if (!resp.error) {
if (resp.result.status){
$("#modalEmailTemplates").modal('close');
$("#response_weekly_report").show();
}
}
});
});
userController.php file :
public function weeklyreportSend(Request $request) {
dd($request->email);die;
// $email = 'shiyalparesh25#gmail.';
$post = [];
$post['email'] = array_column($request->email, 'tag');
$post['subject'] = Config::get('constant.REPLAY_NAME') . "- Weekly Report";
$post['data'] = $this->get_weekly_report_data($request->artist_uuid);
$result = Helper::sendMail($post, "weekly_report");
return response()->json(['error' => false, 'result' => $result]);
}
Problem :- i'm not getting email value in Controller.if any have problem like me Please Help

Related

ajax dont send the variables, send undefined

I have code in html inputs and checkbox the javascript code collects the data of the inputs and in ajax must send the information does not reach the php where it receives it and puts it in session.
ajax send the array for the php file, but the array is empty and i dont know what happen, im sorry my english is very ugly :(
function addcarto() {
var quantity1 = document.getElementById("quiantitynice1").value;
var quantity2 = document.getElementById("quiantitynice2").value;
var quantity3 = document.getElementById("quiantitynice3").value;
var quantity4 = document.getElementById("quiantitynice4").value;
var quantity5 = document.getElementById("quiantitynice5").value;
var quantity6 = document.getElementById("quiantitynice6").value;
var quantity7 = document.getElementById("quiantitynice7").value;
var quantity8 = document.getElementById("quiantitynice8").value;
var quantity9 = document.getElementById("quiantitynice9").value;
var quantity10 = document.getElementById("quiantitynice10").value;
var quantity11 = document.getElementById("quiantitynice11").value;
var quantity12 = document.getElementById("quiantitynice12").value;
var quantity13 = document.getElementById("quiantitynice13").value;
var quantity14 = document.getElementById("quiantitynice14").value;
var quantity15 = document.getElementById("quiantitynice15").value;
var quantity16 = document.getElementById("quiantitynice16").value;
var quantity17 = document.getElementById("quiantitynice17").value;
var quantity18 = document.getElementById("quiantitynice18").value;
var quantity19 = document.getElementById("quiantitynice19").value;
var quantity20 = document.getElementById("quiantitynice20").value;
var quantity21 = document.getElementById("quiantitynice21").value;
var quantities = [quantity1, quantity2, quantity3, quantity4, quantity5, quantity6, quantity7, quantity8, quantity9, quantity10, quantity11, quantity12, quantity13, quantity14, quantity15, quantity16, quantity17, quantity18, quantity19, quantity20, quantity21];
$.ajax({
type: 'post',
url: 'php/addCart2.php',
data: 'cantidades=' + quantities,
//data: { 'cantidades': JSON.stringify(quantities)},
success: function (response) {
alert(response.status);
},
error: function () {
alert("error");
}
});
}
<div class="form-check">
<input class="form-check-input" name="ingrediente" type="checkbox" id="ing19" value="19">
<label class="form-check-label" for="ing19">CAMARON</label>
</div>
<div class="quiantitynice" id="quiantitynice19" style='position:relative;display:none'>
<input class="formgroup" type="number" name="quantity" id="quiantitynice19" min="1" value="" Style="width:45Px" placeholder="1">
</div>
<div class="row text-center">
<div class="col">
<button class="btn btn-lg btn-wy" name ="btnsubmin" type = "submit" onclick="addcarto('');">AGREGAR</button>
</div>
</div>
this is the code of the php file:
<?php
session_start();
if(!empty($_POST)) {
//si llega id y cantidad
$canti = $_POST['cantidades'];
$_SESSION["canti"] = $canti;
}
?>
use these code in your ajax:
contentType: 'application/json; charset=utf-8',
dataType: "JSON",

jQuery ajax keeps adding more and more elements

When a user searches for a username he gets results. When he backspaces or modifies the query, the results just keep getting added on top of the previous results instead of the results being modified and a fresh, updated result returned. I have modified the script here and there with no success yet.
My view:
<div class='container'>
<div class='row'>
<div class='col-sm-6 col-xs-12 col-centered'>
<div class='panel panel-default'>
<div class='panel-heading sticky'>
<div class='back pull-left'><a href='<?php echo site_url('chats') ?>'><span class='glyphicon glyphicon-chevron-left'></span></a></div>
<h1 class='panel-title text-center'>New Chat</h1>
<input class='form-control' id='search-field' type='text' placeholder='Username'>
</div>
<div class='panel-body'>
<ul class='users collapse'>
</ul>
</div>
</div>
</div><!--end column-->
</div><!--end row 1-->
</div><!--end container-->
My JS:
$(function() {
var $search_field = $('#search-field');
$search_field.on('keyup', searchByUsername);
$search_field.focus();
});
function searchByUsername(e) {
var username = this.value.trim();
var keyCode = e.keyCode;
var data = {username : username};
var $usersElement = $('.users');
var users = [];
// Use this condition to prevent searching when whitespace is entered
if (username) {
var request = $.ajax({
url : site_url + 'search/searchByUsername/',
method : 'GET',
data : data,
dataType : 'json'
});
request.done(function(jsonRepsonse) {
if (jsonRepsonse) {
var status = jsonRepsonse.status;
var usernames = jsonRepsonse.usernames;
if (status === 'success') {
$.each(usernames, function(index, value) {
// must be one line or will throw syntax error
users.push("<li class='user text-center'><a href='#'><span class='glyphicon glyphicon-user'></span><strong class='username'>" + value + "</strong></a></li>");
});console.log(users);
$usersElement
.append(users)
.show();
}
}
});
request.fail(function(xhr, status, error) {
console.log(error);
});
}
users.length = 0
$usersElement.hide();
}
My Codeigniter controller function:
public function searchByUsername()
{
$username = $this->input->get('username', true);
$usernames = [];
if (!empty($username)) {
$usernames = $this->find_users_model
->searchByUsername($username);
}
if (!empty($usernames)) {
$this->jsonResponse(
['status' => 'success',
'usernames' => $usernames]);
return;
}
$this->jsonResponse(
['status' => 'success',
'usernames' => ['User not found']]);
}
private function jsonResponse($response)
{
$this->output
->set_status_header(200)
->set_content_type('application/json', 'utf-8')
->set_output(json_encode($response));
}
Result:
This is your users container:
var $usersElement = $('.users');
On ajax response, you do:
$usersElement.append(users).show();
But you're always appending, never removing. Try emptying the element before populating it with users again:
$usersElement.empty().append(users).show();

AJAX call on a javascript function doesn't work

This is actually the first time I'm using ajax so honestly I don't know a single thing. Tried to read articles about ajax but no luck. What I'm trying to do here is quite simple really I just want to try to figure out how ajax works and what I should do to make it work. I wanted it so that when I try to click the login button and go to my php and display "login success" it works when the textboxes are empty it displays fields are empty but the ajax doesn't seem to work
Here is what I've done so far this is my index.php A.K.A login page
<!DOCTYPE html>
<html>
<head>
<title>O-Chat</title>
<link rel="stylesheet" type="text/css" href="index.css">
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="script101.js"></script>
</head>
<body>
<div class="content">
<div class="features">
<div><br><br><br><br><br><br><br><br><br><br>FEATURES HERE</div>
</div>
<div class="loginpart">
<div class="banner"><br><br><br>BANNER HERE</div>
<div class="login" id="divlogin">
<div class="login-header">Login</div>
<form name="loginform" class="login">
<input class="login" type="text" name="pUname" id="jUname" maxlength="35" placeholder="Username"/><br>
<input class="login" type="Password" name="pPass" id="jPass" maxlength="40" placeholder="Password"/><br>
<span class="error" id="jloginerror"></span>
<div class="button" id="login"" onclick="validate();">
</div>
</form>
<div class="login-footer" onclick="location.href='register.php'">Not yet a member?<br>Register Now! Click Here!</div>
</div>
</div>
</div>
<div class="footer">
<div class="footer-container">
Home |
About O-Chat |
Contact Us
<div style="float: right;">Copyright © 2000 - 2017 O-Chat Unlimited (071813-S) All Rights Reserved</div>
</div>
</div>
</body>
</html>
Here is my javascript file script101.js
function validate() {
var uname = $("#jUname").val();
var pass = $("#jPass").val();
var data = "&uname=" + uname + "&pass=" + pass;
if(!uname.match(/\S/) || !pass.match(/\S/)) {
document.getElementById("divlogin").style.height = '275px';
document.getElementById("jloginerror").innerHTML = "Some fields are empty!";
}
else
{
document.getElementById("jloginerror").innerHTML = "";
document.getElementById("divlogin").style.height = '250px';
$.ajax({
type: "post",
url: "login.php",
data: data,
sucess:function(data){
$("#jloginerror").text(data);
}
});
}
}
<?php
echo "very successful";
?>
Remove $ from the function declaration $function validate(). You can not use $ here.
You can use it like either
$(function(){
....
});
OR
if you wants to keep name of your function then just remove $ before the function, simply use it as:
function validate(){
....
}
and on ajax , you can use
$.ajax({
method: "post",
url: "login.php",
data: data;
sucess:function(data){
$("#jloginerror").text(data);
}
});
So your full code should be like as follows:
function validate() {
var uname = $("#jUname").val();
var pass = $("#jPass").val();
var data = "&uname=" + uname + "&pass=" + pass;
if(!uname.match(/\S/) || !pass.match(/\S/)) {
document.getElementById("divlogin").style.height = '275px';
document.getElementById("jloginerror").innerHTML = "Some fields are empty!";
}
else
{
document.getElementById("jloginerror").innerHTML = "";
$.ajax({
type: "post",
url: "login.php",
data: data,
sucess:function(data){
$("#jloginerror").text(data);
}
});
}
}
Remove $ from the function keyword and Jquery works with element id or name var uname = $("#jUname").val(); var pass = $("#jPass").val(); and do not use ; for separating and you should use , $.ajax({}), use $.ajax({}) instead of ajax({}) because its Jquery function not javascript function.
function validate() {
var uname = $("#jUname").val();
var pass = $("#jPass").val();
var data = "&uname=" + uname + "&pass=" + pass;
if(!uname.match(/\S/) || !pass.match(/\S/)) {
document.getElementById("divlogin").style.height = '275px';
document.getElementById("jloginerror").innerHTML = "Some fields are empty!";
}
else
{
document.getElementById("jloginerror").innerHTML = "";
$.ajax({
type: "post",
url: "login.php",
data: data,
sucess:function(data){
$("#jloginerror").text(data);
}
});
}
}

Convert a JavaScript variable to a PHP variable

I'm learning HTML JS CSS and PHP and I have a big problem.
The $input variable in getPosForLieferschein() should be the user input, but I found no way to convert JS variables to PHP. The user should write a contract number into the input field and the contract positions - getPosForLieferschein() - show up in the table below. The page should not be reloaded just in case that no other way works. I know the code is terrible!
Head:
<?php include 'connection_manager.php'; $tags = getLieferscheine();?>
<script type="text/javascript">
var availableTags = "<?php echo $tags;?>"
$(function () {
var values = availableTags.split(",");
$('.select').autocomplete({
source: values
});
});
function generate() {
var eingabe = document.getElementById('input').value;
var position = "<?php $positionen = getPosForLieferschein($input); echo $positionen; ?>";
var arr = position.split(','), contract = arr[0], pos = arr[1], article = arr[2], name = arr[3], amount = arr[4], unit = arr[5];
var table = document.getElementById("table1body");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(2);
var cell5 = row.insertCell(2);
var cell6 = row.insertCell(2);
var i = 60;
var a = document.getElementById("input");
if ((a.value == eingabe)) {
while (i > 0) {
cell1.innerHTML = contract;
cell2.innerHTML = pos;
cell3.innerHTML = unit;
cell4.innerHTML = amount;
cell5.innerHTML = name;
cell6.innerHTML = article;
i = i - 60;
}
}
else {
swal({
title: "Fehler!",
text: "Bitte geben Sie eine gültige Auftragsnummer ein!",
type: "error",
confirmButtonText: "Ok",
confirmButtonColor: "#FF0000"
});
}
};
$(document).ready(function () {
$("#details").click(function () {
$("#uebertragen").removeAttr("disabled");
$("#details").attr("disabled", "disabled");
})
$("#uebertragen").click(function () {
$("#details").removeAttr("disabled");
$("#uebertragen").attr("disabled", "disabled");
})
})
$(document).ready(function () {
$("#uebertragen").click(function () {
$("td").remove()
})
})
</script>
Body:
<body>
<center>
<img style="position:relative;left:25px;" src="quehenberger.jpg" height="50px" width="240px" alt="quehenberger logo" align="left"/>
<img style="position:relative;right:25px;" src="bilton.png" height="50px" width="300px" alt="bilton logo" align="right"/>
<h1><b>QLog Eingabe</b></h1>
<hr/>
<div class="container">
<div class="row">
<form action="" method="get">
<input id="input" type="text" style="width:50%;position:relative;left:14em;" value="" class="select form-control col-xs-1" Placeholder="Auftragsnummer"/>
<button style="position:relative;left:18em;" id="details" class="col-xs-1 btn btn-success" onclick="generate();">Prüfen</button>
</form>
</div>
</p>
<button style="width:100px;position:relative;left:58.65em;" id="uebertragen" disabled="disabled" class="col-xs-1 btn btn-danger">Übertragen</button>
</div>
<table class="table">
<thead>
<tr>
<th>Auftragsnummer</th>
<th>Positions Nummer</th>
<th>Artikel Nummer</th>
<th>Artikel Bezeichnung</th>
<th>Artikel Menge</th>
<th>Einheit</th>
</tr>
</thead>
<tbody id="table1body">
</tbody>
</table>
</center>
</body>
</html>
You cannot just convert the variable. It is not possible. There are other options to make changes to the page without reloading:
You can make an ajax request each time the user input field has its content changed. Do all the calculations you need to do in the controller (server side) and just return the result and display it in the same page.
If you would use Yii2 framework, there would be another option. But this would require you to make some changes to the structure of your functions. In Yii2 you can write your JS in the view file and use values of PHP varibles. There is some info about that function here.
As I understand, you are not using any framework, so I would suggest to use ajax requests and pass the calculated values back to the page (option 1).
This is the final code! Thanks for help guys! :D`
<script type="text/javascript">
var availableTags = "<?php echo $tags;?>"
var currentTag = false;
$(function(){
var values = availableTags.split(",");
$('.select').autocomplete({
source: values,
select: function( event, ui ) {
//$('#input').val()
//console.log(ui.item.value);
getAuftrag(ui.item.value);
}
});
});
function sendAuftrag() {
if (currentTag !== false) {
$.ajax({
method: "GET",
url: "save.php",
data: {
q : currentTag
},
dataType: "html",
success: function(data) {
$("#tableBody").html("");
$("#uebertragen").attr("disabled", "disabled");
swal({title: "Erfolg!",
text: "Auftragsnummer " + currentTag + " erfolgreich übermittelt!",
type: "success",
confirmButtonText: "Ok",
confirmButtonColor: "#FF0000"
});
currentTag = false;
}
});
}
}
function getAuftrag(str) {
if (str == "") {
document.getElementById("tableBody").innerHTML = "";
currentTag = false;
return;
}
var values = availableTags.split(",");
if (values.indexOf(str) === -1) {
currentTag = false;
swal({title: "Fehler!",
text: "Bitte geben Sie eine gültige Auftragsnummer ein!",
type: "error",
confirmButtonText: "Ok",
confirmButtonColor: "#FF0000"
});
} else {
$.ajax({
method: "GET",
url: "ajax.php",
data: {
q : str
},
dataType: "html",
beforeSend: function(jqxhr) {
currentTag = str;
},
success: function(data) {
$("#tableBody").html(data);
$("#uebertragen").removeAttr("disabled");
// console.log(data);
}
});
}
}
$(document).ready(function(){
$("#uebertragen").click(function(){
$("#uebertragen").attr("disabled", "disabled");
})
})
</script>`
HTML:
`<body>
<center>
<img style="position:relative;left:25px;" src="quehenberger.jpg" height="50px" width="240px" alt="quehenberger logo" align="left"/>
<img style="position:relative;right:25px;" src="bilton.png" height="50px" width="300px" alt="bilton logo" align="right"/>
<h1><b>QLog Eingabe</b></h1>
<hr/>
<div class="container">
<div class="row">
<input id="input" style="width:50%;position:relative;left:14em;" class="select form-control col-xs-1" Placeholder="Auftragsnummer"/>
<!-- <button style="position:relative;left:18em;" id="details" class="col-xs-1 btn btn-success" >Prüfen</button> -->
<button style="width:100px;position:relative;left:18em;" id="uebertragen" disabled="disabled" class="col-xs-1 btn btn-danger">Übertragen</button>
</div>
</div>
<div id="tableBody"><b></b></div>
<div style="background-color: #E6E6E6;height:40px;width:100%;" data-role="footer" data-tap-toggle="false" class="ics-footer">
<p>Copyright IcoSense GmbH. All rights reserved.</p>
</div>
</center>
</body>
</html>`

PHP SQL / Ajax retrievement issues

I have a web application where I get the data from a mysql database and put it in the website with the help of handlebars templating.
First of all, the PHP i use looks something like this:
<?php
function isXHR() {
return isset( $_SERVER['HTTP_X_REQUESTED_WITH'] );
}
function connect(){
global $pdo;
$pdo = new PDO("mysql:host=localhost;dbname=personal", "user", "password");
}
function get_blog_posts( ) {
global $pdo;
$stmt = $pdo->prepare('
SELECT url, title, location, date, author, content, thmb
FROM photolog
LIMIT 50');
$stmt->execute();
return $stmt->fetchAll( PDO::FETCH_OBJ );
}
Then i use a javascript function that I call inside the document.ready(...) that looks like:
function loadBlogPosts(){
var photos = {
init: function( config ) {
this.config = config;
this.setupTemplates();
this.fetchphotos();
this.helpers();
$.ajaxSetup({
url: 'index.php',
type: 'POST'
});
},
setupTemplates: function() {
this.config.photoListTemplate = Handlebars.compile( this.config.photoListTemplate);
},
helpers: function(){
Handlebars.registerHelper("foreach",function(arr,options) {
if(options.inverse && !arr.length)
return options.inverse(this);
return arr.map(function(item,index) {
item.$index = index;
item.$first = index === 0;
item.$last = index === arr.length-1;
item.$rest = index >= 1;
return options.fn(item);
}).join('');
});
},
fetchphotos: function() {
var self = photos;
$.ajax({
dataType: 'json',
success: function(results) {
self.config.photosList.empty();
for(i=0;i<results.length;i++){
results[i].author = results[i].author.toLowerCase();
results[i].title = results[i].title.toUpperCase();
results[i].location = results[i].location.toUpperCase();
}
if ( results[0] ) {
self.config.photosList.append( self.config.photoListTemplate( results.reverse() ) );
} else {
self.config.photosList.append('<li>Nothing returned.</li>');
}
}
});
}
};
photos.init({
photoListTemplate: $('#photo_blog_template').html(),
photosList: $('div#blog_list')
});
}
And then put the data into the template:
<div id="blog_list">
<script id="photo_blog_template" type="text/x-handlebars-template">
{{#foreach this}}
{{#if $first}}
<div class="4u">
<div class="photo">
<a id="single_image" href="{{url}}"><img src="{{thmb}}" alt=""/></a>
</div>
</div>
<div class="8u post">
<header>
<h2>{{title}}</h2>
<h3>{{location}}</h3>
<div class="antet">
<div class="author">{{author}}</div>
<div class="date">{{date}}</div>
</div>
</header>
<p>{{content}}</p>
</div>
{{/if}}
{{#if $rest}}
<div class="3u post-small">
<div class="photo">
<a id="single_image" href="{{url}}"><img src="{{thmb}}" alt=""/></a>
</div>
<header>
<h2>{{title}}</h2>
<h3>{{location}}</h3>
<div class="antet">
<div class="author-small">{{author}}</div>
<div class="date-small">{{date}}</div>
</div>
</header>
<p>{{content}}</p>
</div>
{{/if}}
{{/foreach}}
</script>
</div>
The problem appears on the new android browsers, and after I close the application/page and open it with ctrl+shift+T. It doesn't show the page, it just shows the json file. The page is at stefanperju.com

Categories

Resources