How to pass data from Javascript to PHP using ajax - javascript

I am working on to receive data in JSON format from a remote server and save it into database. The remote server updates the data each one minutes.
I have written a JavaScript program that receives the jason data from the remote server. Now the problem is I am not able to pass this data to PHP file to be saved in database.
I tried the solution from same threads on stackoverflow but those do not work so far.
I am trying to print the data received from the js in php to find if data is received. The code I have written runs, but nothing happens. It shows no error when pressing F12.
Here is my code. What is wrong I am doing in it.
EDIT
One more problem I figured out is it's not printing the echo. That mean if I try to simply echo "test";, it doesn't print anything. I add full code under to see how/where I am using echo to print the results. Why echo don't get print ?
Javascript:
<script>
var humArray = [];
var temArray = [];
var N = 24;
for (i = 0; i < N; i++) {
humArray.push(0);
temArray.push(0);
}
function loadChart() { //fetches json data & calls dspChart() to render graph
var wData, hum, tem;
var requestURL = 'https://cors.io/?http://api.holfuy.com/live/?s=759&pw=h1u5l4kka&m=JSON&tu=C&su=m/s'; //URL of the JSON data
var request = new XMLHttpRequest({
mozSystem: true
}); // create http request
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
wData = JSON.parse(request.responseText);
hum = wData.humidity;
tem = wData.temperature;
humArray.shift();
humArray.push(hum);
temArray.shift();
temArray.push(tem);
//dspChrt(humArray, temArray);
$.ajax({
url: 'index.php',
type: 'GET',
data: { temArray : temArray, humArray : humArray },
success: function (data) {
console.log( data );
},
error: function (data) {
console.log(data);
},
});
}
}
request.open('GET', requestURL);
request.send(); // send the request
//dspChrt(hum);
}
var myVar = setInterval(loadChart, 60000);
</script>
index.PHP
<?php
if (isset($_GET['data']))
{
$WData = $_GET['data'];
$Humidity = data.humArray;
$Temprature = data.temArray;
echo "Hum".$Humidity."Temp".$Temprature;
}
?>
FULL CODE
<div class="container">
<div class="row">
<div class="col-sm" style="background-color: #FFFFFF">
<h2 style="color:#B93B8F;">Data from JS</h2>
<?php
$servername = "localhost";
$username = "postgres";
$password = "test123";
$dbname = "testDB";
class TableRows extends RecursiveIteratorIterator {
function __construct($it) {
parent::__construct($it, self::LEAVES_ONLY);
}
function current() {
return "<td style='width:150px;border:1px solid grey;'>" . parent::current(). "</td>";
}
function beginChildren() {
echo "<tr>";
}
function endChildren() {
echo "</tr>" . "\n";
}
}
?>
</div>
<?php
if (isset($_GET['data']))
{
$WData = $_GET['data'];
$Humidity = $WData.humArray;
$Temprature = $WData.temArray;
echo "Hum".$Humidity."Temp".$Temprature;
}
?>
<h2>JS Update</h2>
<div>
<canvas id="myChart"></canvas>
</div>
<div class="col-sm" style="background-color: #FFFFFF">
<?php
echo "<h3>WeatherData</h3>";
echo "<table class='table table-hover table-bordered table-reponsive'>";
echo "<thead class='table-dark'>";
echo "<tr><th>humidity</th><th>temprature</th></tr>";
try {
$conn = new PDO("pgsql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT humidity, temprature FROM weatherdata");
$stmt->execute();
// set the resulting array to associative
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
echo $v;
}
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
echo "</thead'>";
echo "</table>";
?>
<div id="form">
<div id="login">
<form action="" method="post">
<input type="text" name="humidity" id="humidity" required="required" placeholder="Enter humidity"/>
<input type="text" name="temprature" id="monikulmio_gps" required="required" placeholder="Enter temprature"/>
<input type="submit" value="Insert" name="submit12"/><br />
</form>
<hr/>
</div>
<?php
if(isset($_POST["submit12"])){
try {
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
$sql = "INSERT INTO weatherdata (humidity, temprature)
VALUES ('".$_POST["humidity"]."','".$_POST["temprature"]."')";
echo "<meta http-equiv='refresh' content='0'>";
if ($conn->query($sql)) {
echo "<script type= 'text/javascript'>alert('New Record Inserted Successfully');</script>";
}
else{
echo "<script type= 'text/javascript'>alert('Data not successfully Inserted.');</script>";
}
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
$conn = null;
?>
</div>
</div>
</div>
</div>
</div>
</body>

in your php you are checking if isset $_GET['data'] but it will always fail. You don't send data you send temArray and humArray. So use isset on $_GET['humArray'] or $_GET['temArray']
So your code will be:
<?php
if (isset($_GET['humArray'])){
$Humidity = $_GET['humArray'];
$Temprature = $_GET['temArray'];
echo "Hum".$Humidity."Temp".$Temprature;
}
?>
I also assume that:
your js is sending data to php.
even if you say humArray and temArray you are fetching just variables and not arrays.
if these are arrays you need to do (instead of using echo):
print_r($Humidity);
print_r($Temprature);

Try to separate your code into at least two files:
index.php - with html and javascript;
fetchWeatherRequest.php - with code below.
Update your javascript code with:
$.when( $.ajax({
type: 'POST',
url: 'fetchWeatherRequest.php',
dataType: 'json'
})
).then( function( response ) {
// Code so render results on index.php;
});
fetchWeatherRequest.php:
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://cors.io/?http://api.holfuy.com/live/?s=759&pw=h1u5l4kka&m=JSON&tu=C&su=m/s",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"Cache-Control: no-cache"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
// Here code to save $response into database;
echo $response;
}

Related

how to get updated table values while the php page is running

I'm developing a website using php. I have some problems. I want to know know how to get modified table values while running the php page without refreshing the page.
<html>
<?php
function fun_get_user_name() {
$host_name = "localhost";
$db_user_name = "root";
$password = "";
$database_name = "database_name";
$connect = mysqli_connect($host_name, $db_user_name, $password, $database_name);
$query = "SELECT * FROM `users` ";
$result = mysqli_query($connect, $query);
$output = "";
while ($row = mysqli_fetch_array($result)) {
$output = $output."<br/>"..$row[0];
}
}
?>
<script>
function js_function() {
result = "<?php echo fun_get_user_name; ?>";
document.getElementById('div_body_users').innerHTML = result;
}
window.setInterval(function() {
js_function();
}, 1000);
</script>
<body>
<div id="div_body_users">
</div>
</body>
</html>
when I made a change in phpmyadmin table the change didn't affect the page. But I expected the updated table.
So move the fun_get_user_name to another file and then in a setInterval do a n ajax call to that file.
$.get( "users.php", function( data ) {
$( ".result" ).html( data );
alert( "Load was performed." );
});
For more info on ajax request look at this link
https://api.jquery.com/jquery.get/
On user.php you just need to add fun_get_user_name
You can do it with using ajax, here changed with your ajax url and database connection details.
<html>
<?php
function fun_get_user_name()
{
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
$sql = "SELECT * FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}
}
if($_GET['ajax']==1){
$data=fun_get_user_name();
echo $data;
exit(0);
}
?>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script>
$(document).ready(function(){
setInterval(js_function,1000);
function js_function()
{
$.ajax({
url: "http://localhost/test2/test.php?ajax=1",
data: '',
cache: false,
processData: false,
contentType: false,
type: 'POST',
success: function (result) {
document.getElementById('div_body_users').innerHTML=result;
}
});
}
});
</script>
<body>
<div id="div_body_users">
</div>
</body>
</html>
You for update page without page refresh you have to use AJAX along with setInterval function.
Please check below link
https://www.w3schools.com/asp/asp_ajax_intro.asp

How to pass PHP variables along with a Typeahead variable

I have cut this down to be a simple as possible. I create a typeahead variable that works perfectly.
but I need to pass two other variables $php_var1 and $php_var2 that are unrelated to the typeahead. The PHP variables are defined in
start.php. The typeahead script calls search_script.php then calls cart.php. cart.php is were I will need the two PHP variables to
be passed to. Thanks in advance for any help
start.php
<?php
$php_var1 = "my php variable 1";
$php_var2 = "my php variable 2";
?>
<script>
$(document).ready(function() {
var php_var1 = <?php echo $php_var1; ?>;
var php_var2 = <?php echo $php_var2; ?>;
$('#my_input').typeahead({
source: function(query, result) {
$.ajax({
url: "search_script.php",
method: "POST",
data: {
query: query
},
dataType: "json",
success: function(data) {
result($.map(data, function(item) {
return item;
}));
}
})
},
updater: function(item) {
location.href = 'cart.php?shop_name=' + item
return item
}
});
});
</script>
<form action="cart.php" action="post">
<input type="text" id="my_input" placeholder="Typeahead Search" />
</form>
search_script.php
<?php
$php_var1 = isset($_REQUEST['php_var1']) ? $_REQUEST['php_var1'] : "empty";
$php_var2 = isset($_REQUEST['php_var2']) ? $_REQUEST['php_var2'] : "empty";
$connect = mysqli_connect($servername, $username, $password, $dbname);
$request = mysqli_real_escape_string($connect, $_POST["query"]);
$query = " SELECT * FROM all_shops WHERE p_shop_name LIKE '%".$request."%'";
$result = mysqli_query($connect, $query);
$data = array();
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
$data[] = $row["p_shop_name"];
}
echo json_encode($data);
}
?>
cart.php
$php_var1 = isset($_REQUEST['php_var1']) ? $_REQUEST['php_var1'] : "empty";
$php_var2 = isset($_REQUEST['php_var2']) ? $_REQUEST['php_var2'] : "empty";
echo $php_var1;
echo $php_var2;
?>
You need quotes around the php output in order to generate javascript strings
var php_var1 = "<?php echo $php_var1; ?>";
var php_var2 = "<?php echo $php_var2; ?>";
Stackoverflow is an excellent resource, but sometimes you don't get the answer, so you need to persevere and keep trying. I worked on this all day yesterday and just couldn't figure it out. Woke up this AM and it came to me. The answer is as follows. In the typeahead script change the following line
location.href = 'cart.php?shop_name=' + item
to
location.href = 'cart.php?shop_name=' + item + '&php_var1=<?php echo $php_var1 ?>' + '&php_var2=<?php echo $php_var2 ?>'

