php server request method is not changing - javascript

im following a video to creat JSON CRUD project, after watching the tuto i download the project file, started a server and put the files in it, but it was not working as i expect, after while i found out the problem could be the server quest method, in the vid, teacher click the submit button the method change to POST, but in my script it still apearing GET, how can i fix it ,
<?php
include 'partials/header.php';
function getUsers()
{
return json_decode(file_get_contents(__DIR__ . '/users/part.json'), true);
}
function getUserById($id)
{
$users = getUsers();
foreach ($users as $user) {
if ($user['id'] == $id) {
return $user;
}
}
return null;
}
function createUser($data)
{
$users = getUsers();
$data['id'] = rand(1000000, 2000000);
$users[] = $data;
putJson($users);
return $data;
}
function updateUser($data, $id)
{
$updateUser = [];
$users = getUsers();
foreach ($users as $i => $user) {
if ($user['id'] == $id) {
$users[$i] = $updateUser = array_merge($user, $data);
}
}
putJson($users);
return $updateUser;
}
$userId = 2;
$user = getUserById($userId);
if (!$user) {
include "partials/not_found.php";
exit;
}
$errors = [
'time' => "",
'part' => "",
];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$user = array_merge($user, $_POST);
$isValid = validateUser($user, $errors);
if ($isValid) {
$user = updateUser($_POST, $userId);
uploadImage($_FILES['picture'], $user);
header("Location: index.php");
}
}
?>
<div class="container">
<div class="card">
<div class="card-header">
<h3>
<?php if ($user['id']): ?>
Update user <b><?php echo $user['id'] ?></b>
<?php else: ?>
Create new User
<?php endif ?>
</h3>
</div>
<div class="card-body">
<form method="POST" enctype="multipart/form-data"
action="">
<div class="form-group">
<label>Time</label>
<input name="name" value="<?php echo $user['time'] ?>"
class="form-control <?php echo $errors['time'] ? 'is-invalid' : '' ?>">
<div class="invalid-feedback">
<?php echo $errors['time'] ?>
</div>
</div>
<div class="form-group">
<label>part</label>
<input name="username" value="<?php echo $user['part'] ?>"
class="form-control <?php echo $errors['part'] ? 'is-invalid' : '' ?>">
<div class="invalid-feedback">
<?php echo $errors['part'] ?>
</div>
</div>
<button class="btn btn-success">Submit</button>
</form>
</div>
</div>
</div>
the original youtube link the submit part is at 26:00 ish
and my online version is here

Related

"add to cart" button works on localhost but not on cpanel (using sessions)

I have contacted godaddy and everything looks good on their end. This code works on my localhost when using xampp but not when uploaded on cpanel. MYSQL works. I am using sessions only to make the "add to cart" button work. When I click the button it refreshes but doesn't add anything to cart. Do I also have to use cookies? If I do then how can I add it to this code?
<?php
session_start();
$connect = mysqli_connect( "localhost", "username", "pass", "");
if(isset($_POST["add_to_cart"]))
{
if(isset($_SESSION["shopping_cart"]))
{
$item_array_id = array_column($_SESSION["shopping_cart"], "item_id");
if(!in_array($_GET["id"], $item_array_id))
{
$count = count($_SESSION["shopping_cart"]);
$item_array = array(
'item_id' => $_GET["id"],
'item_name' => $_POST["hidden_name"],
'item_price' => $_POST["hidden_price"],
'item_quantity' => $_POST["quantity"]
);
$_SESSION["shopping_cart"][$count] = $item_array;
}
else
{
echo '<script>alert("Item Already Added")</script>';
}
}
else
{
$item_array = array(
'item_id' => $_GET["id"],
'item_name' => $_POST["hidden_name"],
'item_price' => $_POST["hidden_price"],
'item_quantity' => $_POST["quantity"]
);
$_SESSION["shopping_cart"][0] = $item_array;
}
}
if(isset($_GET["action"]))
{
if($_GET["action"] == "delete")
{
foreach($_SESSION["shopping_cart"] as $keys => $values)
{
if($values["item_id"] == $_GET["id"])
{
unset($_SESSION["shopping_cart"][$keys]);
echo '<script>alert("Item Removed")</script>';
echo '<script>window.location="mysqlcart.php"</script>';
}
}
}
}
?>
<?php
if(!empty($_SESSION["shopping_cart"]))
{
$total = 0;
$return = [];
foreach($_SESSION["shopping_cart"] as $keys => $values) {
?>
<tr>
<td><?php echo $values["item_name"]; ?></td>
<td><?php echo $values["item_quantity"]; ?></td>
<td>$ <?php echo $values["item_price"]; ?></td>
<td>$ <?php echo number_format($values["item_quantity"] * $values["item_price"], 2);?></td>
<td><span class="text-danger">Remove</span></td>
</tr>
<?php
$total = $total + ($values["item_quantity"] * $values["item_price"]);
$return[] = $values["item_quantity"];
$return[] = $values["item_name"];
}
?>
<?php
}
?>
<?php
$query = "SELECT * FROM tbl_product.tbl_product ORDER BY id ASC";
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
?>
<form method="post" action="mysqlcart.php?action=add&id=<?php echo $row["id"]; ?>">
<input type="text" name="quantity" value="1" class="form-control" />
<input type="hidden" name="hidden_name" value="<?php echo $row["name"]; ?>" />
<input type="hidden" name="hidden_price" value="<?php echo $row["price"]; ?>" />
<input type="submit" name="add_to_cart" style="margin-top:5px;" class="btn btn-success" value="Add to Cart" />
</form>
<?php
}
}
?>

