I need a script that can show results form my database dynamically. I found a method here: http://openenergymonitor.org/emon/node/107
My question is how to alter the code so that it will show all results instead of only one?
And is it possible to display all results on load and then add newly added lines afterwards?
I tried the following on the client.php:
<html>
<head>
<script language="javascript" type="text/javascript" src="http://code.jquery.com/jquery-1.4.4.js"></script>
</head>
<body>
<h2> Client example </h2>
<h3>Output: </h3>
<div id="output">Henter data.</div>
<script id="source" language="javascript" type="text/javascript">
$(function ()
{
setInterval(function() { $.ajax({
url: 'api.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
var id = data[0]; //get id
var vname = data[1]; //get name
$('#output').append("<b>id: </b>"+id+"<b> name: </b>"+vname+"<br />"); //Set output element html
//recommend reading up on jquery selectors they are awesome
// http://api.jquery.com/category/selectors/
}
}); }, 1000);
});
</script>
</body>
</html>
And this is what I tried on the api.php page:
$result = mysql_query("SELECT * FROM $tableName ORDER BY id DESC");
while($row = mysql_fetch_assoc($result)){
echo json_encode($row);
}
Now it won't show anything. What am I doing wrong?
Thank you!
Related
I'm trying to do something I would think would be really simple: Pass form data to a PHP page with AJAX, and get the result of the PHP back.
Edited to Add: As written right now, it only returns successfully sporadically, rather than every time it's run, for some reason.
Edited to Add (05/30/2020):
I was able to get it working such as it is by changing the ajax like this:
<script>
$(document).ready(function(){
$("#button").click(function(){
var DDD_Number=$("#DDD_Number").val();
var Manager_Review=$("#Manager_Review").val();
var dataTosend='?DDD_Number='+DDD_Number+'&Manager_Review='+Manager_Review;
$.ajax({
type: "GET",
url:'showme.php' + dataTosend,
data:dataTosend,
async: false,
success:function(data){
document.getElementById('txtresponse').innerHTML = "Success.";
document.getElementById('thisworks').innerHTML = data;
},
error: function(data){
document.getElementById('txtresponse').innerHTML = "failure.";
}
});
});
});
</script>
Now I have to work on serializing the form, because it's actually multiple rows I have to pass. I don't know if I need that as a second question, though.
This is my main page:
<html>
<head>
<script src="Scripts/jquery.min.js"></script>
<script src="Scripts/jquery-2.1.3.min.js"></script>
<script type="text/javascript" src="Scripts/jquery.plugin.min.js"></script>
<script type="text/javascript" src="Scripts/jquery.datepick.min.js"></script>
<script>
$(document).ready(function(){
$("#button").click(function(){
var DDD_Number=$("#DDD_Number").val();
var Manager_Review=$("Manager_Review").val();
var dataTosend='DDD_Number='+DDD_Number+'&Manager_Review='+Manager_Review;
$.ajax({
type: "POST",
url:'showme.php',
data:dataTosend,
async: true,
success:function(data){
document.getElementById('txtresponse').innerHTML = "Success.";
document.getElementById('thisworks').innerHTML = "Successful.";
},
error: function(data){
console.log(data);
document.getElementById('txtresponse').innerHTML = "failure.";
console.log(data);
}
});
});
});
</script>
</head>
<body>
<form id="dddform" method="post">
<input type="text" id="DDD_Number" name="DDD_Number"><br>
<input type="text" id="Manager_Review" name="Manager_Review"><br>
<button id="button" name="Submit">Click Me</button>
</form>
<div id="txtresponse"></div>
<div id="thisworks"><?php if(!isset($_POST['Submit'])){echo $Manager_Review;} ?></div>
</div>
</body>
</html>
This is showme.php:
<?php
$Manager_Review_Date = $_POST['Manager_Review'];
echo $Manager_Review_Date;
?>
<script language = 'Javascript'>
document.getElementById('thisworks').innerHTML = '<?php echo $Manager_Review_Date; ?>';
</script>
The call is made successfully. (The "Success"and "Successful" messages appear), but I can't get the value of $Manager_Review_Date to appear in the "thisworks" DIV.
Any pointers? I'm fairly new to AJAX (if you couldn't tell from my code).
Your php should be:
<?php
$Manager_Review_Date = $_POST['Manager_Review'];
echo $Manager_Review_Date;
// NO javascript here
And the output of this script is in data variable of success callback:
success:function(data){
document.getElementById('txtresponse').innerHTML = "Success.";
document.getElementById('thisworks').innerHTML = data;
},
I have a hard time finding my mistake in this code. I have a search bar and I'd use ajax so that the data will fetch automatically.
This is my html file.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="bootstrap4/jquery/jquery.js"></script>
<script>
function loadproducts()
{
var name = document.getElementById("search");
if(name)
{
$.ajax({
type: 'post',
contentType:false,
cache: false,
processData:false,
data: {
products:name,
},
url: 'loadproducts.php',
success: function (response){
$('#product_area').html(response);
}
});
}
else
{
$('#product_area').html("No Product found!");
}
}
</script>
</head>
<body>
<input type="text" name="search" id="search" onkeyup="loadproducts();">
<div id="product_area">
</div>
</body>
</html>
----------
This is my loadproducts.php file
<?php
include('server/connection.php');
if (isset($_POST['products'])){
$name = mysqli_real_escape_string($db,$_POST['products']);
$show = "SELECT product_name,sell_price FROM products WHERE product_name LIKE '$name%' ";
$query = mysqli_query($db,$show);
if(mysqli_num_rows($query)>0){
while($row = mysqli_fetch_array($query)){
echo "<p>".$row['product_name']."</p>";
echo "<p>".$row['sell_price']."</p>";
}
}
}
Ill tried putting alert("called"); function on the ajax success and the alert is activated but still no output show. I also edit the var name = document.getElementById("search"); to var name = document.getElementById("#search"); but it pass straight to the else statement.Can someone site the problem of this code?
Currently, you're accessing the actual HTML element. You want the value, so use .value:
var name = document.getElementById("search").value;
Or if you prefer, you can simplify this down with jQuery:
var name = $("#search").val();
I have a problem with send data to php. I want to send button value via jquery ajax. This is my code:
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.ajax({
url: "try.php",
type: "POST",
data: {
data: val // removed ; after val.
}
});
});
</script>
<body>
<button id="1" name="1" value="some_value">1</button>
<button id="2" name="2" value="some_value">2</button>
</body>
PHP:
<?php
$name = $_POST['data'];
echo $name;
?>
It doesn't working...
try this out, i just did and worked fine
here's my js file
<html>
<head>
</head>
<body>
<button id="1" name="1" value="some_value">1</button>
<button id="2" name="2" value="some_value">2</button>
</body>
<footer>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('button').click(function() {
var val = $(this).val();
$.ajax({
// your uri, pay attention if the post is going to the right place
url: "try.php",
type: "POST",
// myVar = name of the var that you will be able to call in php
// val = your data
data: {'myVar': val}
});
});
});
</script>
</footer>
</html>
and here's my php
<?php
$name = $_POST['myVar']; //the var you put in your ajax data:{}
print_r($name);
in google chrome you can press f12 and go to Network Tab, you will be able to see the requisitions that your browser made and theirs responses
Make proper json string to send data. You are having extra ; there.
$(document).ready(function(){
$.ajax({
url: "try.php",
type: "POST",
data: {
data: val // removed ; after val.
}
});
});
And get it with data key in php.
<?php
$name = $_POST['data'];
echo $name;
?>
Also, write your event listeners inside document.ready(). Currently your listeners are not getting applied as the script is on the top and is not able to find the <button> as they are not yet present.
<button id="example" name="name_example" value="some_value">
1</button>
$(document).ready(function () {
$('#example').click(function() {
var buttonValue = $(this).val();
$.ajax({
url: "try.php", //assuming that your html file is in the same folder as
//your php script.
type: "POST",
data: {'example': buttonValue}
});
});
});
look this: https://jsfiddle.net/willianoliveirac/yarLfdnu/
In your .php file, which should be in the same folder as your html file doing the request you will have:
<?php
echo '<pre>'; print_r($_POST); die; // see if you now have those vars.
?>
I'm trying to pass a variable from my jQuery code to my HTML/PHP code using AJAX and POST, but I get the error message "Notice: Undefined index: testData in C:\xampp\htdocs\teszt\test1.php on line 9".
I'm using XAMPP, I'm running the code in localhost, I'm using Mozilla Firefox and here's my HTML/PHP code (test1.php):
<!DOCTYPE html>
<html lang="hu">
<head>
<title>Test</title>
<meta http-equiv="Content-type" content="text/html;charset=utf-8">
</head>
<body>
<?php echo "<p class='testParagraph'>" . $_POST['testData'] . "</p>";?>
<script src = "http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
And here's my jQuery code (script1.js):
$(document).ready(function() {
var temporaryVariable = "temporary variable";
$.ajax({
type: "POST",
url: "test1.php",
data: { testData:"2" },
success: function (result) {
alert('success');
}
}).done(function() {
$('.testParagraph').addClass( temporaryVariable );
});
});
What I tried changing so far (but didn't work of course):
test1.php:
charset was previously iso-8859-2
GET instead of POST in both codes
commenting out the script tag includes
script1.js:
commenting out the $(document).ready(function() {... lines
in data: I tried changing the quote symbols from ' to " or no quote symbols at all
commenting out the success: function... line and the two lines below it
Also, when I run the PHP code, the p tag gets the temporaryVariable class from the jQuery code.
Still, I get the error message written above. I would appreciate any help I get.
Change your test1.php to:
<!DOCTYPE html>
<html lang="hu">
<head>
<title>Test</title>
<meta http-equiv="Content-type" content="text/html;charset=utf-8">
</head>
<body>
<p id='testParagraph'> </p> <!-- You receive the value by jquery not from PHP. -->
<script src = "http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
And your script1.js to:
$(document).ready(function() {
var temporaryVariable = "temporary variable";
$.ajax({
type: "POST",
url: "test1.php",
data: { testData:"2" },
success: function (result) {
alert('success');
}
}).done(function() {
$('#testParagraph').html(temporaryVariable); //The value is inserted into the paragraph.
});
});
Hope works for you.
Unless you are getting the php page from a post request, using $_POST['testData'] will be of no use and will always give an index not found error. If you want to set the value in the p tag from jquery, you could use $('.testParagraph').html( temporaryVariable ) instead of .addClass
Use data : 'testData=2',
Instead of data : {testData:"2"},
Notice: Undefined index: testData in C:\xampp\htdocs\teszt\test1.php
on line 9
means your
data: { testData:"2" },
is wrong.
Didn't test it, but this should work:
data: [ testData:"2" ],
because $_POST is an Array
It sounds like you're posting test1.php to itself, and it's not clear why you would do that.
As #Rasclatt has pointed out in the comments check to see if the data exists before you try to access it.
Change:
<?php echo "<p class='testParagraph'>" . $_POST['testData'] . "</p>";?>
To:
<?php
if( isset( $_POST['testData'] ) ) {
echo "<p class='testParagraph'>" . $_POST['testData'] . "</p>";
}
?>
If, however, test1.php is a different script altogether then make the following changes:
Include a placeholder for the ajax content in your HTML:
<p class="tetParagraph"></p>
Trim and edit your JavaScript to the following:
$(document).ready(function() {
var tempVal = "temporary variable";
$.ajax({
type: "POST",
url: "test1.php",
data: { testData:"2" },
success: function (result) {
tempVal = result;
$('.testParagraph').html( tempVal );
alert('success');
}
});
});
I need to do the following:
Catch a URL pasted into a simple HTML text box on the paste event and save to a JavaScript variable called myURL (this code works)
Send the myURL variable using AJAX to a PHP page that will scrape some content from the URL. The PHP page (webscraper.php) will save the scraped content in the database and then also display the scraped content on the HTML page (where the text box is) without reloading the page. And this step is where the code is missing and broken.
index.html:
<body>
<input type="text" class="newslinkinput"/>
</body>
URLonpaste.js:
$(document).ready(function () {
$(".newslinkinput").bind('paste', function (e) {
setTimeout(function () {
var myURL = $(".newslinkinput").val()
$.ajax({
type: "POST",
url: "webscraper.php",
data: "newslink=" + myURL.val(),
success: function (data) {}
});
}, 0);
});
});
webscraper.php:
<?php
$newslink = $_POST['newslink'];
require_once('ExternalScraper.php');
$result = ExternalScraper::fetch($newslink);
$contentA = $result->contentA;
$contentB = $result->contentB;
include "include/database.php";
$insert = mysqli_query($connect, "INSERT INTO mytable (contentA, contentB) VALUES ('$contentA', '$contentB')");
mysqli_close($connect);
//Somehow get $contentA and $contentB to display on index.html
//Do all this without refreshing the page
?>
Try this:
index.html:
<body>
<input type="text" class="newslinkinput"/>
<div id="contentA"></div>
<div id="contentB"></div>
</body>
URLonpaste.js:
...
$.ajax({
type: "POST",
url: "webscraper.php",
data: "newslink=" + myURL.val(),
dataType: "json",
success: function (data) {
$('#contentA').html(data.contentA);
$('#contentB').html(data.contentB);
}
});
...
webscraper.php (append to the end):
...
echo json_encode(array('contentA' => $contentA, 'contentB' => $contentB));