PHP running AJAX script works only once

I have this strange issue, happening to my PHP script, On page load the AJAX script runs and also after the second time the AJAX script runs it works and sends data to PHP, but i seem to not understand why the PHP script doesn't process the incoming POST request the second time it is sent in when i clean the input text box and type again, i get a blank response.My code for more expatiation.
index.php :
<input type="text" onkeyup="searchmedia(this)" placeholder="Search for seller with UNIQUE ID or Name.">
<div id="resut" style="margin-top:-24px!important;">
//where the ajax result is returned
</div>
<div style="margin-top:-24px!important;" id="normal">
//bla bla data here
</div>
<div id="hui" style="display:none;"><img src="../ajax5.gif">
</div>
<script>
function searchmedia(e) {
var tuq = $(e).val();
if (tuq == "") {
$('#resut').hide();
$('#normal').show();
$('#hui').hide();
} else {
$('#normal').hide();
$('#hui').show();
$.ajax({
type: 'POST',
url: 'sellersmessageajax.php',
data: {tuq: tuq},
timeout: 5000,
cache: false,
success: function (r) {
//console.log(r);
$('#resut').html(r);
$('#normal').hide();
$('#hui').hide();
},
error: function () {
alert("Could not search, reload the page and try again.");
$('#normal').show();
$('#hui').hide();
}
});
}
}
</script>
sellersmessageajax.php :
<?php include('../connect.php'); ?>
<?php
if (isset($_POST['tuq']))
{
$term = $_POST['tuq'];
$term = mysqli_real_escape_string($con,
$term); //WHEN I ALERT HERE THE SECOND TIME I SEE THE INPUT TEXT DATA THAT CAME IN BUT PLEASE CHECK AFTER THE **FOREACH**
$condition = '';
$query = explode(" ", $term);
foreach ($query as $text)
{
$condition .= "name LIKE '%" . mysqli_real_escape_string($con,
$text) . "%' OR reign_uniqeer LIKE '%" . mysqli_real_escape_string($con, $text) . "%' OR ";
}
//WHEN I ALERT HERE I GET NOTHING
$condition = substr($condition, 0, -4);
$zobo = "ORDER BY name";
$sql_query = "SELECT * FROM sellers_login WHERE " . $condition . $zobo;
$result = mysqli_query($con, $sql_query);
if (mysqli_num_rows($result) > 0)
{
while ($row = mysqli_fetch_array($result))
{
$v_ida = $row['id'];
$v_namea = $row['name'];
$v_reign_uniqeera = $row['reign_uniqeer'];
?>
<div style="border-bottom:0.1px solid #eee;padding-bottom:20px;margin-top:20px;">
<a class="zuka" title="<?php echo $v_ida ?>" id="<?php echo $v_ida ?>"
style="color:#666;text-decoration:none;outline:none!important;cursor:pointer;">
<b style="color:blue;"><?php echo $v_namea ?></b>
<br/>
<div style="height:auto;max-height:30px;">
<b>UNIQUE ID :</b> <b style="color:red;"><?php echo $v_reign_uniqeera ?></b>
</div>
</a>
</div>
<?php
}
}
else
{
?>
<h1 class="zuka" style="text-align:center;margin-top:20%;"> No result found.</h1>
<?php
}
}
?>
Second time after clearing the data result set to hide. second time data is returning but it's hide
Add this line in ajax success block
$('#resut').show(); // Add this line
you are sending the var tuq wrongfully. Try this:
data : {"tuq": tuq}