Hide and Display activity checkbox when click on services checkbox

PHP
<?php
//for service 1
$all_activities = "select * from activity join displayserviceactivitymap on activity.activity_id = displayserviceactivitymap.activity_id right join services on services.service_id = displayserviceactivitymap.service_id";
$all_activities = $conn->query($all_activities) or die ($conn>error.__LINE__);
$activities = [];
while ($row = $all_activities->fetch_assoc()) {
$activities[] = $row;
}
$repeated = 'repeated';
foreach ($activities as $act) {
if($act['servicename'] != $repeated){
echo '<br><input type="checkbox" name="arr['.$act['service_id'].'][service]" value="'.$act['service_id'].'" id="'.$act['service_id'].'">'.$act['service_id'].$act['servicename'].'<br>';
$repeated = $act['servicename'];
}
if($act['activity_id'] != '')
echo '<input type="checkbox" name="arr['.$act['service_id'].'][activity][]" value="'.$act['activity_id'].'" id="'.$act['activity_id'].'">'.$act['nameofactivity'].'<br>';
}
?>
Output of My code is
Incometax
Return
filling
GST
Form
Return
GSTR
TDS
Application
Refund
Here Incometax,GST,TDS are services and others are related activity of the services.
I want to display activity when I check checkbox and hide when I uncheck checkbox.
Please try to run this whole code for better understand
<?php
function array_group(array $data, $by_column) {
$result = [];
foreach ($data as $item) {
$column = $item[$by_column];
unset($item[$by_column]);
if (isset($result[$column])) {
$result[$column][] = $item;
} else {
$result[$column] = array($item);
}
}
return $result;
}
$activities = array(
array('service_id' => '1',
'servicename' => 'Incometax',
'activity_id' => '1',
'nameofactivity' => 'Return'),
array('service_id' => '1',
'servicename' => 'Incometax',
'activity_id' => '2',
'nameofactivity' => 'filling')
);
$activities = array_group($activities, 'servicename');
?>
<link href = "https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css" rel = "stylesheet" />
<script src = "https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<?php foreach ($activities as $key => $act) { ?>
<div id="accordion">
<h3>
<label for='product-44-44'>
<input type='checkbox' name="arr[<?php echo $act[0]['service_id']; ?>][service]" value="<?php echo $act[0]['service_id']; ?>" id="<?php echo $act[0]['service_id']; ?>"/>
<?php echo $key; ?>
</label>
</h3>
<div class="columns">
<?php foreach ($act as $value) { ?>
<div class="d1">
<label>
<input type="checkbox" name="arr[<?php echo $value['service_id']; ?>][activity][]" value="<?php echo $value['activity_id']; ?>" id="<?php echo $value['activity_id']; ?>">
<?php echo $value['nameofactivity']; ?>
</label>
</div>
<?php } ?>
</div>
</div>
<?php } ?>
<script>
$("#accordion")
.accordion({
collapsible: true,
active: false,
heightStyle: "content",
beforeActivate: function (event, ui) {
var oldInput = ui.oldHeader.find('input');
oldInput.prop('checked', !oldInput.prop('checked')) // this bit unchecks when the accordion is closed
var newInput = ui.newHeader.find('input');
// this bit checks when the accordion is opened
newInput.prop('checked', !newInput.prop('checked'))
}
}
);
</script>

