I am trying to fix AJAX function to retrieve data from Wolfram Alpha API using the GET method in my form, but instead to transfering the data to the API handler file, the data is passed to the same page.
Below is the CODE, please tell me where I am going wrong, been stuck here for 3 days without any result: simpleRequest.php
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
function loadDoc()
{
var xmlhttp= window.XMLHttpRequest ?
new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
document.getElementById("demo").innerHTML = xmlhttp.responseText; // Here is the response
}
var query = document.getElementById('q').value;
var queryString = "?q="+query;
xmlhttp.open("GET","handle.php" + queryString, true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
Search:
<input type="text" name="q" id="q" value="
<?php
$queryIsSet = isset($_REQUEST['q']);
if ($queryIsSet) {
echo $_REQUEST['q'];
};
?>"
> <input type="submit" onclick="loadDoc()" name="Search" value="Search">
</form>
<br><br>
<hr>
<div id="demo"></div>
Here is the php file to handle the API calls from Wolfram Alpha and display the result: handle.php
<?php
include '../wa_wrapper/WolframAlphaEngine.php';
?>
<?php
$appID = 'APP_ID';
//if (!$queryIsSet) die();
$qArgs = array();
if (isset($_REQUEST['assumption']))
$qArgs['assumption'] = $_REQUEST['assumption'];
// instantiate an engine object with your app id
$engine = new WolframAlphaEngine( $appID );
// we will construct a basic query to the api with the input 'pi'
// only the bare minimum will be used
$response = $engine->getResults( $_REQUEST['q'], $qArgs);
// getResults will send back a WAResponse object
// this object has a parsed version of the wolfram alpha response
// as well as the raw xml ($response->rawXML)
// we can check if there was an error from the response object
if ( $response->isError() ) {
?>
<h1>There was an error in the request</h1>
</body>
</html>
<?php
die();
}
?>
<h1>Results</h1>
<br>
<?php
// if there are any assumptions, display them
if ( count($response->getAssumptions()) > 0 ) {
?>
<h2>Assumptions:</h2>
<ul>
<?php
// assumptions come as a hash of type as key and array of assumptions as value
foreach ( $response->getAssumptions() as $type => $assumptions ) {
?>
<li><?php echo $type; ?>:<br>
<ol>
<?php
foreach ( $assumptions as $assumption ) {
?>
<li><?php echo $assumption->name ." - ". $assumption->description;?>, to change search to this assumption click here</li>
<?php
}
?>
</ol>
</li>
<?php
}
?>
</ul>
<?php
}
?>
<hr>
<?php
// if there are any pods, display them
if ( count($response->getPods()) > 0 ) {
?>
<h2>Pods</h2>
<table border=1 width="80%" align="center">
<?php
foreach ( $response->getPods() as $pod ) {
?>
<tr>
<td>
<h3><?php echo $pod->attributes['title']; ?></h3>
<?php
// each pod can contain multiple sub pods but must have at least one
foreach ( $pod->getSubpods() as $subpod ) {
// if format is an image, the subpod will contain a WAImage object
?>
<img src="<?php echo $subpod->image->attributes['src']; ?>">
<hr>
<?php
}
?>
</td>
</tr>
<?php
}
?>
</table>
<?php
}
?>
</body>
</html>
Now whenever I click the search button, the GET data isn't passed to the handle.php instead, it is passed to the same page i.e simpleRequest.php as the url after clicking the search button shows: localhost/wolf/php/samples/simpleRequest.php?q=[StringToBeSearched]&Search=Search
Please tell where am I going worng, please keep in mind I am an AJAX beginner.
Related
Situation
I'm creating a custom Wordpress website where I want to show the most recent articles grouped by day and have it scroll infinitely when you've reached the bottom of your screen.
Problem
I don't know how to continue with the date you were on without breaking the layout.
I've seen many code that involve having infinite scroll, but none of them really worked for me since it also needs to match the design.
Here is the design:
The image pretty much explains what I need to create and so I've written the following code:
<div class="recent">
<?php
$args = array(
'posts_per_page' => -1,
'orderby' => 'date'
);
$myQuery = new WP_Query($args);
$date = '';
$postCount = 0;
$newDay = false;
if ( $myQuery->have_posts() ) : while ( $myQuery->have_posts() ) : $myQuery->the_post();
$postCount++;
if ( $date != get_the_date() ) {
if ( $postCount != 1 ) {
$newDay = false;
if (!$newDay) {
?></div><?php
}
?>
</div>
<?php
}
?>
<div class="recent__articles">
<?php
$newDay = true;
$date = get_the_date();
?>
<div class="recent__header">
<img class="header__icon" src="<?php echo get_home_url() ?>/wp-content/themes/insane/assets/images/time.svg" alt="time-icon">
<?php echo $date; ?>
</div>
<?php
if ($newDay) {
?>
<div class="articles__wrapper"><?php
}
}
?>
<div class="recent__article">
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
<figure class="article__image">
<?php if ( has_post_thumbnail() ) :
the_post_thumbnail();
else : ?>
<img src="<?php echo get_home_url() ?>/wp-content/themes/insane/assets/images/article-placeholder.png" alt="image-placeholder">
<?php endif ?>
</figure>
<div class="article__meta">
<span class="article__cat">
<?php
foreach((get_the_category()) as $category){
echo $category->name;
}
?>
</span>
<h2 class="article__title"><?php echo get_the_title() ?></h2>
<div class="article__date">
<?php echo esc_html( time_difference( get_the_time('U'), current_time('timestamp') ) ); ?>
</div>
</div>
</a>
</div>
<?php
endwhile; endif;
wp_reset_postdata();
?>
</div>
Top part where I check the date and increment the postCount is so I can group the articles of that day in separate div and style it accordingly.
Now all I need is to check wether I've reached the bottom and continue with where I left off.
Any help with the directions I need to be going is much appreciated.
Thank you!
I've fixed my problem in combination with the Ajax Load More plugin.
I hope this will help others facing the same problem as I did.
If anybody sees improvement in my code, I'd much appreciate it.
Tested on: MacOS - Chrome/Safari/Firefox & iOS - Chrome/Safari
I've installed the Ajax Load More plugin
They have a Repeat Templates section which is basically the while loop in php and I've added the following code (a bit stripped from what I've showed here above).
<?php $postCount++;
if ( $date != get_the_date() ) {
if ( $postCount != 1 ) {
$newDay = false;
if (!$newDay) {
?></div><?php
}
?>
</div>
<?php
}
?>
<div class="recent__articles">
<?php
$newDay = true;
$date = get_the_date();
?>
<div class="recent__header">
<img class="header__icon" src="<?php echo get_home_url() ?>/wp-content/themes/insane/assets/images/time.svg" alt="time-icon">
<?php echo $date; ?>
</div>
<?php
if ($newDay) {
?>
<div class="articles__wrapper"><?php
}
}
?>
<div class="recent__article">
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
<figure class="article__image">
<?php if ( has_post_thumbnail() ) :
the_post_thumbnail();
else : ?>
<img src="<?php echo get_home_url() ?>/wp-content/themes/insane/assets/images/article-placeholder.png" alt="image-placeholder">
<?php endif ?>
</figure>
<div class="article__meta">
<span class="article__cat">
<?php
foreach((get_the_category()) as $category){
echo $category->name;
}
?>
</span>
<h2 class="article__title"><?php echo get_the_title() ?></h2>
<div class="article__date">
<?php echo esc_html( time_difference( get_the_time('U'), current_time('timestamp') ) ); ?>
</div>
</div>
</a>
</div>
I've a .php file that I load in somewhere els that looks like this:
<div class="recent">
<?php
$date = '';
$postCount = 0;
$newDay = false;
echo do_shortcode("[ajax_load_more post_type='post' posts_per_page='2' scroll_distance='0']");
?>
</div>
Now for the last part I've written the following in jQuery:
// Ajax load more fix
function ajaxShowMore() {
var oldXHR = window.XMLHttpRequest;
function newXHR() {
var realXHR = new oldXHR();
realXHR.addEventListener("readystatechange", function() {
if (realXHR.readyState === 4) { // When the Ajax call is finished new content is loaded
var oldRecentHeaders = $('.recent__header'); // Store all previous recent headers in variable
setTimeout(function() { // Set a timeout, since it goes a bit to fast to store the data
var newRecentHeaders = $('.recent__header'); // Store all the headers in a variable
newRecentHeaders.splice(0, oldRecentHeaders.length); // Splice it, so you only get the new added headers
if (newRecentHeaders.first().text() === oldRecentHeaders.last().text()) { // Check if the first of new header date is the same as the last of the old header date
var newArticles = newRecentHeaders.first().parent().find('.articles__wrapper').children(); // Store all the articles
newRecentHeaders.first().parent().remove(); // Remove the first new added articles
oldRecentHeaders.last().parent().find('.articles__wrapper').append(newArticles); // Add them here
}
}, 10);
}
}, false);
return realXHR;
}
window.XMLHttpRequest = newXHR;
}
So for me this specific solution works, based on the classes and structure of my project I've set.
I hope this helps
I am a student studying Ajax to change the value of an input field generated with PHP DOM.
Here is the code that generates the table rows.
<?php
$totalval = 0;
foreach($_SESSION as $name=>$value){
$total = 0;
if(substr($name,0,5) == "item_"){
$id = substr($name,5,4);
$cart_xml= new DomDocument;
$cart_xml->Load('prod_db.xml');
$root=$cart_xml->getElementsByTagName('root')->item(0);
$product=$root->getElementsByTagName('product');
foreach($product as $prod){
$itms_id=$prod->getElementsByTagName('prod_id')->item(0)->nodeValue;
$itms_categ=$prod->getElementsByTagName('prod_categ')->item(0)->nodeValue;
$itms_imgsrc=$prod->getElementsByTagName('prod_imgsrc')->item(0)->nodeValue;
$itms_name=$prod->getElementsByTagName('prod_name')->item(0)->nodeValue;
$itms_price=$prod->getElementsByTagName('prod_price')->item(0)->nodeValue;
$itms_stock=$prod->getElementsByTagName('prod_stock')->item(0)->nodeValue;
if($id==$itms_id){
$price = floatval($itms_price);
$total=$price*$value;
?>
<tr>
<td><img src="<?php echo $itms_imgsrc?>" class="citemimg"/></td>
<td>
<p class="prodname"><?php echo ucfirst($itms_name);?></p>
<p class="prodcateg"><?php echo ucfirst($itms_categ)?></p>
<p class="prodprice"><?php echo "Php. ".number_format($itms_price,2)?></p>
</td>
<td class="cartAmount;">
<img onclick="ajaxMinus('<?php echo $itms_id;?>','<?php echo $itms_stock;?>')" class="carticons" src="images/logos/Minus_r_50px.png"/>
<input type="number" min="1" max="<?php echo $itms_stock;?>" class="cartqty" id="itmQty<?php echo $itms_id;?>" value="<?php echo $value; ?>" disabled>
<img onclick="ajaxAdd('<?php echo $itms_id;?>','<?php echo $itms_stock;?>')" class="carticons" src="images/logos/Add_r_50px.png"/>
</td>
<td><?php echo "Php. ".number_format($total,2);?></td>
<td>
<a href="cart_actionCart.php?del=<?php echo $itms_id;?>&maxval=<?php echo $itms_stock;?>">
<img class="carticons" src="images/logos/Remove_r_50px.png"/>
</a>
</td>
</tr>
<?php
}
}
$totalval+=$total;
}
}
?>
And I make my image tag clickable by adding
`onclick="ajaxMinus('<?php echo $itms_id;?>','<?php echo $itms_stock;?>')"`
And I add as well
`onclick="ajaxAdd('<?php echo $itms_id;?>','<?php echo $itms_stock;?>')"`
And here is my simple function for ajaxAdd
function ajaxAdd(id,maxqty){
if(window.XMLHttpRequest){
xhrAdd=new XMLHttpRequest();
}
else{
if(window.ActiveXObject){
try{
xhrAdd=new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){}
}
}
if(xhrAdd){
xhrAdd.onreadystatechange=minusQty;
xhrAdd.open("GET","cart_actionCart.php?add="+id+"&maxval="+maxqty,true);
xhrAdd.send();
}
else{
alert("Couldn't create an XMLHttpRequest");
}
}
function minusQty(){
if(xhrAdd.readyState == 4 && xhrMinus.staus == 200){
document.getElementById('itmQty'+id).value = xhrAdd.responseText;
}
}
This is working but my problem is the input value is not changing until I refresh the page, where is my problem? Any help is greatly appreciated.
Anything loaded in via AJAX will not have a listener unless the parent element was there in the first place.
As an example, I had a form HTML come through AJAX, and the datepicker would not work, until I changed the original code from this:
$('.datepicker').datepicker();
To this:
$("body").on("focusin", ".datepicker", function(){
$(this).datepicker();
});
Because body is there always, the listener now works. This will probably what your issue is too, so I suggest trying to adapt your listeners as above.
I have a problem. I checked tons of good answers and tried them. Some helped me a lot but I still can't solve my problem completely. Can someone please help me?
I have one text file with following lines:
123456789, c
123456790, c
123456791, c
123456792, d
I read and parse this text file using a PHP script:
$myusers = array();
$my_txt = file_get_contents('C:\xampp\htdocs\net\net1\conStats.txt');
$rows = explode("\n",$my_txt);
foreach($rows as $row => $data){
$row_data = explode(',',$data);
array_push($myusers,$row_data);
}
I can reach to the result of this php script with JS code below:
var userConStats = <?php echo json_encode( $myusers ) ?>;
for ( i = 0; i < userConStats.length-1; i++){
document.getElementById(userConStats[i][0]).innerHTML = userConStats[i][1];
}
with this; I filled the necessary html table for the first time. Everything is perfect.
The problem starts when I want this PHP to read text file every second and refresh the table elements according to the changes in the text file. PHP parse the text file only once and the changes in the text file won't change anything on the browser.
Maybe my approach to the problem was wrong I am not sure.
Any help will be appreciated. Thank you!
Complete code can be found below:
<?php
require 'connectionNetIndex2.php';
include 'txtPHP.php';
include 'userConStatUpdater.php';
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>2-NetIndex</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.0.js"></script>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
<body>
<h1>MY_TEST</h1>
<select name="OperationalMode">
<option value="">Normal</option>
<?php while($opMode = mysqli_fetch_assoc($opModes)) { ?>
<option value="<?php echo $opMode["operational_mode"]; ?>"><?php echo $opMode["operational_mode"]; ?></option>
<?php } ?>
</select>
<?php if(isset($Users)): ?>
<table>
<tr>
<td>IMSI</td>
<td>Connection Status</td>
<td>Profile</td>
</tr>
<?php foreach($Users as $user): ?>
<tr>
<td value="<?php echo $user["u_id"]; ?>"><?php echo $user["imsi"]; ?></td>
<td id="<?php echo $user['imsi'];?>" class="conStats"></td>
<td><form action="" method="POST">
<select id="profiles" name="Profiles" onchange="valueChanged()">
<option value="<?php echo $user["p_id"]; ?>"><?php echo $user["profile_name"]; ?></option>
<?php foreach($profiles as $PR): ?>
<option name="" value="<?php echo $PR["p_id"]; ?>"><?php echo $PR["profile_name"]; ?></option>
<?php endforeach; ?>
</select>
<input name="uid" type="hidden" value="<?php echo $user["u_id"]; ?>">
<!--<input type="submit" value="save">-->
</form>
</td>
</tr>
<?php endforeach; ?>
</table>
<?php endif; ?>
<script type="text/javascript">
function conStatUpdater(){
<?php
$myusers = array();
$my_txt = file_get_contents('C:\xampp\htdocs\net\net1\conStats.txt');
$rows = explode("\n",$my_txt);
foreach($rows as $row => $data){
$row_data = explode(',',$data);
array_push($myusers,$row_data);
json_encode( $myusers ) ;
}
?>
// pass PHP array to JavaScript array
//Dont refresh the elements.
var userConStats = <?php echo json_encode( $myusers ) ?>;
//test is function working every second?
//test result : YES
console.log(userConStats[0][1]);
for ( i = 0; i < userConStats.length-1; i++){
document.getElementById(userConStats[i][0]).innerHTML = userConStats[i][1];
}
}
setInterval(conStatUpdater, 1000);
</script>
</body>
</html>
Like you've realized, PHP can't update an HTML page after it's been generated (unless you reload the page). You can only do that with JavaScript. In order to get the data every second, you'd need to use ajax (https://www.w3schools.com/xml/ajax_intro.asp) to make asynchronous calls every second to your PHP page to get the data. So you'd need something like this:
PHP:
$myusers = array();
$my_txt = file_get_contents('C:\xampp\htdocs\net\net1\conStats.txt');
$rows = explode("\n",$my_txt);
foreach($rows as $row => $data){
$row_data = explode(',',$data);
array_push($myusers,$row_data);
}
print json_encode($myusers);
Your JavaScript code:
function updatePage(userConStats) {
for ( i = 0; i < userConStats.length-1; i++){
document.getElementById(userConStats[i][0]).innerHTML = userConStats[i][1];
}
}
var secondPerRequest = 1;
setInterval(function() {
$.ajax({
url: "<your php page>",
success: function(result) {
var resultAsObject = JSON.parse(result);
updatePage(resultAsObject);
}
});
}, secondsPerRequest * 1000);
Note that I used jQuery to do the ajax call because it's simpler that way. If you don't want to use jQuery, you can find info on how to do ajax in vanilla JS here: How to make an AJAX call without jQuery?
the <?php ... ?> block script inside your conStatUpdater() javascript function will not re-executed on the server-side because it is already parsed and will only yield the same result.
what you need is an AJAX function that will call your php script, in which that php script will re-executed on server-side and respond you with an updated values on your text files.
I have a div with an ID of intro, i want to append a div containing php that will give me data from my database when i clicked a button. i have successfully append <li> successfully but when I want to append a div containing php it wont append.
<div class="container" id="article">
<button id="addArticle()" onClick="addArticle()">+</button>
<div class="section" id="intro">
<?php
require_once("dbconfig.php");
$query = mysqli_query($koneksi, "SELECT * FROM content WHERE id=1");
while($row = mysqli_fetch_array($query))
{ ?>
<?php echo $row['content']; ?>
<?php
}
?>
</div>
<div class="section" id="usage">
<?php
require_once("dbconfig.php");
$query = mysqli_query($koneksi, "SELECT * FROM content WHERE id=2");
while($row = mysqli_fetch_array($query))
{ ?>
<?php echo $row['content']; ?>
<?php
}
?>
</div>
</div>
Code that I want to append when I click the + button:
<div class="section" id="intro">
<?php
require_once("dbconfig.php");
$query = mysqli_query($koneksi, "SELECT * FROM content WHERE id=8");
while($row = mysqli_fetch_array($query))
{ ?>
<?php echo $row['content']; ?>
<?php
}
?>
</div>
Javascript:
function addArticle(){
$('#article').append('<li>tes2</li>');
}
PHP has already done in server side before the page send to you.
In your case, you may try to use AJAX.
I did a simple example for you, but you need to make it fit to your solution.
view.php
<html>
<head>
<script>
function showContent()
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
document.getElementById("paragraph").innerHTML = this.responseText;
}
}
xmlhttp.open("GET","content.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
Name : <span id="paragraph"></span>
<br /><br />
<button onclick="showContent()">Show me</button>
</body>
</html>
content.php
<?php
echo "milan";
?>
Hope it help ;)
I need help to display result a sum of values of a json file that's like this:
http://www.base.gov.pt/base2/rest/contratos?&sort(-publicationDate)
I have this code in php to do that:
(name of this file: estat.php)
<?php
//include "sum.php";
$x="active";
$y='';
if(isset($_GET['tabsoft'])){
$y="active";
$x="";
}
?>
<html>
<?php include 'cab.php'; ?>
<body>
<?php include 'menu.php'; ?>
<div class="container">
<div calss="row">
<ul id="tabs" class="nav nav-tabs" data-tabs="tabs">
<li class="<?php echo $x ?>">Valor Total Gasto</li>
<li class="<?php echo $y ?>">NĂºmero de Empresas Envolvidas</li>
</ul>
<div id="my-tab-content" class="tab-content">
<div class="tab-pane <?php echo $x ?> " id="val">
<p>
<form>
<h2>Dinheiro gasto nos contratos</h2>
<input type="submit" name="soma" value="Somar Valores" class="btn btn-primary" formaction="action_sum.php"/>
<!-- <p><?php echo $total; ?></p> -->
</form>
</p>
</div>
<div class="tab-pane <?php echo $y ?> " id="emp">
</div>
</div>
</div>
</div>
<?php include 'rodape.php';?>
</body>
</html>
And i need to display the sum value of 'initialContractualPrice' from the json file, to do this i write this code in other file that i name sum.php:
<?php
// Get json from url
$json = file_get_contents("file.json");
// Decode json into an array
//$json = json_decode($content, true);
$data = json_decode($json, TRUE);
// Set default
global $total;
// Loop through the array created when decoding json
foreach ($data as $key)
{
// remove symbol from the end leaving only digits
$value = substr(utf8_decode($key['initialContractualPrice']), 0, -1);
// remove the decimal point
$value = str_replace('.', '', $value);
// replace the comma with a decimal point
$value = str_replace(',', '.', $value);
// add this number to the total value
$total += $value;
}
//echo $total;
?>
My question is how can i do for the page do the sum without redirect to the sum.php but do it and print the result in estat.php
I can change the type of sum.php to js or jquery if are more easy to do that.
Thank you very much.
as you did, include your sum.php at the beggining of your file estat.php. Hide the sum value with css.
<input id="sum-btn" type="submit" name="soma" value="Somar Valores" class="btn btn-primary" formaction="action_sum.php"/>
<p id="sum"><?php echo $total; ?></p>
css:
#sum {
display:none;
}
and with jQuery (as you tag it) put a click handler on your button:
<script>
$(document).ready(function() {
$('#sum-btn').click(function() {
$('#sum').show();
});
});
</script>
FIDDLE DEMO
Alternative, if you dont want to calculate the sum when the page is loaded, you can call your sum.php with an AJAX call when the button is clicked.
<script>
$(document).ready(function() {
$('#sum-btn').click(function() {
var request = $.ajax({
url: "sum.php",
type: "GET"
});
request.done(function( value ) {
$('#sum').text( value );
$('#sum').show();
});
request.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
});
});
</script>
and in sum.php, echo $total; at the end.