using ajax call to empty the div - javascript

Making a ajax, so when i click on this Link1 Button, i need to empty the contents in the products_list div
<button type="w3-button">Link1</button>
Please help me on how to make a ajax call when clicking link1 button it empty the products in product_list
The below code contains a javascript to clear the contents of products_list but it do not work
PHP File
<?php
session_start(); //start session
include("config.inc.php"); //include config file
?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Stores</title>
<link href="style/style1.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
</head>
<body>
<div align="center">
<h3>Products</h3>
</div>
<script>
$(document).on("click", ".w3-button", function() {
$('.products-wrp').html('')
// $("#products_list").html();
});</script>
<?php
//List products from database
$results = $mysqli_conn->query("SELECT product_name, product_desc, product_code, product_image, product_price FROM products_list");
//Display fetched records as you please
$products_list = '<ul id ="products_list" class="products-wrp">';
while($row = $results->fetch_assoc()) {
$products_list .= <<<EOT
<li>
<form class="form-item">
<h4>{$row["product_name"]}</h4>
<div>
<img src="images/{$row["product_image"]}" height="62" width="62">
</div>
<div>Price : {$currency} {$row["product_price"]}<div>
</form>
</li>
EOT;
}
$products_list .= '</ul></div>';
echo $products_list;
?>
</body>
</html>