Adding image to comment box

Thanks for your time guys.
I have the following code working for my commenting system though I can't really be sure about the security for now. But I need your help guys in :
Allowing anyone that comment to add their image to their comment whether registered users or Visitors
Building the inside comment or reply box. This is what I got.
Comment for comment counter
Here is the PHP code for the comment:
<?php
// Connect to the database
include('config.php');
$id_post = "1"; //the post or the page id
?>
<div class="cmt-container" >
<?php
$sql = mysql_query("SELECT * FROM comments WHERE id_post = '$id_post'") or die(mysql_error());;
while($affcom = mysql_fetch_assoc($sql)){
$name = $affcom['name'];
$email = $affcom['email'];
$comment = $affcom['comment'];
$date = $affcom['date'];
// Get gravatar Image
// https://fr.gravatar.com/site/implement/images/php/
$default = "mm";
$size = 35;
$grav_url = "http://www.gravatar.com/avatar/".md5(strtolower(trim($email)))."?d=".$default."&s=".$size;
?>
<div class="cmt-cnt">
<img src="<?php echo $file_path; ?>" height="250" />
<div class="thecom">
<h5><?php echo $name; ?></h5><span data-utime="1371248446" class="com-dt"><?php echo $date; ?></span>
<br/>
<p>
<?php echo $comment; ?>
</p>
</div>
</div><!-- end "cmt-cnt" -->
<?php } ?>
<div class="new-com-bt">
<span>Write a comment ...</span>
</div>
<div class="new-com-cnt">
<input type="text" id="name-com" name="name-com" value="" placeholder="Your name" />
<input type="text" id="mail-com" name="mail-com" value="" placeholder="Your e-mail adress" />
<textarea class="the-new-com"></textarea>
<div class="bt-add-com">Post comment</div>
<div class="bt-cancel-com">Cancel</div>
</div>
<div class="clear"></div>
</div><!-- end of comments container "cmt-container" -->
<script type="text/javascript">
$(function(){
//alert(event.timeStamp);
$('.new-com-bt').click(function(event){
$(this).hide();
$('.new-com-cnt').show();
$('#name-com').focus();
});
/* when start writing the comment activate the "add" button */
$('.the-new-com').bind('input propertychange', function() {
$(".bt-add-com").css({opacity:0.6});
var checklength = $(this).val().length;
if(checklength){ $(".bt-add-com").css({opacity:1}); }
});
/* on clic on the cancel button */
$('.bt-cancel-com').click(function(){
$('.the-new-com').val('');
$('.new-com-cnt').fadeOut('fast', function(){
$('.new-com-bt').fadeIn('fast');
});
});
// on post comment click
$('.bt-add-com').click(function(){
var theCom = $('.the-new-com');
var theName = $('#name-com');
var theMail = $('#mail-com');
if( !theCom.val()){
alert('You need to write a comment!');
}else{
$.ajax({
type: "POST",
url: "ajax/add-comment.php",
data: 'act=add-com&id_post='+<?php echo $id_post; ?>+'&name='+theName.val()+'&email='+theMail.val()+'&comment='+theCom.val(),
success: function(html){
theCom.val('');
theMail.val('');
theName.val('');
$('.new-com-cnt').hide('fast', function(){
$('.new-com-bt').show('fast');
$('.new-com-bt').before(html);
})
}
});
}
});
});
</script>
And the Ajax Script :
<?php
extract($_POST);
if($_POST['act'] == 'add-com'):
$name = htmlentities($name);
$email = htmlentities($email);
$comment = htmlentities($comment);
// Connect to the database
include('../config.php');
// Get gravatar Image
// https://fr.gravatar.com/site/implement/images/php/
$default = "mm";
$size = 35;
$grav_url = "http://www.gravatar.com/avatar/" . md5( strtolower( trim( $email ) ) ) . "?d=" . $default . "&s=" . $size;
if(strlen($name) <= '1'){ $name = 'Guest';}
//insert the comment in the database
mysql_query("INSERT INTO comments (name, email, comment, id_post)VALUES( '$name', '$email', '$comment', '$id_post')");
if(!mysql_errno()){
?>
<div class="cmt-cnt">
<img src="<?php echo $grav_url; ?>" alt="" />
<div class="thecom">
<h5><?php echo $name; ?></h5><span class="com-dt"><?php echo date('d-m-Y H:i'); ?></span>
<br/>
<p><?php echo $comment; ?></p>
</div>
</div><!-- end "cmt-cnt" -->
<?php } ?>
<?php endif; ?>

