PHP variable calculation - javascript

I am quite a beginner in PHP and have created a calculator and I am posting the calculation as a variable(q) to a php file and want to make the calculation and echo it back to the box as the result.
Going through the php function library I could not locate a function the can help me with that like 'eval' in JavaScript.
The reason I am not using 'eval' is that the calculation must happen on the server side.
Any help will be greatly appreciated.
JAVASCRIPT
$('.equal').click(function(){
$.post('calculator.php',{q: $('.result').val()} ,function(a){
$('.result').val(a).show();
});
});
PHP
<?php
$_POST[q];
?>
HTML
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>calculator</title>
<link rel='stylesheet prefetch' href='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css'>
<link rel='stylesheet prefetch' href='https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css'>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="container col-sm-2 text-center" id="calc">
<div class="row">
<form name="calc">
<input type="text" class="screen text-right result" name="result" placeholder="0" readonly>
</form>
</div>
<!-- First row -->
<div class = "row">
<button class="btn btn-primary number" data-key="1" type="button">1</button>
<button class="btn btn-primary number" data-key="2" type="button">2</button>
<button class="btn btn-primary number" data-key="3" type="button">3</button>
<button class="btn btn-danger" data-key="reset" type="button">C</button>
</div>
<!-- Second row -->
<div class = "row">
<button class="btn btn-primary number" data-key="4" type="button">4</button>
<button class="btn btn-primary number" data-key="5" type="button">5</button>
<button class="btn btn-primary number" data-key="6" type="button">6</button>
<button class="btn btn-warning number" data-key="+" type="button">+</button>
</div>
<!-- Third row -->
<div class = "row">
<button class="btn btn-primary number" data-key="7" type="button">7</button>
<button class="btn btn-primary number" data-key="8" type="button">8</button>
<button class="btn btn-primary number" data-key="9" type="button">9</button>
<button class="btn btn-warning number" data-key="-" type="button">-</button>
</div>
<!-- Fourth row-->
<div class = "row">
<button class="btn btn-primary number" data-key="0" type="button">0</button>
<button class="btn btn-primary number" data-key="." type="button">.</button>
<button class="btn btn-warning number" data-key="/" type="button">/</button>
<button class="btn btn-warning number" data-key="*" type="button">*</button>
</div>
<div class="row">
<button class="btn btn-success btn-lg equal" type="button">=</button>
</div>
</div>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js'></script>
<script src="js/calculator.js"></script>
<!-- jquery fade in function -->
<script>
$( "#calc" ).hide( 500 ).delay( 1500 ).show( 300 );
</script>
</body>
</html>

You can find a list of related PHP functions here:http://www.w3schools.com/php/php_ref_math.asp
Callback functions might be helpful, here is some documentation:http://php.net/manual/en/language.types.callable.php
An example of a callback function:
<?php
// Just an example, two numbers passed with GET
// $calc_choice will be add, subtract, etc.
$num_one = $_GET['number_one']);
$num_two = $_GET['number_two']);
$calc_choice = $_GET['calculation'];
// passing these variables into a callback function
customEval($num_one, $num_two, $calc_choice);
// This is abstraction
// $callback is going to be a function we pass
// You can name $numOne and $numTwo anything you would like
function customEval($numOne, $numTwo, $callback){
$answer = $callback($numOne, $numTwo);
echo '$answer';
}
//This will add two numbers together and return them
//What gets returns is what will be echoed in our callback function
function add($numOne, $numTwo){
return $numOne + $numTwo;
}
// You can make as many as you like
function subtract($numOne, $numTwo){
return $numOne - $numTwo;
}
?>
In use:
$num_one = 5;
$num_two = 10;
$calc_choice = "add";
// our function would be doing this behind the scene
customEval(5, 10, "add"){
// Because our add function returns 15 in this case
echo '15'
}

Related

Page refresh after click on register in jquery ajax php

