I'm trying to remove product from session cart.I'm sending request from Ajax to event on click and nothing happens.Here is my code.I don't get any response,like the button at all don't work anything. I on button press to erase id from session data and remove product div.
function removeFromBasket(item) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert('item removed')
}
else if(xmlhttp.status == 400) {
alert("request error 400");
}
else{
alert("something went wrong");
}
};
xmlhttp.open("GET","cart.php?remove="+item,true);
xmlhttp.send();
}
cart.php
<?php
require "cfg.php";
if(isset($_GET['remove'])){
$id = $_GET['remove'];
$items = $_SESSION["cart"];
if(($key = array_search($id, $items)) !== false) {
unset($items[$key]);
$ses = $_SESSION["cart"] = array_values($items);
}
print_r($ses);
die();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<?php
$cart = Session::get("cart");
$cartItems = array_keys($cart);
$q = "select * from items where id in (".implode(",",$cartItems).")";
$db = Database::getInstance();
$res = $db->_db->query($q);
foreach($res as $item){
?>
<form method="post" action="" class='.remove'>
<div style='border:1px solid blue;padding:4px;'>
<?=$item['name']?> (<?=$cart[$item['id']]?>)
<input class='glyphicon glyphicon-remove' onclick='removeFromBasket(<?= $cart[$item['id']] ?>)' name='submit' type='button' value='Remove' >
</div>
<?php
}
?>
Related
I am trying to get the PHP threads progress via AJAX, but the strange think I am facing right now is that any code before startPool() method can be seen in the AJAX response but not after it, would you explain to me why this is happening?
AjaxIndex.php:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="Source code generated using layoutit.com">
<meta name="author" content="LayoutIt!">
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<link href="css/gijgo.min.css" rel="stylesheet" type="text/css" />
<style>
.error {
border: 5px solid red !important;
}
.download-link {
color: #26c605;
}
.download-error {
color: #f20404;
}
</style>
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-md-4">
<form id="county-form" role="form" autocomplete="off">
<div class="form-group">
<label for="courtHouse">
Choose an action to scrap:
</label>
<select id="courtHouse" name="get-data" class="form-control">
<option value="none"></option>
<option value="all" selected="selected">Scrap.</option>
<option value="force">Force scrap.</option>
</select>
</div>
<button id="scrape-button" type="button" class="btn btn-primary">
Scrap now
</button>
<p id="result"></p>
</form>
</div>
</div>
</div>
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/gijgo.min.js" type="text/javascript"></script>
<script src="js/scripts.js"></script>
<script>
$(document).ready(function() {
let result_label = $("p#result");
$("button#scrape-button").on('click', function(e){
e.preventDefault();
result_label.removeClass('download-error').html('');
if($('#courtHouse option:selected').text() === '') {
$("#courtHouse").css("border", "2px solid red");
$("#courtHouse").focus();
return;
}
$("#courtHouse").css("border", "0.916667px solid rgba(0, 0, 0, 0.15)");
$("#courtHouse").focus();
result_label.html('<b>Please don\'t close the browser until the link appears here.</b>');
const formData2 = $("#county-form").serialize();
let last_response = '';
$.ajax({
//url: "testAJAX.php",
url: "AjaxThread.php",
method: 'POST',
data: formData2,
dataType: 'text',
//contentType: 'application/json',
encode: true,
xhrFields: {
onprogress: function(e) {
let response = e.target.response.replace(/\n/g, '').split("|").slice(0, -1).pop();
//console.log('response split: ', e.target.response.replace(/\n/g, '').split("|").slice(0, -1));
console.log('response pop: ', response);
//console.log('response pop: ', JSON.parse(response).replace(/\n/g, ''));
}
},
success: function (result, status, xhr) {
console.log('success step');
console.log(result.status);
if(result.status === 'success') {
result_label.html(result.data);
}
else {
result_label.removeClass('download-link').addClass('download-error').html(result.data);
}
},
error: function(request, status, error) {
result_label.removeClass('download-link').addClass('download-error').html('Internal error, please contact the support.');
console.log('error step');
//console.log(JSON.stringify(request));
console.log(request);
console.log(status);
console.log(error);
}
});
});
});
</script>
</body>
</html>
AjaxThread.php:
<?php
require_once __DIR__ . '/vendor/autoload.php';
use \ByJG\PHPThread\ThreadPool as ScrapperPool;
try {
$scrapper_pool = new ScrapperPool();
for($i = 0; $i < 10; ++$i) {
$rfc_scrapper = new ScrapperThread($i);
$scrap = function(ScrapperThread $instance) {
return $instance->scrap();
};
$scrapper_pool->queueWorker($scrap, [$rfc_scrapper]);
}
$scrapper_pool->startPool();
$scrapper_pool->waitWorkers();
// Get results
file_put_contents('AjaxThreadCount', count($scrapper_pool->getThreads())); //
foreach($scrapper_pool->getThreads() as $worker) {
echo($scrapper_pool->getThreadResult($worker));
}
}
catch(Exception $e) {
echo $e->getMessage();
}
?>
Check if this helps
<?php
require_once __DIR__ . '/vendor/autoload.php';
use \ByJG\PHPThread\ThreadPool as ScrapperPool;
try {
$scrapper_pool = new ScrapperPool();
for($i = 0; $i < 10; ++$i) {
$rfc_scrapper = new ScrapperThread($i);
$scrap = function(ScrapperThread $instance) {
return $instance->scrap();
};
$scrapper_pool->queueWorker($scrap, [$rfc_scrapper]);
}
$scrapper_pool->startPool();
$scrapper_pool->waitWorkers();
$result_getThreads = $scrapper_pool->getThreads();
// Get results
file_put_contents('AjaxThreadCount', count($result_getThreads)); //
if($result_getThreads){
foreach($result_getThreads as $worker) {
echo($scrapper_pool->getThreadResult($worker));
}
}else{
echo 'Something went wrong';
}
}
catch(Exception $e) {
echo $e->getMessage();
}
?>
Important Apache webserver information
Try to run AjaxThread.php through command line and see if it works with (exit() in ForkHandler.php). Because you do an ajax request I suppose you run this through an apache webserver. In this case the exit() does not work, you should use instead:
posix_kill(getmypid(), SIGKILL);
Change this line:
for($i = 0; $i < 10; ++$i) {
to
for($i = 0; $i < 10; $i++) {
I'm having problem with calling php page with ajax. When I click the button, the chart.php is not displayed. Both of the buttons don't work. The target php files are the same with different data only, so I included only one of the chart.php pages. How can I fix this? please. Thanks for your help!
Index.php code:
<!DOCTYPE html>
<html>
<head>
<title>Charts</title>
<link rel="stylesheet" type="text/css" href="etc/main.css" />
<script type="text/javascript" src="etc/jquery-2.1.4.js"></script>
</head>
<body>
<div id="wrapper">
<div id="header">
<button id='actbutton1'> Chart1</button>
<button id='actbutton2'> Chart2</button>
</div>
<div id="contentliquid">
<div id="content">
<div id="querydiv">
</div>
</div>
</div>
<div id="leftcolumn">
</div>
</div>
<script>
document.getElementById('actbutton1').onclick = function() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "chart1.php", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("querydiv").innerHTML = xhr.responseText;
}
}
xhr.send();
}
document.getElementById('actbutton2').onclick = function() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "chart2.php", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("querydiv").innerHTML = xhr.responseText;
}
}
xhr.send();
}
</script>
</body>
</html>
The page I call with ajax, chart1.php, is this:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydb";
$con = new mysqli($servername, $username, $password, $dbname);
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
else
{
}
$query = "SELECT Week, Omean FROM charts";
$aresult = $con->query($query);
?>
<!DOCTYPE html>
<html>
<head>
<title>Chart1</title>
<script type="text/javascript" src="loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart(){
var data = new google.visualization.DataTable();
var data = google.visualization.arrayToDataTable([
['Week','Omean'],
<?php
while($row = mysqli_fetch_assoc($aresult)){
echo "['".$row["Week"]."', ".$row["Omean"]."],";
}
?>
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc: 'stringify',
sourceColumn: 1,
type: 'string',
role: 'annotation'
}]);
var options = {
title: 'Chart1',
'width':1700,
'height':600,
hAxis : {textStyle : {fontSize: 8}},
'tooltip' : { trigger: 'none'},
enableInteractivity: false,
legend: { position: 'bottom' }
};
var chart = new
google.visualization.LineChart(document.getElementById('curvechart'));
chart.draw(data, options);
chart.draw(view, options); // <-- use data view
}
</script>
</head>
<body>
<div id="curvechart" style="width: 900px; height: 400px"></div>
</body>
</html>
I am getting user data by passing the id in url and using the select statement where it matches the id in url and display result
But I want this by using ajax. Please help me
<div id="show_data">
<?php
$id=$_GET['id'];
$category=$_GET['category'];
if ($category==Hosted) {
$result = $wpdb->get_results ("SELECT * FROM wp_user_host WHERE user_id=$id");
foreach ( $result as $print ){
?>
<table>
<tr>
<td>Name: <?php echo $print->drive_name;?</td>
<td>Date: <?php echo $print->drive_date;?</td>
</tr>
</table>
<?php
}
}
?>
</div>
<a href="page.php?id=2&category=Hosted:>VIEW DATA</a>
lets say i have an index file like follow
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div>TODO write content</div>
<button id="testDom">click to load dom</button>
<p id="domOutput"></p>
<script>
document.getElementById("testDom").addEventListener('click', function(){
loadAjax();
});
function loadAjax(){
var xmlHttp = new XMLHttpRequest();
var requestUrl = 'test.php';
xmlHttp.onreadystatechange = function(){
if( this.readyState == 4 && ( this.status > 200 || this.status < 300 ) ){
console.log("ok");
document.getElementById("domOutput").innerHTML = xmlHttp.responseText;
}
}
xmlHttp.open('GET', requestUrl);
xmlHttp.send();
}
</script>
</body>
lets say if u click the button ajax call made to the php file called test.php
<?php
echo "php file loaded";
ouput will printed in the index.html on p tag.
My question is very simple. I have some cycles within other cycles, however, let's imagine it's just one and I want to use a progress bar to only show the progress of this cycle.
I have here code that I am developing, in which I use UIKit, but that is making my head hurt because everything works except the progress bar.
The memory consumption is also a complete exaggeration, because through the task manager I see RAM being completely consumed!
The code I'm using is this:
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" href="uikit3/css/uikit.min.css" />
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="uikit3/js/uikit.min.js"></script>
</head>
<body>
<progress id="progressbar" class="uk-progress" value="0" max="100"></progress>
<div id="information" style="width"></div>
<div id="information2" style="width"></div>
<?php
ini_set('memory_limit','16M');
$total = 1741768;
$x = 0;
for($n1=1; $n1 < 15; ++$n1)
{
for($n2=($n1+1); $n2<48; ++$n2)
{
for($n3=($n2+1); $n3<49; ++$n3)
{
for($n4=($n3+1); $n4<50; ++$n4)
{
for($n5=($n4+1); $n5<51; ++$n5)
{
++$x;
$percent = intval($x/$total * 100);
echo '<script language="javascript">document.getElementById("information").innerHTML="'.$percent.'"</script>';
echo '<script language="javascript">document.getElementById("information2").innerHTML="'.$x.'"</script>';
echo '<script>
jQuery(function () {
var animate = setInterval(function () {
window.progressbar && (progressbar.value = "'.$percent.'");
if (!window.progressbar || progressbar.value >= progressbar.max) {
clearInterval(animate);
}
},0);
});
</script>';
}
}
}
}
}
echo '<script language="javascript">document.getElementById("information").innerHTML="Chaves Geradas!"</script>';
?>
</body>
</html>
I would like to have on my HTML page a simple button allowing me if right clicked one, click activate every time my PHP script.
I tried with this code, without any positive result for the moment:
//My html code
<!DOCTYPE html>
<head>
<title><?php echo $pageTitle; ?></title>
<meta charset="UTF-16" />
<link rel="stylesheet" type="text/css" media="all" href="css.css">
<style></style>
</head>
<body>
<main>
<button onclick="doTheFunction();">Run the script</button>
<script>
function doTheFunction(){
xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","script.php",true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
}
}
</script>
</main>
<footer>
<?php echo $footer; ?>
</footer>
</body>
A part of my php code :
echo "$result";
Your code is doing nothing with the result of Ajax. I suggest starting here as a reference. The most important thing you're missing is:
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
Where "demo" is the Id of the element you want to load the Ajax result into. Otherwise nothing will happen with that result.
EDIT
Let's clean up your code so scripts and html are separate:
function doTheFunction(){
xmlhttp = new XMLHttpRequest();
//Set this before sending!!
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
}
//No reason to post
xmlhttp.open("GET","theme/generator/gensent.php",true);
xmlhttp.send();
}
<head>
<title><?php echo $pageTitle; ?></title>
<meta charset="UTF-16" />
<link rel="stylesheet" type="text/css" media="all" href="css.css">
<style></style>
</head>
<body>
<main id="demo">
<button onclick="doTheFunction();">Run the script</button>
</main>
<footer>
<?php echo $footer; ?>
</footer>
</body>
I would put the <script> tag at the end of your html, after closing the body, or include it in the header from another file. Note- I use GET since no sensitive info is transferred, the script should load after the HTML- hence put at the end, and finally you need a tag with the Id for this to actually work.