Can't retrieve data from controller to view page without refreshing - javascript

I'm new to coding and I'm trying to create a simple project which is a BMI calculator. Every time I hit the 'calculate' button the page posts the data with the DIV element for a second then the page refreshes.
Here's my code from controller:
<?php
class Cal extends BaseController
{
protected $helpers = ['url', 'form', 'text', 'html'];
public function calc(){
return view('calc');
}
public function calculator(){
$bmi = new BMI();
$height = $this->request->getPost('height');
$weight = $this->request->getPost('weight');
$bmicalc = $weight/($height*$height);
$result;
if($bmicalc <= 18.5){
$result = "Underweight";
}elseif($bmicalc > 18.5 AND $bmicalc<=24.9){
$result = "Normal weight";
}elseif($bmicalc > 24.9 AND $bmicalc<=29.9){
$result = "Overweight";
}elseif($bmicalc > 30.0){
$result = "OBESE";
}elseif($bmicalc > 31.0){
$result = "OBESE 2";
}
$bmiInsert = array(
'weight' => $this->request->getPost('weight'),
'height' => $this->request->getPost('height'),
'res' => $result,
);
$data = [
'res' => $result,
];
$bmi->insert($bmiInsert);
return view('calc', $data);
}
}
Here's my code for my view page:
<div class="try">
<?php
if(isset($res[0]))
echo "Your BMI is ", "$res";
?>
</div>
Now here's the script that I've tried already:
$(".btn-check").click(function() {
$('form').submit(function() {
$(".try").css('display', 'block');
event.preventDefault();
});
});
I've also tried changing the button type into "button" instead of "submit" but still no avail.

You need to pass event as an function parameter to submit to prevent default behaviour
$(".btn-check").click(function() {
$('form').submit(function(event) {
$(".try").css('display', 'block');
event.preventDefault();
});
});

Related

ALERT ,when searched word not found in mysql database