page refreshes after data submitted.
register.php
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<div class="container">
<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Register Now</button>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title bg-primary text-center">Register</h4>
</div>
<div class="modal-body" id="away">
<form method="post" name="form" id="login" align="center">
Email:<input type="email" name="email" id="email" placeholder="email" autocomplete="off" required/> <br/> <br/>
Password:<input type="password" name="password" id="password" placeholder="password" required> <br/> <br/>
<input type="submit" id="register" name="register" value="Create Account" class="btn btn-info save" />
<a class="btn btn-info" href="login.php" > Login </a>
</form>
</div>
<div class="modal-footer">
<button class="btn btn-danger" type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function(){
$('#register').on('click',function(){
var email = $('#email').val();
var password = $('#password').val();
$.ajax({
method:"POST",
url:"registeruser.php",
data:{ email:email, password:password},
});
});
});
</script>
registeruser.php
<?php
include('db.php');
if(isset($_POST['email']) && isset($_POST['password']) )
{
$email = $_POST['email'];
$password = $_POST['password'];
$query = "insert into newtable (email,password) values ('$email','$password')";
$result = mysqli_query($conn,$query);
}
?>
The problem is that, my data is submitted successfully, but i used ajax jquery. my data is submitted and page also refreshes. i don't want my page to refresh.
please help to find my mistake.
i also used event.preventDefault() function to stop refresh. but it also did not work. it stops full functionality to save data.
The simplest approach is probably to make the button no longer be a "submit" button:
<input type="button" id="register" name="register" value="Create Account" class="btn btn-info save" />
or:
<button type="button" id="register" class="btn btn-info save">Create Account</button>
Additionally, if you don't want to post a <form> and aren't otherwise using that <form>, you can simply remove that element entirely:
<div class="modal-body" id="away">
Email:<input type="email" name="email" id="email" placeholder="email" autocomplete="off" required/> <br/> <br/>
Password:<input type="password" name="password" id="password" placeholder="password" required> <br/> <br/>
<input type="submit" id="register" name="register" value="Create Account" class="btn btn-info save" />
<a class="btn btn-info" href="login.php" > Login </a>
</div>
That way there'd be nothing to accidentally be submitted in the first place.

Detect button click on form item