Check if radio button value is, then echo some HTML

I want to check if the value of the select field is some value and if it is, it needs to echo some text.
I use this code for input box in the form:
<li>
<div class="input-box">
<strong><?php echo $this->__('Would you recommend this product to a friend?') ?></strong>
<?php foreach ( $this->getOptions() as $option ): ?>
<label class="recommend">
<input type="radio" name="recommend" id="recommend_field
<?php echo $option['value'] ?>" class="radio-gender" value="
<?php echo $option['value'] ?>"
<?php if ($option['value'] == $value)
echo ' checked="checked"' ?> >
<?php echo $this->__($option['label']) ?></input>
</label>
<?php endforeach ?>
</div>
</li>
And I currently echo the entire value of the input box with this line:
<div id="reviewwriter">
<span class="recommendation">
<?php echo $this->getAnswer() ?>
</span>
</div>
Code is loaded by this php:
public function confRecommendItemsArray()
{
$resArray = array();
if (Mage::getStoreConfig('advancedreviews/recommend_options/recommend_field1')) {
$resArray[] = array(
'value' => 1,
'label' => Mage::getStoreConfig('advancedreviews/recommend_options/recommend_field1')
);
}
if (Mage::getStoreConfig('advancedreviews/recommend_options/recommend_field2')) {
$resArray[] = array(
'value' => 2,
'label' => Mage::getStoreConfig('advancedreviews/recommend_options/recommend_field2')
);
}
And
class AW_AdvancedReviews_Block_Recommend_Field extends Mage_Core_Block_Template
{
public function canShow()
{
return (Mage::helper('advancedreviews')->confShowRecommend()
&& count(Mage::helper('advancedreviews')->confRecommendItemsArray()));
}
public function getOptions()
{
return Mage::helper('advancedreviews')->confRecommendItemsArray();
}
}
The values of the select field are
1. Yes
2. No
I want to check if value is Yes and if so echo 'Value is Yes'.
And if value is No than echo ''.
See also this JSFiddle: http://jsfiddle.net/wL3xu9d7/1/
But I do not know why it is not working.
How can I achieve that?
i hope this solution you want...
<li>
<div class="input-box">
<strong><?php echo $this->__('Would you recommend this product to a friend?') ?></strong>
<?php foreach ( $this->getOptions() as $option ): ?>
<label class="recommend">
<input type="radio" name="recommend" id="recommend_field<?php echo $option['value'] ?>" class="radio-gender" value="<?php echo $option['value'] ?>"<?php if ($option['value'] == $value) echo ' checked="checked"' ?>><?php echo $this->__($option['label']) ?></input>
</label>
<?php endforeach ?>
</div>
</li>
add hidden field on answer
<div id="reviewwriter">
<span class="recommendation" id="reviewwriteranswer">
<?php echo $this->getAnswer() ?>
</span>
</div>
<script>
$$(".radio-gender").each(function(el) {
el.observe("click", function(event) {
if(el.checked)
{
sub = $('reviewwriteranswer').value;
sub ==sub =.trim();
if(el.value==sub)
{
$('reviewwriteranswer').update('value is yes');
}else {
$('reviewwriteranswer').update('value is No');
}
}
});
});
</script>
<scrip>
var allElements = document.body.getElementsByTagName("*");
for(var i = 0; i < allElements.length; i++) {
var text = allElements[i].innerHTML;
text=text.trim();
if (text == 'Yes') {
allElements[i].innerHTML = "Value is Yes";
}
if (text == 'No') {
allElements[i].innerHTML = "Value is No";
}
}
</scrip>

How do i block specific search words on my website from my search form

i want to block certain searches from my search box....the address looks like this below:
http://domain.com/search.php?search=dog
How do i set up an array or something that blocks the search word "dog"?
<form id="headbar-search" action="search.php" method="GET" x-webkit-speech="x-webkit-speech">
<input type="text" name="search" id="jsid-search-input" value="<?php echo$_GET['search']; ?>" class="ui-autocomplete-input search search_input" placeholder="Search…" tabindex="1"/>
<div class="ui-widget"></div>
</form>
search.php
<?php include 'header.php'; ?>
<!-- Container -->
<div id="container">
<div class="left">
<div class="pic" style="overflow:hidden; margin-top:5px;">
<div style="margin:0 0 5px 0;overflow:hidden;border:none;height:auto;">
<div class="video-container" style="text-align: left; background: #fff;">
<h2>Search results for: <?php echo htmlspecialchars($_GET['search'], ENT_QUOTES, 'UTF-8'); ?></h2>
________________________________________________________________________________________
<br><br>
<?php
if($svid) {
$squerys = mysql_query("SELECT * FROM videos WHERE title LIKE '%$word%' OR author LIKE '%$word%'");
while($ft = mysql_fetch_array($squerys)){
?>
<table>
<tr>
<td>
<?php if($st['seo'] == 1) { ?>
<a href="./<?php echo seo($ft['title'], $ft['id']); ?>.html">
<?php }else{ ?>
<a href="./?v=<?php echo$ft['id'];?>">
<?php } ?>
<div class="image-container"><img src="<?php echo$ft['thumb_large']; ?>" width="120" height="130"></div></a></td>
<td style="padding-left:10px; vertical-align:top;"><h3>
<?php if($st['seo'] == 1) { ?>
<a href="./<?php echo seo($ft['title'], $ft['id']); ?>.html">
<?php }else{ ?>
<a href="./?v=<?php echo$ft['id'];?>">
<?php } ?>
<?php echo stripslashes($ft['title']); ?></a></h3>By: <?php echo$ft['author']; ?><br><?php echo number_format(round($ft['views'])); ?> views</td>
</tr>
<br>
</table>
<?php
}
}else{
echo"No results found.";
}
?>
</div>
<div style="margin: 5px 0 0 0;"></div>
</div></div>
</div>
<?php include 'sidebar.php'; ?>
<div class="clear"></div>
</div>
<!-- Container -->
<?php include 'footer.php'; ?>
A very quick markup
$Naughty_Words = array ("Cat","dog");
function DetermineBanned ($Input,$Array){
if (in_array($Input,$Array)){
return true;
}
return false;
}
var_dump(DetermineBanned("Cat",$Naughty_Words)); // Returns bool(true)
var_dump(DetermineBanned("dd",$Naughty_Words)); // Returns bool(false)
var_dump(DetermineBanned("CatMan",$Naughty_Words)); // Returns bool(false)
var_dump(DetermineBanned("CatMan",$Naughty_Words)); // bool(false)
var_dump(DetermineBanned("CatDog",$Naughty_Words)); // bool(false)
/// Due to the lack of initial code being shown in your question, I have spotted a bug, it's up to you to decide how to make it fool proof
//Validate with
if (DetermineBanned($_GET['Key'],$Naughty_Words) !== false){
echo "Banned Words Detected";
exit;
}
It has to be done in the search.php file.
Example:
$excluded_words = array("dog", "hello", "world");
if(in_array($_GET['search'], $excluded_words) {
echo "Keyword not found";
}
Note: this is just if you pass one word only
Put some javascript between your html and php.
<form>
<input type="text" id="search-box" value="" placeholder="Search…"/>
<input type="submit" onclick="search()"/>
</form>
javascript
var badWords = ["dog"];
function search() {
var searchStr = document.getElementById("search-box").value;
var badWordHit = false;
for (key in badWords) {
if (badWords[key] == searchStr) {
badWordHit = true;
}
}
if (badWordHit) {
alert("I ain't searchin' for no dog");
} else {
alert("searching");
// do ajax request here
}
}

Categories