my coding is all about
1)fetch the data from mysql thro php
2)get data from php to d3 based on input by using PHP URL
I want to set alert when the text in the input field is not found in mysql database..
now when I try with the word other than mysql data, it shows
this console
how can i alert when wrong word(other than mysql database value) is submitted
HTML FORM
<form name="editorForm">
<input type="text"name="editor" id="editor"
onchange="document.getElementById('editorForm').submit();">
<input type="submit"value="butn">
</form>
JQUERY TO FETCH THE DATA FROM PHP BASED ON URL
$(function () {
$('form').submit(function (e) {
e.preventDefault();
var t=$('form').serialize();
var u='http://localhost:8888/saff/indexi.php?'+t;
if(u==null){
alert("not found");
}
else{
funn();
}
D3 CODES
function funn(){
d3.json(u, function(treeData) {
//D3 CODES
});
}
my php code
<?php
$con=mysqli_connect("localhost","root","admin","data");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$name=$_GET['editor'];
$sql="SELECT * FROM phptab where value LIKE '%".$name."%'";
$r = mysqli_query($con,$sql);
$data = array();
while($row = mysqli_fetch_assoc($r)) {
$data[] = $row;
}
function buildtree($src_arr, $parent_id = 0, $tree = array())
{
foreach($src_arr as $idx => $row)
{
if($row['parent'] == $parent_id)
{
foreach($row as $k => $v)
$tree[$row['id']][$k] = $v;
unset($src_arr[$idx]);
$tree[$row['id']]['children'] = buildtree($src_arr, $row['id']);
}
}
ksort($tree);
return $tree;
}
function insertIntoNestedArray(&$array, $searchItem){
if($searchItem['parent'] == 0){
array_push($array, $searchItem);
return;
}
if(empty($array)){ return; }
array_walk($array, function(&$item, $key, $searchItem){
if($item['id'] == $searchItem['parent']){
array_push($item['children'], $searchItem);
return;
}
insertIntoNestedArray($item['children'], $searchItem);
}, $searchItem);
}
$nestedArray = array();
foreach($data as $itemData){
//$nestedArrayItem['value'] = $itemData['value'];
$nestedArrayItem['id'] = $itemData['id'];
$nestedArrayItem['name'] = $itemData['name'];
$nestedArrayItem['parent'] = $itemData['parent'];
$nestedArrayItem['tooltip'] = $itemData['tooltip'];
$nestedArrayItem['color'] = $itemData['color'];
$nestedArrayItem['level'] = $itemData['level'];
$nestedArrayItem['children'] = array();
//$data[]=$dat;
insertIntoNestedArray($nestedArray, $nestedArrayItem);
}
header('Content-Type: application/json');
$json= json_encode($nestedArray,JSON_UNESCAPED_UNICODE);
echo $json = substr($json, 1, -1);
?>
works as expected when the word used is exist in the database
and the page looks like this
getting correct json format in the mozilla console.but design is not shown in the page...but in chrome ,everything works fine..
You need to test if the page is empty in the json function of the d3
function funn(){
d3.json(u, function(treeData) {
if(!treeData.length){
alert("not found");
}else {
//D3 CODES
}
});
}
Make sure that you return a empty object from the page when not found

javascript function passes only one specific parameter

I built this function in my html page:
<script type = "text/javascript">
function set() {
var type = 'test';
var status = 0;
var id = 2;
$.post("sys/class/buttonHandler.php"), { status: status};
}
</script>
that is triggered by this button:
<button type="button" onclick="set()" class="btn">Press here</button>
to reach this buttonHandler.php:
<?php
require 'class.global.php';
$type = 'test';
$status = $_POST['status'];
$id = 2;
set($type, $status, $id);
?>
that correctly executes this function in the class.global.php:
function set($type, $status, $id)
{
$result = mysql_query("UPDATE users SET $type = '$status' WHERE id = '$id'");
}
The problem is when I try to change the parameter that the javascript function passes or when I try to add the other two parameters, like this:
<script type = "text/javascript">
function set_profile() {
var type = 'test';
var status = 0;
var id = 2;
$.post("sys/class/admobButtonHandler.php"), { status: status, type: type, id: id};
}
</script>
<?php
require 'class.global.php';
$type = $_POST['type'];
$status = $_POST['status'];
$id = $_POST['id'];
setProfile($type, $status, $id);
?>
Nothing works anymore..
Is there any other way that I can make this work?
Thanks
Take a look at the jQuery docs for the post() function. http://api.jquery.com/jquery.post/. You've got your syntax all wrong... It should be:
$.post("/sys/class/admobButtonHandler.php", {status: status, type: type, id: id});

JQuery form submission generates a new form

I have a JQuery script that submits user input to a PHP script in the same file, and then displays the result of what the PHP script does with the input. That part works fine. The issue that I’m having is that, upon submission, the JQuery script (at least, I think it's the script) also generates a new submission box below the original.
I’m not sure why. I thought at first that it was an issue with the input type, with the asynchronous part, or even with where I had the form in the overall code, but none of those seem to be playing any role. I'm still a beginner and I'm just not seeing the issue.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<form id = "my_form">
verb <input type = "text" id ="word1"/>
<input type = "submit"/></form>
<div id="name"></div>
<script>
$(document).ready(function(){
$("#my_form").on('submit', function(e)
{
e.preventDefault();
var verb = $ ("#word1").val();
var tag = "#Latin ";
var url = "http://en.wiktionary.org/wiki/"+verb+tag;
$.ajax({
url: "Parser.php",
data: {"verb": verb},
type: "POST",
async: true,
success: function(result){
$("#name").html(result);
$("#name").append(url);
}
});
});
});</script>
RESULT:
PHP
<?php
$bank = array();
function endsWith($haystack, $needle) {
return $needle === "" || (($temp = strlen($haystack) - strlen($needle)) >= 0 && strpos($haystack, $needle, $temp) !== false);
}
function check_end_array($str, $ends)
{
foreach ($ends as $try) {
if (substr($str, -1*strlen($try))===$try) return $try;
}
return false;
}
function db_connect() {
static $connection;
if(!isset($connection)) {
$connection = mysqli_connect('127.0.0.1','username','password','Verb_Bank');
}
if($connection === false) {
return mysqli_connect_error();
}
return $connection;
}
function db_query($query) {
$connection = db_connect();
$result = mysqli_query($connection,$query);
return $result;
}
function db_quote($value) {
$connection = db_connect();
return "'" . mysqli_real_escape_string($connection,$value) . "'";
}
$y = false;
if (isset($_POST['verb'])){
$y=db_quote($_POST['verb']);
echo $y;
echo "\n";
$m = db_query("SELECT `conjugation` FROM normal_verbs WHERE (" . $y . ") LIKE CONCAT('%',root,'%')");
if($m !== false) {
$rows = array();
while ($row = mysqli_fetch_assoc($m)) {
$rows[] = $row;
}
}
foreach ($rows as $key => $value){
if (in_array("first",$value)==true){
echo "first conjugation verb\n";}
$y = $_POST["verb"];
$x = $y;
foreach ($bank as $key => $value)
(series of IF-statements)
}}?>
As Roamer-1888 says's the problem lies in server side, you are returning a html which has a input too. You need to change your code to return only the result string which you append to the div. Else if this is not possible doing at server side as it might require you to change lot of code, then you can strip off the input element from the result and then append it to the div. Like below.
success: function(result){
var div = document.createElement('div');
div.innerHTML = result;
$(div).find('input').remove();
$("#name").html(div.innerHTML);
$("#name").append(url);
}

pass data from java script to php file in codeigniter

I had developed a event management system using javascript php and mysql. It works perfectly in plain php but now I need to migrate it into codeigniter and need some advice on how to pass the data from js to php while in codeigniter.
My front end java script function is like this
// event creating
dp.onTimeRangeSelected = function (args) {
var name = prompt("New event name:", "Event");
dp.clearSelection();
if (!name) return;
var e = new DayPilot.Event({
start: args.start,
end: args.end,
id: DayPilot.guid(),
resource: args.resource, //Change to classroom name
text: name //Change to event name
});
dp.events.add(e);
args.text = name;
DayPilot.request(
"backend_create.php",
function(req) { // success
var response = eval("(" + req.responseText + ")");
if (response && response.result) {
dp.message("Created: " + response.message);
}
},
args,
function(req) { // error
dp.message("Saving failed");
}
);
};
The php file handling the create function is like this
<?php
require_once '_db.php';
$insert = "INSERT INTO events (name, start, end, resource) VALUES (:name, :start, :end, :resource)";
$stmt = $db->prepare($insert);
$stmt->bindParam(':start', $start);
$stmt->bindParam(':end', $end);
$stmt->bindParam(':name', $name);
$stmt->bindParam(':resource', $resource);
$received = json_decode(file_get_contents('php://input'));
$start = $received->start;
$end = $received->end;
$resource = $received->resource;
$name = $received->text;
$stmt->execute();
class Result {}
$response = new Result();
$response->result = 'OK';
$response->message = 'Created with id: '.$db->lastInsertId();
echo json_encode($response);
?>
Now on migrating to codeignitor I moved to segregated the backend_create.php file into model and controller and it looks like this.
The controller part
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class TimecalCon extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model("Timecal_model");
}
public function insert()
{
$received = json_decode(file_get_contents('php://input'));
$start = $received->start;
$end = $received->end;
$resource = $received->resource;
$name = $received->text;
$this->Timecal_model->InsertDetails($name, $start, $end, $resource);
}
The Model
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Timecal_model extends CI_Model {
function __construct()
{
// Call the Model constructor
parent::__construct();
}
function InsertDetails($name, $start, $end, $resource)
{
$insert = "INSERT INTO events (name, start, end, resource) VALUES (:name, :start, :end, :resource) ";
$query = $db->prepare($insert);
$stmt->bindParam(':start', $start);
$stmt->bindParam(':end', $end);
$stmt->bindParam(':name', $name);
$stmt->bindParam(':resource', $resource);
$stmt->execute();
class Result {}
$response = new Result();
$response->result = 'OK';
$response->message = 'Created with id: '.$db->lastInsertId();
return json_encode($response);
}
The issue is when I change the javascript in the view page and use it like this
.....
DayPilot.request(
"TimecalCon/insert", .......
The functionality breaks and I am unable to insert events into the db. How should I be passing the data from js to the controller in this condition?
We can send the value from javascript to controller using Ajax. I have some code of mine which may help you.
function deleteEmp(empid){
var base_url = '<?php echo site_url(); ?>';
var r=confirm("Do You Really Want to Delete? ")
if (r==true)
{
objPost= new Object();
objPost.empid = empid;
$.ajax({
url:"employee_registration/deleteEmp?empid="+empid,
type:"POST",
data:objPost,
beforeSend:function(data){
},
error:function(data){
},
success:function(data){
alert(data);
result=JSON.parse(data);
alert(result);
if(result.status == 'success'){
alert('Deleted Successfully ');
window.location.reload();
return false;
}
}
});
}else{
return false;
}
}
As you can see I have pass the empid from my view to controller using ajax which gives me result back in variable. Which in this case is json.
Try this
DayPilot.request("<?php echo base_url().'TimecalCon/insert';?>",...)
You'll have to add "url" in "autoload.php" under config folder, then check if the url being loaded is the right one if not. Try modifying base_url() a bit like adding or removing the "index.php" part in the url.
Hope This helps

Using javascript to reload php function

I am using OO php and have the front end page generated through this class, I am trying to reload a button so that once it is pressed it changes class and button all together. Below is the function in which generates the buttons:
public static function printStartStopAll($enabled = 'false')
{
syslog(LOG_INFO, "HELLO");
?>
<div class="big-button-wrapper">
<?
if ( is_combined_server() ) {
// print start all button
$title_text = dgettext('triplecast', "Start All Transfers");
$btn_text = dgettext('triplecast', "Start All");
if ( !Transfer::CanTransferNow() || count(self::getPendingTransfers()) == 0 ) {
$class = "big-green-button-off";
$onclick='';
} else {
$class = "big-green-button";
$onclick = 'onclick=\'startAllTransfers("'.str_replace('"', '\"', self::$txtOpts).'");\'';
}
?>
<div id='start-all' class='<?=$class?>' title='<?=$title_text?>' <?=$onclick?>><?=$btn_text?></div>
<?
}
//Separate out the text for readability.
$title_text = dgettext('triplecast', "Stop Transfers and disable the system till you re-enable it in the configuration menu");
$btn_text = dgettext('triplecast', "Stop All");
$confirm_msg= dgettext('triplecast', 'If you continue all current transfers will be stopped and the system disabled till you re-enable it.');
$confirm = dgettext('triplecast', 'Do you want to stop all transfers?');
?>
<div id='stop-all' class='big-red-button' title='<?=$title_text?>' onclick='stopAllTransfers("<?=$confirm_msg.'\n\n'.$confirm?>", "<?=str_replace('"', '\"', self::$txtOpts)?>");'><?=$btn_text?></div>
<?
syslog(LOG_INFO, "===>".$enabled);
if($enabled != "true") {
$title_text = dgettext('triplecast', "Enable Select");
$btn_text = dgettext('triplecast', "Select");
$class = "big-green-button";
$onclick='onclick=\'enableSelect(true);\'';
?>
<div id='enable_select' class='<?=$class?>' title='<?=$title_text?>' <?=$onclick?>><?=$btn_text?></div>
<?
}
else {
$title_text = dgettext('triplecast', "Stop selected Transfers");
$btn_text = dgettext('triplecast', "Stop Selected");
?>
<div id='stop-select' class='big-red-button' title='<?=$title_text?>' onclick=''><?=$btn_text?></div>
<?
}
?>
</div>
<?
}
Please ignore any syslog :) thats me testing ...
I use ajax to push a variable back to the page and reload this function.
function enableSelect(value)
{
$.getJSON("ajax_requests/enableSelect.php", { enabled: value },
function(data){
});
}
<?php
$requireAuthentication = false;
$requireLicensing = false;
$minimalIncludes = true;
require_once('../Library.php');
header('content-type: application/json');
$enabled = getParameter('enabled');
$dist_server = TriplecastConfig::get('distribution_server');
$resp = new TriplecastMsg();
try {
TransferController::setSelectEnabled($enabled);
TransferController::printStartStopAll($enabled);
} catch (Exception $e) {
$resp->setCode(STATUS_ERROR);
$resp->setMessage($e->getMessage());
}
$json = new JSON();
echo $json->encode( array("code" => $resp->getCode(), "message" => $resp->getMessage())
);
?>
I understand that the code is messy, im just trying to figure out how to do this properly.
The aim of this is to enable the user to press this button and for it to reload the button with the stop-selected class (big-red-button)
Any help will be gratefully appreciated

Categories

Resources