I have a list of store items. Each item is showing its values as a form.
<?php
if($statement->execute())
{
$result = $statement->fetchAll();
$output = '';
foreach($result as $row)
{
$output .= '
<div class="col-md-3" style="margin-top:12px;">
<div class="item-content" align="center">
<div class="img-container">
<img src="../administrar/application/admin/productos/'.$row["image"].'" class="img-responsive" /><br />
<h4 class="text-info">'.$row["name"].'</h4>
<h4 class="text-danger">$ '.$row["price"] .'</h4>
<input type="text" name="quantity" id="quantity' . $row["id"] .'" class="form-control" value="1" style="text-align:right;"/>
<input type="hidden" name="hidden_name" id="name'.$row["id"].'" value="'.$row["name"].'" />
<input type="hidden" name="hidden_price" id="price'.$row["id"].'" value="'.$row["price"].'" />
<div class="input-group">
<span class="input-group-btn">
<button type="button" class="btn btn-danger btn-number" name="restar" id="'.$row["id"].'" " >
<span class="glyphicon glyphicon-minus"></span>
</button>
</span>
<span class="input-group-btn">
<button type="button" class="btn btn-success btn-number" name="sumar" id="sumar"">
<span class="glyphicon glyphicon-plus"></span>
</button>
</span>
</div>
<input type="button" name="add_to_cart" id="'.$row["id"].'" style="margin-top:5px;" class="btn btn-success form-control add_to_cart" value="Add to Cart" />
</div>
</div>
</div>
';
}
}
?>
I need to identify when the user clicks on button 'restar' from a certain form item.
This is my current script, but it doesn't launch the expected alert.
<script type="text/javascript">
$(document).ready(function(){
var product_id = $(this).attr("id");
$('#restar'+'product_id+').on('click', function(event) {
alert("ssssspp2");
});
});
</script>
Use class for describing similar objects, e.g.:
$('.js-some-btn').click(function() {
console.log("I'm button");
console.log("My id is " + $(this).attr('id'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="btn btn-success btn-number js-some-btn" name="sumar1" id="id1">btn 1</button>
<button type="button" class="btn btn-success btn-number js-some-btn" name="sumar2" id="id2">btn 2</button>
This approach allows you to write only one click handler for all buttons with provided class.

When i click edit button all the buttons are getting clicked with same username

I'm making a app in which there is option for a user to add a comment and also to delete and modify it but when i click edit button , every button gets called and a edit block shows for every comment created by that user.
I'm running js on backend in node js,mongodb and express js as framework
...HTML
<div class='card-body'>
<%campground.comments.forEach(comment=>{ %>
<div class='row'>
<div class='col-md-12'>
<strong><%=comment.author.username%></strong>
<span class='float-right'>10 days ago</span>
<p ><%=comment.text %></p>
<%if(currentUser){ if(currentUser.username==comment.author.username) { %>
<form class='cmtForm py-3' action='/campgrounds/<%=campground._id%>/comments/<%=comment.author.username%>/<%=comment._id%>?_method=PUT' method='POST'>
<textarea class="form-control" rows="3" name='updateComment'><%=comment.text%></textarea>
<button class=' btn btn-success btn-sm m-3 float-right'>
Update
</button>
</form>
<button class='editBtn sel btn btn-secondary btn-sm float-right' id='<%=comment._id %>' >Edit</button>
<form action='/campgrounds/<%=campground._id%>/comments/<%=comment._id%>?_method=DELETE' method='POST'>
<button class='btn btn-danger btn-sm mr-2 float-right ' >Delete</button>
</form>
</div>
<%}}%>
</div>
</div>
<% }); %>
</div>
//..JS//
$('.cmtForm').css('display','none');
let status=true;
$('.editBtn').on('click',(event)=>{
if(status){
$('.sel').text('cancel');
$('.cmtForm').css('display','block');
// $('.cmtForm').addClass('cmtForm form-control show');
}
else{
$('.sel').text('edit');
$('.cmtForm').css('display','none');
// $('.cmtForm').removeClass('cmtForm form-control hide');
}status=!status;
});
//Edit button should unhide particular comment section
As I mentioned in the comment to the original post, you have the same class for all buttons where the action is performed and also the same class of elements you are changing on the click event. This is the reason when click action is performed all the comments etc. are changing.
Since every set of elements (comment, edit button, etc.) are enclosed within a div you may use siblings() function to select the specific elements for changing stuff.
Here is the demonstration with two rows having similar elements:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
console.log("ready");
$(".b").click(function () {
$(this).siblings('.h').text("hello");
});
});
</script>
<div>
<label class="h">first</label>
<button class="b">Edit</button>
</div>
<div>
<label class="h">second</label>
<button class="b">Edit</button>
</div>
The key part is:
// same button element
$(event.target).text('cancel');
// sibling
$(event.target).siblings('.cmtForm').css('display', 'block');
Your JS code after modification will look like the following. I removed dynamic elements to make it executable.
<div class='card-body'>
<div class='row'>
<div class='col-md-12'>
<strong>User 1</strong>
<span class='float-right'>10 days ago</span>
<p>Comment 1</p>
<form class='cmtForm py-3'
action='/campgrounds/<%=campground._id%>/comments/<%=comment.author.username%>/<%=comment._id%>?_method=PUT'
method='POST'>
<textarea class="form-control" rows="3" name='updateComment'>Comment 1</textarea>
<button class=' btn btn-success btn-sm m-3 float-right'>Update</button>
</form>
<button class='editBtn sel btn btn-secondary btn-sm float-right' id='<%=comment._id %>'>Edit</button>
<form action='/campgrounds/<%=campground._id%>/comments/<%=comment._id%>?_method=DELETE' method='POST'>
<button class='btn btn-danger btn-sm mr-2 float-right '>Delete</button>
</form>
</div>
</div>
<div class='row'>
<div class='col-md-12'>
<strong>User 2</strong>
<span class='float-right'>10 days ago</span>
<p>Comment 2</p>
<form class='cmtForm py-3'
action='/campgrounds/<%=campground._id%>/comments/<%=comment.author.username%>/<%=comment._id%>?_method=PUT'
method='POST'>
<textarea class="form-control" rows="3" name='updateComment'>Comment 2</textarea>
<button class=' btn btn-success btn-sm m-3 float-right'>Update</button>
</form>
<button class='editBtn sel btn btn-secondary btn-sm float-right' id='<%=comment._id %>'>Edit</button>
<form action='/campgrounds/<%=campground._id%>/comments/<%=comment._id%>?_method=DELETE' method='POST'>
<button class='btn btn-danger btn-sm mr-2 float-right '>Delete</button>
</form>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$('.cmtForm').css('display', 'none');
let status = true;
$('.editBtn').on('click', (event) => {
if (status) {
$(event.target).text('Cancel');
$(event.target).siblings('.cmtForm').css('display', 'block');
// $(this).siblings('.cmtForm').addClass('cmtForm form-control show');
}
else {
$(event.target).text('Edit');
$(event.target).siblings('.cmtForm').css('display', 'none');
// $(this).siblings('.cmtForm').removeClass('cmtForm form-control hide');
}
status = !status;
});
</script>
Note: In your code, you are using a global variable status to control hide/display comment and changing button label. All rows (items) use the same status so you'll have an issue. Instead, you need to maintain status for every row (item).

How to keep selected the button on click of another button on same page using bootstrap?

On click of one of blue buttons(only one can be selected at a time) it is selected. But when I click on Buy button the previous blue button gets unselected. Therefore, I cannot read the value of blue button by onclick of yellow button.
Fiddle here.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Sign in Success</title>
</head>
<body>
<div class="btn-group" style="background:black;width:100%">
<button type="button" class="btn btn-default">Tr</button>
<div style="width:10px"></div>
<button type="button" class="btn btn-default">T</button>
<div style="width:10px"></div>
<button type="button" class="btn btn-default">Vt</button>
<div style="width:10px"></div>
<button type="button" class="btn btn-default">Rt</button>
</div>
<br> <br>
<h2 style="text-decoration:underline;" align="center">T</h2>
<div align="center"><!-- id="centerit" -->
<br> <br> <br>
<!-- <div style="width:50px"></div> -->
<button type="button" class="btn btn-primary cust" value="bu">Butter</button>
<button type="button" class="btn btn-primary cust" value="mi">Milk</button>
<button type="button" class="btn btn-primary cust" value="bi">Biscuit</button>
<br> <br>
<button type="button" class="btn btn-warning" value = "submit">Buy!</button>
</div>
</body>
</html>
I expect the blue button to remain selected when i click on buy button which is not happening now.
You can put your buttons in a form and replace the three blue buttons with radio buttons. See the documentation here:
https://getbootstrap.com/docs/4.0/components/buttons/#checkbox-and-radio-buttons
Updated fiddle: https://jsfiddle.net/0wj1m8ce/
<div class="btn-group btn-group-toggle" data-toggle="buttons" >
<label class="btn btn-primary cust">
<input type="radio" name="options" id="option1" autocomplete="off" value="bu"> Butter
</label>
<label class="btn btn-primary cust">
<input type="radio" name="options" id="option2" autocomplete="off" value="mi"> Milk
</label>
<label class="btn btn-primary cust">
<input type="radio" name="options" id="option3" autocomplete="off" value="bi" > Biscuit
</label>
</div>
Try adding radio buttons instead of buttons
That is what you required
<div id="radioBtn" class="btn-group">
<a class="btn btn-primary btn-sm active" data-toggle="fun" data-title="bu">Butter</a>
<a class="btn btn-primary btn-sm notActive" data-toggle="fun" data-title="mi">Milk</a>
<a class="btn btn-primary btn-sm notActive" data-toggle="fun" data-title="bi">Biscuit</a>
</div>
<script>
$('#radioBtn a').on('click', function(){
var sel = $(this).data('title');
var tog = $(this).data('toggle');
$('#'+tog).prop('value', sel);
$('a[data-toggle="'+tog+'"]').not('[data-title="'+sel+'"]').removeClass('active').addClass('notActive');
$('a[data-toggle="'+tog+'"][data-title="'+sel+'"]').removeClass('notActive').addClass('active');
})
</script>
<style>
#radioBtn .notActive{
color: #3276b1;
background-color: #fff;
}
</style>
Here is an updated JSFiddle

Laravel send data to mysql using ajax

I am stuck with creating a function in ajax that would take a value from variable "code2" and send it to controller which would send it to database. Problem I am getting all the time is :
Is This Really Working? Oh by the way: newLat: code2
So it kind of works however instead of newLat: code2 it should be newLat: (html code defined in variable code2) So how can I fix this?
JS:
$(function() {
$('.content-link').click(function(e) {
e.preventDefault();
$('#content-link2').load($(this).attr("href"), function() {
$('#content').draggable({
containment: "#content-link2",
scroll: false
});
});
});
return false;
});
var code2 = "";
document.getElementById("content-link2").onmousedown = function() {
mousedown();
};
document.getElementById("content-link2").onmouseup = function() {
mouseup();
};
function mousedown() {
code2 = document.getElementById("content-link2").innerHTML;
console.log(code2);
}
function mouseup() {
code2 = document.getElementById("content-link2").innerHTML;
console.log(code2);
}
AJAX:
function updateDatabase(newCode)
{
code2 = document.getElementById("content-link2").innerHTML;
console.log(code2);
// make an ajax request to a PHP file
// on our site that will update the database
// pass in our lat/lng as parameters
$.post('http://localhost/template', {
_token: $('meta[name=csrf-token]').attr('content'),
newCode: ("code2"),
})
.done(function(code2) {
alert(code2);
})
.fail(function() {
alert("error");
});
}
Route:
Route::group(['middleware' => ['web']], function () {
Route::get('home', 'BuilderController#homepage');
Route::get('template', 'BuilderController#templates');
Route::post('template', 'BuilderController#postDB');
Route::get('logout', 'BuilderController#getLogout');
});
Controller:
class BuilderController extends Controller
{
function templates()
{
$templates = Template::all();
return view('layouts/template', ['templates' => $templates]);
$id = $templates->id;
}
function homepage()
{
return view('layouts/home');
}
public function getlogout()
{
\Auth::logout();
return redirect('/home');
}
public function postDB(Request $request) {
$newLat = $request->input('newCode');
return "Is This Really Working? Oh by the way: newLat: $newLat";
return redirect('layouts/template', ['templates' => $templates]);
}
}
Blade:
#extends('layouts.master') #section('title', 'Website Builder') #section('content')
<div class="container template_class ">
#foreach ($templates as $template)
<a class="content-link" href="{{ asset($template->file )}}">
<img src="{{ asset($template->image )}}"/>
</a> #endforeach
</div>
<div class="features form-group">
<input class="filestyle form-control margin images" data-input="false" type="file" data-buttonText="Upload Logo" data-size="sm" data-badge="false" onchange="readURL(this);" />
<button onClick=" updateDatabase(this);"</button>
<script>
$( function() {
$( document ).tooltip();
} );
</script>
<button style="display: none" class="form-control margin btn btn-primary" id="showColor">Show Colors</button>
<button style="display: none" class="form-control margin btn btn-primary" id="hideColor">Hide Colors</button>
<input title="Choose a color and then click on any box" style="display: none" class="btn btn-default form-control margin" type="color" id="colorChoice">
<a style="display: none" href="#" class="btn btn-default form-control margin" id="cp4">Background</a>
<button style="display: none" onclick="$('#fonts1').bfhfonts({font: 'Arial'})" id="fontsShow" class="btn btn-primary form-control margin">Load Fonts</button>
<button style="display: none" class="btn btn-primary form-control margin" id="fontsHide">Hide Fonts</button>
<select title="Choose a font and then click on any box" style="display: none" id="fonts1" class="form-control margin"></select>
<button style="display: none" onclick="$('#googlefonts1').bfhgooglefonts({font: 'Lato'})" id="googleShow" class="btn btn-primary form-control margin">Google fonts</button>
<button style="display: none" class="btn btn-primary form-control margin" id="googleHide">Hide Google</button>
<select title="Choose a font and then click on any box" style="display: none" id="googlefonts1" class="form-control margin"></select>
<button style="display: none" onclick="$('#fontsizes1').bfhfontsizes({fontsize: '12'})" id="sizeShow" class="btn btn-primary form-control margin">Load font size</button>
<button style="display: none" class="btn btn-primary form-control margin" id="sizeHide">Hide font size</button>
<select title="Choose a font size and then click on any box" style="display: none" id="fontsizes1" class="form-control margin"></select>
<button style="display: none" class="form-control margin btn btn-default" id="finishEdit">Done</button>
<button class="form-control margin btn btn-default" id="startEdit">Edit</button>
<button type="button" class="form-control margin btn btn-warning" id="getRequest">Save</button>
</div>
<div id="content-link2"></div>
</body>
<link href="{{asset('css/bootstrap-colorpicker.min.css')}}" rel="stylesheet" type="text/css">
<link href="{{asset('css/bootstrap-formhelpers.min.css')}}" rel="stylesheet" type="text/css">
<link href="{{asset ('//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css')}}" rel="stylesheet" type="text/css">
<script type="text/javascript" src="{!! asset('js/bootstrap-colorpicker.min.js') !!}">
</script>
<script type="text/javascript" src="{!! asset('js/bootstrap-formhelpers.js') !!}">
</script>
<script type="text/javascript" src="{!! asset('js/template.js') !!}"></script>
<script type="text/javascript" src="{!! asset('js/bootstrap-filestyle.min.js') !!}">
</script>
</html>
#endsection
Check /path/to/project/root/storage/logs/laravel.log for what Internal Server Error is occurring. If there is no log file make sure APP_DEBUG in /path/to/project/root/.env is set to true.

Categories