when I click this product it does not do anything - javascript

I tried to show products if it's available ok added to cart else it show me an alert. if the main window is opened without use AJAX it's works fine but when I **
** for Sorting Item when I use sortby(AJAX) if the item available ok it works add to cart link but if the product is not available when I click it stuck which not do anything, I think the problem with the onClick="*****" but I can't solve it.
I tried many times but I can't solve it.
Thanks for help this is my code.
if (isset($q) || isset($p)) {
$sql="SELECT * FROM product WHERE cat='3'".$q.$p;
$output = '';
$result = mysqli_query($conn,$sql);
while ($row = mysqli_fetch_assoc($result)) {
$output .= '<img src="'.get_image($row['pro_image']).'">';
if ($row['product_status']=='1') {
$output .= '<span>Add to Cart</span>';
} else {
$output .= '<a onclick="return alert("Out of stock!")"><span>Add to Carth</span></a>';
}
} // end while
echo $output;
}

Related

How to fetch questions ony by one on save and next buttons

I have a quiz management system and need to fetch the data from the database and displaying the data one by one on clicking next button.
I want to use ajax to insert data into database after clicking next button by using file read and write function.
$sql=mysqli_query($con,"SELECT * FROM tbl_question WHERE setid='$set' AND status=1 ORDER BY RAND()");
while($sha=mysqli_fetch_array($sql)) {
<h4><? echo $sha['id'];?></h4>
here's simple way to do it
first get question from database then put a button to the next id
<?php
$rows = 0;
$id = isset($_GET['id'] ? (int) $_GET['id'] : 0;
$query = 'SELECT * FROM `tbl_question` WHERE `tbl_question`.`status` = 1 AND `tbl_question`.`id` = ? LIMIT 1';
$mysqli = new mysqli('localhost','user','password','database');
$stmt = $mysqli->prepare($query);
$stmt->bind_param('i',$id);
$stmt->execute();
$stmt->bind_result($id,$something,$something_else,$status);
while($stmt->fetch())
$rows++;
$stmt->close();
$mysqli->close();
if($rows === 0) {
echo 'qustion not found';
} else {
// output qustion
// button
echo '<a type="buttton" href="?id=' . $id + 1 . '">next</a>';
}

appending data from loop php

I'm having an issue appending data from loop. I am trying to append the result that is clicked on, but when theres multiple results every result is appended on click. I am using ajax to retrieve search results. Below is my php section. I think the issue is that every result has the same class so it appends every one, but I can't figure out how to identify only one
if(isset($_POST['inviteSearch'])) {
include_once "connect.php";
$con = getConnection();
$search = "%{$_POST['inviteSearch']}%";
$query = "SELECT FirstName,LastName FROM `Profiles` WHERE FirstName LIKE ? OR LastName LIKE ? ";
$stmt = $con->prepare($query);
$stmt->bind_param("ss", $search ,$search);
if(!($stmt->execute())) {
die(mysql_error());
} else {
$result = $stmt->get_result();
$output = '<ol>';
if(mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)){
$name = $row['FirstName'] . " " . $row['LastName'];
$output .= "
<li id='invitetoken'>
<p>$name</p>
</li>
<script>
$(document).ready(function(){
$('#invitetoken').click(function(){
$('.invitedSection').show();
$('.invitedList').append('<li><p>$name</p><button>×</button></li>');
});
});
</script>
";
}
} else {
$output .= "<h3>We could not find $search</h3>";
}
$output .= '</ol>';
echo "$output";
}
}
To start with the obvious, please use parameterized queries you are currently vulnerable to SQL injection attacks.
You are appending the same js repeatedly in your while loop, that is generally bad practice. I'm going to break this up a bit, since you have both php and JS issues
PHP
Here just generally cleaning up and using parameterized queries and class based mysqli (in line with the above suggestion comments). I also moved the javascript out of the loop as repeating it over and over doesn't achieve anything. Obviously haven't tested my changes but they are fairly boilerplate (see the docs)
if (!isset($_POST[''inviteSearch']) {
return;
}
$connection = new mysqli('host', 'user', 'password', 'schema');
$param = filter_input(INPUT_POST, 'inviteSearch', FILTER_SANITIZE_STRING);
// setup query
$query = "SELECT CONCAT(FirstName, ' ', LastName) AS name
FROM Profiles
WHERE (FirstName LIKE ? OR LastName LIKE ?)";
// prepare statement
$stmt = $connection->prepare($query);
// need variable bind for each tokenized parameter
$stmt->bind_param('ss', $param, $param);
$stmt->execute();
$results = $stmt->get_result();
$output = makeOutput($results);
// Siloing your presentational elements for clarity.
function makeOutput($results) {
if ($results->num_rows === 0) {
return "<h3>We could not find $search</h3>";
}
$output = '<ol>';
while ($row = $results->fetch_assoc()) {
$output .= "<li class='invitetoken'><p>{$row['name']}</p></li>";
}
$output .= '</ol>';
return $output;
}
JavaScript
A few things here, enclosed the function into an IIFE to keep it namespace contained, generally a good practice. The changes to the click handler let the callback handle the update dynamically for any matching class that is clicked. I reference this (in this case it is helpful to think of this as event.target) and use it to find the name to be appended. from there it is pretty similar to what you already had. Of note, I'm using let for variable definitions and template literal syntax for the string data, but you should look up their availability and decide whether you need to worry about old browser support :).
(function($) {
$(document).ready(function(){
$('.invitetoken').on('click', function() {
let name = $(this).children('p').text()
, string = `<li><p>${name}</p><button>×</button></li>`;
$('.invitedSection').show();
$('.invitedList').append(string);
});
});
})(jQuery);

Why my JS Alert box is not displaying?

I have the following code.
if(isset($_POST['save'])){
$descript = $_POST{'descript'};
$type = $_POST{'type'};
$c_max = $_POST{'c_max'};
$status = $_POST{'status'};
$queryInsert = "INSERT INTO `item_master` (`Item`, `Descript`, `Type`, `C_max`, `Exist`, `Status`) VALUES ('$item', '$descript', '$type', '$c_max', '0', '$status');";
try{
$resultInsert = mysqli_query($conn, $queryInsert);
if($resultInsert)
{
if(mysqli_affected_rows($conn) > 0)
{
echo '<script type="text/javascript">alert("Item Inserted");</script>';
header ("Location: Insertion.php");
}else{
echo '<script type="text/javascript">alert("The item could not be inserted ");</script>';
}
}
} catch (Exception $ex){
echo 'Error Delete '.$ex->getMessage();
}
}
My code works fine my query actually can insert new data in my DB but as the title said my "confirmation" alert is not displaying and I don't understand why. Before my if(isser($_POST['save'])) a JS function runs and ask me if I really want to insert a new data. So obviously I have the pop alerts activated in my browser. So... Im I doing somthing wrong?
Thanks for your comments!
you can use window.location(or other related options like:window.location.href).
if(mysqli_affected_rows($conn) > 0)
{
echo '<script type="text/javascript">alert("Item Inserted");window.location="Insertion.php";</script>';
}else{
echo '<script type="text/javascript">alert("The item could not be inserted ");</script>';
}

generate unique link that runs an images slider with different images

i searched all over the web and i couldn't find an answer, please help me!.
I have an HTML form, like this one:
<form action="upload.php" method="POST" enctype="multipart/form-data">
<input type="text" name="folder_name" placeholder="Folder name">
<input type="submit" value="Submit">
</form>
Now, upload.php takes number of images and store a link to the folder in MySQL.
Then i call query.php through angularJS $http to retrieve the link to the folder + the images.
Here is query.php:
session_start();
include 'connection.php';
header("Content-Type: application/json; charset=UTF-8");
$folder = $_SESSION["target_folder"];
$query = "SELECT * FROM links WHERE link LIKE '%$folder%'";
$stmt = $db->prepare($query);
$stmt->execute();
$imagesArray = [];
$images = [];
$response = "";
$imageArray = "";
$first_response = "";
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$images = unserialize($row["images"]);
$imagesArray = explode(",", $images);
foreach($imagesArray as $image) {
if ($response != "") {$response .= ",";}
$response .= '{"target_folder":"' . $row["link"] . '",';
//$response .= '"ext":"' . $row["ext"] . '",';
$response .= '"billboardNumber":"' . $image . '"}';
}
}
$response ='{"records":['.$response.']}';
echo $response;
Last is the slider in slider.html that retrieves the JSON data from query.php:
$http.get("php/query.php")
.success(function (response) {
$scope.slides = response.records;
});
Most important part, my question :-)
every time i run slider.html it overwrites the old slider.html link and outputs the images from the last JSON call.
how can i run slider.html for a month and still get to the same folder even if i generate another 1000 links to different folder.
i hope that someone will understand me :-)
thank you !!!