Check Code below that will empty the div On Failure on Ajax Request -
function getFailOutput() {
$.ajax({
url:'myAjax.php',
success: function (response) {
console.log(data, response);
$('#output').html(response);
},
error: function () {
//Empty Output Div ON Error Returned From Ajax Request
$('#output').html('');
},
});
return false;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
test success | test failure
<div id="output">waiting for action</div>

Related

jquery add 1 to variable on click then insert to database

I want to have 2 buttons on a page. If u click button "addMe", then I want to add 1 to a variable? (theCount). The other button (InsertDB) I want to add "theCount" into my db.
Im able to add data to my db, but not "theCount", probly because its a "div id" and I dont know how to do it. I have 3 files: index.php, addscript.js and insert.php
Here is my script:
index.php:
<?php
include "insert.php";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add 1 on click, then add sum to db</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<button id="addMe">Add 1</button>
<div id="theCount"></div>
<form method="post">
<button id="InsertDB">Add to DB</button>
</form>
</body>
</html>
<script
src="https://code.jquery.com/jquery-3.5.1.min.js"
integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
crossorigin="anonymous"></script>
<script src="addscript.js"></script>
addscript.js:
var counter = 0;
$(document).ready(function() {
$("#InsertDB").click(function(){
var theCount= $("#theCount").val();
$.ajax({
type: "POST",
url: "insert.php",
data: "theCount=" + theCount,
success: function(data) {
alert("Added to DB");
}
});
});
$("#addMe").click(function(){
counter++;
$("#theCount").text(counter);
});
});
insert.php:
<?php
include "db.php";
$theCount=$_POST['theCount'];
$sql = "INSERT INTO `mat`( `polse`)
VALUES ('$theCount')";
if (mysqli_query($conn, $sql)) {
echo "Craig is Satoshi";
}
else {
echo "Error";
}
mysqli_close($conn);
?>
#theCount is a <div>:
<div id="theCount"></div>
And a <div> doesn't have a value, so this won't work:
var theCount= $("#theCount").val();
Instead, get the text of the element:
var theCount= $("#theCount").text();
Much in the same way that you already set the text of the element:
$("#theCount").text(counter);

How to connect HTML page to MySQL Workbench Server using JavaScript,Ajax and PHP?

I have an HTML page where we enter the name of a movie and if that movie is present in the database,then the name is displayed. I am trying to connect to the database using JavaScript, Ajax and PHP. The database is in the MySQL Workbench Server.
This is what I have done:
pc.html
<html>
<head>
<script type="text/javascript">
function Search_Data()
{
var httpr = new XMLHttpRequest();
var movie_name=document.getElementById("moviename").value;
console.log(movie_name);
httpr.open("GET","get_data.php",true);
httpr.send();
httpr.onreadystatechange = function()
{
if(this.readyState==4 && this.status==200)
{
alert(this.responseText);
}
}
}
</script>
<body>
<input type="text" name="moviename" id="moviename" placeholder="Enter a movie...">
<br/>
<input type="button" name="search" value="Search" onclick="Search_Data()">
<br/>
<span id="response"></span>
</body>
</head>
</html>
get_data.php
(Below code is a trial code to see if its working)
<?php
echo "Hello World"
?>
In the browser,the result I am getting is:
The files are in the following location:
C:\Users\Admin\AppData\Roaming\MySQL\Workbench\scripts
The entire code is getting displayed instead of just "Hello World".I am new to web development and PHP and I am not sure what seems to be the problem.
what are you using is ajax with normal java-script i suggest to use jquery ajax and this is a full example how to connect it to php and how to get the value or list
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="main.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<button type="button" name="search" id="search" class="btn btn-info">Search</button>
<td width="90%"><span id="employee_name"></span></td>
second
<input type="input" id="inputs" value="submit">
<p id="email"></p>
<p id="pass"></p>
<p id="permission"></p>
<script>
$(document).ready(function(){
$('#search').click(function(){
var val = document.getElementById("inputs").value;
var id= $('#employee_list').val();
setInterval(function(){
$.ajax({
url:"db.php",
method:"POST",
data: {val : val},
dataType:"JSON",
success:function(data)
{
$('#email').text(data[val].email);
$('#pass').text(data[val].pass);
$('#permission').text(data[val].perm);
}
})
}, 1000);
});
});
</script>
</body>
</html>
the php file
<?php
$items = array();
$url="localhost";
$user= "root";
$pass="";
$dbname="test";
$value= 0;
if(isset( $_POST['val'])){
$value= $_POST['val'];
}
$num=0;
$connect=mysqli_connect($url,$user,$pass,$dbname);
$result="SELECT email,pass,permission FROM test where id=$value";
$sql=mysqli_query($connect,$result);
while($row=mysqli_fetch_assoc($sql) ){
/* add a new item */
$num++;
$items[$value] = array(
'email' => $row['email'],
'pass' => $row['pass'],
'perm' => $row['permission']
);
}
$json_response = json_encode($items);
echo $json_response;
?>

jquery ajax not sending data in code igniter

I'm new to Codeigniter MVC framework. when i send data through ajax from views to controller this error shows click here to view the image
here is my code :
views/ajax_post_view.php :
<!DOCTYPE html>
<html lang="en">
<head>
<title>Ajax 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.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
$(document).ready(function(){
$(".submit").click(function(e){
e.preventDefault();
var user_name = $("input#name").val();
var password = $("input#pwd").val();
//alert(user_name);
//alert(password);
$.ajax({
type:'POST',
url:'<?php echo base_url();?>'+'index.php/ajax_controller/submit',
dataType:'json',
data:{name:user_name,pwd:password},
success:function(data){
console.log(data);
}
});
});
});
</script>
</head>
<body>
<div class="main">
<div id="content">
<h2 id="form-head">Pavan Code Igniter Ajax</h2>
<hr>
<div id="form_input">
<?php
echo form_open();
echo form_label('User Name');
$data_name = array(
'name'=>'name',
'class'=>'input_box',
'placeholder'=>'Please enter name',
'id'=>'name'
);
echo form_input($data_name);
echo "<br>";
echo "<br>";
echo form_label('Password');
$data_name = array(
'type'=>'password',
'name'=>'pwd',
'class'=>'input_box',
'placeholder'=>'Please enter Password',
'id'=>'pwd'
);
echo form_input($data_name);
?>
</div>
<div id="form_button">
<?php echo form_submit('submit','Submit','class="submit"');?>
</div>
<?php
echo form_close();
?>
</div>
</div>
</body>
</html>
controller : controllers/Ajax_controller.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Ajax_controller extends CI_Controller {
// Show view Page
public function index(){
$this->load->helper('form');
$this->load->helper('url');
$this->load->view("ajax_post_view");
}
// This function call from AJAX
public function submit() {
$data = array(
'username' => $this->input->post('name'),
'pwd'=>$this->input->post('pwd')
);
echo json_encode($data);
}
}
?>
KINDLY HELP ME THANKS IN ADVANCE
In the controller, set Access-Control-Allow-Origin at the top of your php script :
header('Access-Control-Allow-Origin: *');

validating answer submitted to database

<?php
include ("dbFunctions.php");
$query = "SELECT * FROM two_three";
$result = mysqli_query($link, $query);
mysqli_close($link);
?>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<link rel="stylesheet" href="CSS/main.css" type="text/css"/>
<link rel="stylesheet" href="CSS/easy.css" type="text/css"/>
<title> Easy Game 1 </title>
<center>
<h1> Easy Game 1 </h1>
<h2> Click the image the number of times to get the answer! </h2>
<div class="border_solid">
<div id="timer"></div>
</div>
<hr>
</center>
</head>
<body>
<center>
<form method="post" id="validate">
<div id="display"><script type="text/javascript">document.write(count);</script></div>
<img src="image/ufo.png" class="ufo" onclick="add()"><br>
<input type="button" class="submit" value="submit" name="submit"/>
</form>
</center>
<?php
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$questID = $row['two_three_id'];
$factor1 = $row['factor1'];
$factor2 = $row['factor2'];
$answer = $row['answer'];
?>
<div class="image-questionid"><u>Question <?php echo $questID; ?></u></div>
<div class="image-questionfactor1"><?php echo $factor1; ?></div>
<div class="image-betweenfactor">X</div>
<div class="image-questionfactor2"><?php echo $factor2; ?></div>
<div class="image-questionequals">= ?</div>
<?php
break;
}
}
?>
</body>
<script type="text/javascript">
var count = 0;
function add() {
count++;
document.getElementById('display').innerHTML = count;
}
var myVar = setInterval(function () {
myTimer()
}, 1000);
var d = 0;
function myTimer() {
document.getElementById("timer").innerHTML = d++;
}
</script>
</html>
So basically this is the code I've done so far, I'd like to do a validation to check the count after the user clicks on submit, and check the count with the database answer. Is there anyone out there who can help me out?
in the form use the method in tag form onsubmit ="validation". after you need to implement the validation method in javascript and make a ajax request (in validation) to another php form, in that php form u make the query to db and returning the number of click you need to do. o you need to implement jquery library.
function validation(){
$.ajax({
url: "your_php_requesting_to_db.php",
success: function(data){
if(data == numberofclicks){
return true;
}else{
return false;
}
}
});
}
Here is the new code, im new in this foro so i don't know how to put in a comment the code, im assumng you got the total clicks you need to do, answering your question of timmer here is a little bit of doc
http://www.w3schools.com/js/js_timing.asp
<?php
include ("dbFunctions.php");
$query = "SELECT * FROM two_three";
$result = mysqli_query($link, $query);
mysqli_close($link);
?>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<link rel="stylesheet" href="CSS/main.css" type="text/css"/>
<link rel="stylesheet" href="CSS/easy.css" type="text/css"/>
<title> Easy Game 1 </title>
<center>
<h1> Easy Game 1 </h1>
<h2> Click the image the number of times to get the answer! </h2>
<div class="border_solid">
<div id="timer"></div>
</div>
<hr>
</center>
</head>
<body>
<center>
<form method="post" id="validate" onsubmit="validate()">
<div id="display">
<script type="text/javascript">document.write(count);</script>
</div>
<img src="image/ufo.png" class="ufo" onclick="add()"><br>
<input type="hidden" id="totalClicks" value="<?php /*IF U GOT THE NUMBER OF CLIC FROM BD PUT IN THERE LIKE ECHO $NUMCLICKS */ ?>"/>
<input type="hidden" id="countClic" value="0" />
<input type="button" class="submit" value="submit" name="submit"/>
</form>
</center>
<?php
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$questID = $row['two_three_id'];
$factor1 = $row['factor1'];
$factor2 = $row['factor2'];
$answer = $row['answer'];
?>
<div class="image-questionid"><u>Question <?php echo $questID; ?></u></div>
<div class="image-questionfactor1"><?php echo $factor1; ?></div>
<div class="image-betweenfactor">X</div>
<div class="image-questionfactor2"><?php echo $factor2; ?></div>
<div class="image-questionequals">= ?</div>
<?php
break;
}
}
?>
</body>
<script type="text/javascript">
var count = 0;
function add() {
count++;
document.getElementById('display').innerHTML = count;
document.getElementById('countClic').value=count;
}
var myVar = setInterval(function () {
myTimer()
}, 1000);
var d = 0;
function myTimer() {
document.getElementById("timer").innerHTML = d++;
}
function validate(){
var totalClics = document.getElementById('totalClicks').value=count;
var clicksCount = document.getElementById('countClic').value=count;
if(totalClics == clicksCount){
return true;
}else{
return false;
}
}
</script>
</html>

