Convert a JavaScript variable to a PHP variable - javascript

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>`

Related

Get value from document.querySelector and insert into localhost database

I want to get the value from document.querySelector and save the data into the database via form with ajax and php, but the code I wrote did not run well / could not display the result, if there was an error in writing my code
<script>
//on the click of the submit button
$(document).ready(function () {
$("#submit").click(function () {
//get the form value
let no = document.querySelector('i[data-name="no"]').value;
let question = document.querySelector('i[data-name="question"]').value;
let countdown = document.querySelector('i[data-name="countdown"]').value;
let answer = document.querySelector('i[data-name="answer"]').value;
//make the postdata
var postData = 'no=' + no + '&question=' + question + '&countdown=' + countdown +
'&answer=' + answer;
if (no == '' || question == '' || countdown == '' || answer == '') {
alert("Please Fill All Fields");
} else {
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "post-answer.php",
data: postData,
cache: false,
success: function (result) {
alert(result);
}
});
}
return false;
});
});
</script>
this is the form I created
<form class="glass userform" method="post" data-ajax="false">
<i data-name='countdown'></i><i data-name='answer'></i>
<i data-name='no'></i>
<a href=""
style="float:right;font-size: 30px;width: 50px;margin-right:50px;margin-top:30px;display:
inline-block;"><i>Next</i></a>
<i data-name='question'></i>
<br>
<a href="#" onclick="checkboxtrue();"
style="width:100%;text-align: center;font-size: 30px;display: inline-block;"><i>Benar
</i></a><br>
<a href="#" onclick="checkboxfalse();"
style="width:100%;text-align: center;font-size: 30px;display: inline-block;"><i>Salah</i></a>
<br><br>
<input type="hidden" id="checkboxtotext" name="checkboxtotext" onkeyup="valueoftrueanswer()" />
<input id="submit" type="button" value="Submit">
</form>

LARAVEL: how to send Email data from view to controller

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

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",

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);
}
});
}
}

using ajax to get data from a database with php [duplicate]

every type i run this it calls the error: OnError function and i can't see why it doesn't call the success: OnSuccess,
JS:
$(document).ready(function () {
// retreving data on button click
$("#data-submit").click(LoadDataThroughAjaxCall);
//loading screen functionality - this part is additional - start
$("#divTable").ajaxStart(OnAjaxStart);
$("#divTable").ajaxError(OnAjaxError);
$("#divTable").ajaxSuccess(OnAjaxSuccess);
$("#divTable").ajaxStop(OnAjaxStop);
$("#divTable").ajaxComplete(OnAjaxComplete);
//loading screen functionality - this part is additional - end
});
// ajax call
function LoadDataThroughAjaxCall() {
$.ajax({
type: "POST",
url: "Ajax/dataloader.php",
data: '{}',
dataType: "json",
success: OnSuccess,
failure: OnFailure,
error: OnError
});
// this avoids page refresh on button click
return false;
}
// on sucess get the xml
function OnSuccess(response) {
//debugger;
var xmlDoc = $.parseXML(response.d);
var xml = $(xmlDoc);
var tweets = xml.find("Table");
showOnATable(tweets);
}
// show data on a table
function showOnATable(tweets) {
//debugger;
var headers = [];
var rows = [];
// header section
headers.push("<tr>");
headers.push("<td><b>tweets</b></td>");
headers.push("<td><b>created</b></td>");
headers.push("<td><b>source</b></td>");
headers.push("</tr>");
// rows section
$.each(tweets, function () {
var tweets = $(this);
rows.push("<tr>");
rows.push("<td>" + $(this).find("tweet_text").text() + "</td>");
rows.push("<td>" + $(this).find("created_at").text() + "</td>");
rows.push("<td>" + $(this).find("source").text() + "</td>");
rows.push("</tr>");
});
var top = "<table class='gridtable'>";
var bottom = "</table>";
var table = top + headers.join("") + rows.join("") + bottom;
$("#divTable").empty();
$("#divTable").html(table);
}
// loading screen functionality functions - this part is additional - start
function OnAjaxStart() {
//debugger;
//alert('Starting...');
$("#divLoading").css("display", "block");
}
function OnFailure(response) {
//debugger;
alert('Failure!!!' + '<br/>' + response.reponseText);
}
function OnError(response) {
//debugger;
var errorText = response.responseText;
alert('Error!!!' + '\n\n' + errorText);
}
function OnAjaxError() {
//debugger;
alert('Error!!!');
}
function OnAjaxSuccess() {
//debugger;
//alert('Sucess!!!');
$("#divLoading").css("display", "none");
}
function OnAjaxStop() {
//debugger;
//alert('Stop!!!');
$("#divLoading").css("display", "none");
}
function OnAjaxComplete() {
//debugger;
//alert('Completed!!!');
$("#divLoading").css("display", "none");
}
PHP:
<?php
//if(isset($_POST['data'])==true&&empty($_POST['data'])==false){
require_once('../connection.php');
function clean($str)
{
if(get_magic_quotes_gpc())
{
$str= stripslashes($str);
}
return str_replace("'", "''", $str);
}
//Sanitize the POST values
//$username = clean($_POST['data']);
//$result=sqlsrv_query($conn,"execute sp_ORDER_BY_name '$username'");
$result=sqlsrv_query($conn,"select tweet_text,source from tweets");
if($result) {
if(sqlsrv_has_rows($result) > 0) {
//Login Successful
while( $row = sqlsrv_fetch_array( $result, SQLSRV_FETCH_ASSOC) ) {
echo $row['tweet_text'].", ".$row['source']."<br />";
}
}else {
//Login failed
echo 'Name not found';
}
}
//}
?>
HTML FORM:
</head>
<body>
<div id="banner">
<h1>P-CAT version 0.1</h1>
</div>
<div id ="content">
<h2>Sreach Catigroies</h2>
<select id="data2">
<option value="">Plece select one of the follwing</option>
<option value="Name">Name</option>
<option value="Location">Location</option>
</select>
<input name="data" id="data" type="text" />
<input type="submit" id="data-submit" value="Grab">
<div id="divTable">
</div>
</div>
<div id="divLoading" style="display: none; position: absolute; top: 50%; left: 40%;
text-align: left;">
<span>
<img src="Images/ajax-loader.gif" alt="Image not found." /></span>
<br />
<span style="text-align: left; padding-left: 8px;">Loading ...</span>
</div>
<div id="navbar">
<input type="button" value="EDIT">
<input type="button" value="HISTORY">
<input type="button" value="SETTINGS">
<input type="button" value="SEARCH">
</div>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="js/global.js"></script>
</body>
You have to response a json from php like,
if(sqlsrv_has_rows($result) > 0) {
//Login Successful
$xml='<Table>';
while( $row = sqlsrv_fetch_array( $result, SQLSRV_FETCH_ASSOC) ) {
$xml.='<tweet_text>'.$row['tweet_text'].'</tweet_text>';
$xml.='<source>'.$row['source'].'</source>';
// create xml tag for created_at
}
$xml.='</Table>';
echo json_encode(array('d'=>$xml));
return TRUE;
} else {
//Login failed
echo json_encode(array('d'=>'Name not found'));
}

Categories

Resources