Elements not included in div when added using Javascript

I have a list of products on my website a Catalogue. The following PHP Code uses javascript to create a div and insert all the product description links inside it.
$sql = "SELECT * from Products ORDER BY `Name` ASC";
$result = mysqli_query($con, $sql);
echo "<script>document.getElementById('products').innerHTML = '<div class=ks>';</script>";
while($row = mysqli_fetch_assoc($result))
{
$rowid = $row['Id'];
$xx = '<a href="Getdesc.php?hid='.$rowid . '" class=lnk>' . $row['Name'] . '</a><br>';
echo "<script>document.getElementById('products').innerHTML += '$xx';</script>";
}
echo "<script>document.getElementById('products').innerHTML += '</div>';</script>";
Ignore all the ks style sheet class and all the mysql stuff for now.
The problem is it displays the grey backgrounded div (grey from style sheet)
and THEN the links. I need the links to be inside the div.
For a little explanation for those of you who are confused by the pieces of code unrelated to the primary purpose of this question,
The Products table in MySQL is a table that hold all my product info including price, name, id, e.t.c.
the "Getdesc.php?hid=..." link is a link to a php web page that will display all the information about the product from it's Id.
"Products" is an Id of a different div that contains this internal div (With the products I mean) PLUS some other stuff ( I don't feel like telling you all about it).
Sorry for the messy code, thanks in advance.
Javascript:
//from https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
function reqListener () {
document.getElementById('products').innerHTML = this.responseText;
}
var oReq = new XMLHttpRequest();
oReq.onload = reqListener;
oReq.open("get", "yourFile.php", true);
oReq.send();
PHP
$sql = "SELECT <columns> from Products ORDER BY `Name` ASC";
$result = mysqli_query($con, $sql);
echo '<div class="ks">';
while($row = mysqli_fetch_assoc($result))
{
$rowid = $row['Id'];
echo '' . htmlspecialchars($row['Name']) . '<br>';
}
echo '</div>'
why not put everything in a variable :
$html = '<div class="ks">'; // btw you forgot those double-quotes. you html won't evaluate the class if not surrounded by double-quotes
while($row = mysqli_fetch_assoc($result))
{
$rowid = $row['Id'];
$xx = '<a href="Getdesc.php?hid='.$rowid . '" class=lnk>' . $row['Name'] . '</a><br>';
$html.= $xx;
}
$html.= '</div>';
then echo it? if you're using php, then there's no need to change the page with javascript after it's been loaded, you just sent all the remainder of the page to the client, why not directly put this code at the right place?
echo $html;

Categories