Layout, Phonegap and JSON

I have an application to list the information via JSON db, I can list the information from db, the problem is that it comes without the layout of jQuery Mobile, could someone give me some light on how to solve this problem?
Below is my code:
HTML:
<!DOCTYPE HTML>
<html>
<head>
<title>Unidas Taxi</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="text/javascript" charset="utf-8" src="js/jquery-1.11.1.min.js"></script>
<script type="text/javascript" charset="utf-8" src="js/jquery.mobile-1.4.3.min.js"></script>
<link rel="stylesheet" type="text/css" href="js/jquery.mobile-1.4.3.css"/>
<script charset="utf−8" type="text/javascript">
var id_taxista = 1;
setInterval(function(){
//alert('oi');
corridas();
}, 3000);
$("#result").html("");
function corridas(){
$.post('url', {
'id_taxista': id_taxista
}, function (data) {
$("#result").html(data);
});
}
</script>
</head>
<body>
<div data-role="page" id="main">
<div data-role="header">
<h1>Unidas Taxi</h1>
</div>
<div id="content" data-role="content">
<ul data-role="listview" data-inset="true">
<li data-role="list-divider">Corridas <span class="ui-li-count">2</span></li>
<span id="result">
</span>
</ul>
</div>
</div>
</body>
</html>
PHP:
$server = "localhost";
$username = "username";
$password = "pass";
$database = "db";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$id_taxista = $_POST["id_taxista"];
$sql = "SELECT USED";
if (mysql_query($sql, $con)) {
$query = mysql_query($sql) or die(mysql_error());
$html = '';
while($row = mysql_fetch_assoc($query)){
$html .= '<li id="'.$row['id_corrida'].'">
<a href="index.html">
<h2>'.$row['nome'].' '.$row['sobrenome'].'</h2>
<p><strong>Hotal Ibis - Botafogo</strong></p>
<p>Quarto: 504, Tel.: (21) 0932-0920</p>
<p class="ui-li-aside"><strong>'.$row['data'].' '.$row['hora'].'</strong></p>
</a>
</li>';
}
echo $html;
} else {
die('Error: ' . mysql_error());
}
mysql_close($con);
If I understand your question correctly, you are able to return json full of data you want and display it in #result but the style doesn't have the jQuery Mobile style applied. If this is a correct summation
First, add an id to your listview element
<ul id="mylistview" data-role="listview" data-inset="true">
then add this line after $("#result").html(data);
$( "#mylistview" ).listview( "refresh" );
See the Listview Widget page for more on listviews.

Categories

Resources