I can not display the data from my json_encode ($.each)

Hello to every one and thank you for your time.
My problem is that i can not display the json_encode from my php database but in my chrome the data is appear.
The $.each is not dispaly all only one
enter image description here
now the code for the php :
comment.php
$data = $_REQUEST;
$photo_id =38;//$data['photo_id_comment'];
$con = mysqli_connect('localhost','root','','gallery');
$sql = "SELECT * FROM comments";
$sql .= " WHERE photo_id = " . $database->escape_string($photo_id);
$sql .= " ORDER BY photo_id ASC";
$result = mysqli_query( $con,$sql);
$arr = array();
$row_count = mysqli_num_rows($result);
while ($row = mysqli_fetch_array($result)) {
array_push($arr , $row);
}
mysqli_close($con);
echo json_encode($arr);
And the ajax to retrieve data is: script.js
function refreshComment() {
requestData = $("#photo_id_comment").serialize();
$.ajax({
url: "http://localhost/udemy/app_php/includes/comment.php",
type: "get",
data: requestData,
dataType: "text",
success : function (data) {
jQuery.each(data, function(index, item) {
//now you can access properties using dot notation
$('#chat_box').val( $('#chat_box').val() + item.body + '\n');
/* $('#author_comment').html(item.author);
$('#chat_box').html(item.body);*/
});
},
error: function (http, status, error) {
alert('Some error occurred :'+error);
}
});
return false;
}
setInterval( refreshComment , 5000 );
And the html where the data is not display is: photo.php.
<div class="media">
<a class="pull-left" href="#">
<img class="media-object" src="http://placehold.it/64x64" alt="">
</a>
<div class="media-body">
<h4 id="author_comment" class="media-heading"></h4>
<p id="chat_box"></p>
<p class="text-info">This is post at: </p>
</div>
</div>
Please try this one,
$sql = "SELECT * FROM comments WHERE photo_id = " . $database->escape_string($photo_id) ORDER BY photo_id ASC";
$result = mysqli_query( $con,$sql);
$arr = array();
while ($row = mysqli_fetch_array($result)){
$arr[] = $row;
}
echo json_encode($arr);
and change ,
dataType:'json' instead of dataType:'text'
in script.
change dataType:text to dataType:JSON
EDIT
use this instead of $.each
for(var i = 0;i < data.length ; i++)
{
/*access data as data[i].orfeas*/
}
PHP
$array = array();
$i = 0;`
foreach($res as $r){
$array[$i] = $r;
$i++;
}
header('Content-Type:Application/json');
echo json_encode($array);
EDIT2
USE Header to help jQuery to identify the response type and then jQuery will parse the JSON and you can access it by using a loop above mentioned
in your script.js file make change on success function of ajax:-
success : function (data) {
$.each($.parseJSON(data), function(key,item){
$('#chat_box').val( $('#chat_box').val() + item.body + '\n');
});
}

How do I output PHP/SQL results from HTML/AJAX

If I call the .php file directly it works great, so I believe the error is in how I am displaying the AJAX result. I am new to AJAX. I have a form that the user can select dates to search on, etc and I would like to results to be displayed when returned.
$("#searchForm").on("submit", function (event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "searchnow.php",
data: $('#searchForm').serialize(),
success : function (output) {
console.log(output);
}
});
});
searchnow.php
<div id="output">
<div class="container-fluid">
<div class='features'>
<?php
include ("config.php");
$con = mysql_connect($server, $user, $password) or die('Sorry, could not connect to database server');
mysql_select_db($database, $con) or die('Sorry, could not connect to database');
$query = "SELECT * FROM hsevents WHERE
CURDATE()<=enddate AND
verified='Y'
ORDER BY location";
$result = mysql_query($query) or die('Sorry, could not access the database at this time ');
$SPACES = "</br><b>Description:</b> ";
if (mysql_num_rows($result) == 0)
{
echo "<h3>Sorry, there are no classes or events that meet your criteria.</h3>";
}
else
{
$i = 1;
while($row=mysql_fetch_array($result, MYSQL_ASSOC))
{
$unique = 'unique' . $i;
$tempname=htmlentities($row[name]);
$tempcontact=htmlentities($row[contact]);
$tempbegdate = date("m-d-Y", strtotime($row[startdate]));
$tempenddate = date("m-d-Y", strtotime($row[enddate]));
ob_start();
if ( ($i%4) === 0) {
echo "<div class='row row-padded row-bordered row-centered'>";
}
echo "
<div class='col-md-3'>
<div class='panel'>
<div class='panel-heading'>
<img src='images/$row[category]' class='img-responsive img-thumbnail img-hsb'>
</div>
<div class='panel-body text-center'>
$tempname</br>
Start Date: $tempbegdate</br>
End Date: $tempenddate</br>
Location: $row[location]</br>
Age Range: $row[lowerage] - $row[upperage]</br>
Contact: <a href=$tempcontact>$tempcontact</a></br>
<div id='$unique' class='collapse collapse-hsb'>
$tempdescription
</div>
</div>
</div>
</div>
";
if ( ($i%4) === 0) {
echo "</div>";
}
$classdata = ob_get_contents();
ob_end_clean();
?>
<?php echo $classdata ?>
<?php
$i++;
}
$classdata = ob_get_contents();
ob_end_clean();
echo $classdata;
}
?>
</div>
</div>
</div>
You just need to provide the DIV or any Selector inside the success function, to replace the DIV or selector html with the AJAX success output. Here i used #MyDivId which should be your html element in which you need to print the AJAX output.
$("#searchForm").on("submit", function (event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "searchnow.php",
data: $('#searchForm').serialize(),
success : function (output) {
output = output.trim(); // Trim's unwanted white space around the output
if (output != "") {
$("#MyDivId").html(output); // This Adds the AJAX output inside #MyDivId
}
}
});
});

Categories

Resources