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

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
}
}
});
});

Related

How to pass data from Javascript to PHP using ajax

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;
}

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');
});
}

Codeigniter Jquery : I want reload this page same

I want when I add a product to the cart and reload the same page, but the problem did not this product.
The controller
public function detail()
{
$data=array('title' =>'Ecommerce Online | Detail Product',
'username' => $this->session->userdata('id'),
'categories' => $this->categories_model->get_categories(),
'details' => $this->categories_model->get_details($this->uri->segment(3)),
'isi' =>'member/detail');
$this->load->view('template_home/wrapper',$data);
}
function addtocart()
{
if($this->cart_model->validate_add_cart_item() == TRUE){
if($this->input->post('ajax') != '1'){
redirect('member/detail/'); // this problem
}else{
echo 'true';
}
}
}
I add my models
function validate_add_cart_item()
{
$id = $this->input->post('product_id');
$cty = $this->input->post('quantity');
$this->db->where('productID', $id);
$query = $this->db->get('product', 1);
if($query->num_rows > 0){
foreach ($query->result() as $row)
{
$data = array(
'id' => $id,
'qty' => $cty,
'price' => $row->price,
'name' => $row->productName
);
$this->cart->insert($data);
return TRUE;
}
}else{
return FALSE;
}
}
I add my view
<?php foreach ($details as $s) { ?>
<div class="col-md-5">
<div class="box text-center">
<img src="<?php echo base_url('upload/'.$s->photo); ?>" width="150px" height="150px">
<br><?php echo $s->productName; ?>
<br><strong>Rp. <?php echo $s->price; ?></strong>
<br>
<?php echo form_open('member/add'); ?>
<fieldset>
<label>Quantity</label>
<?php echo form_input('quantity', '1', 'maxlength="2"'); ?>
<?php echo form_hidden('product_id', $s->productID); ?>
<?php echo form_submit('add', 'Add'); ?>
</fieldset>
<?php echo form_close(); ?>
</div>
</div>
<?php } ?>
Jquery script
<script type="text/javascript">
$(document).ready(function() {
/*place jQuery actions here*/
var link = "<?php echo site_url('member/detail')?>/"; // Url to your application (including index.php/)
$(".detail-product").submit(function(){
var id = $(this).find('input[name=product_id]').val();
var qty = $(this).find('input[name=quantity]').val();
$.post(link + "member/add", { product_id: id, quantity: qty, ajax: '1' },
function(data){
if(data == 'true'){
$.get(link + "member/detail", function(cart){ // Get the contents of the url cart/show_cart
$("#cart_content").html(cart); // Replace the information in the div #cart_content with the retrieved data
});
}else{
alert("Product does not exist");
});
return false; // Stop the browser of loading the page defined
});
});
</script>
This is problem url: http://localhost/scientificwriting/member/detail/ and productid can not be invoked. Do I need to replace the IF statement on my controller and my jquery?
Please help me thanks

Can someone spot my error (autocomplete text box)?

So far I have HTML:
<div id="box" style="width:400; height:400; margin-left:auto; margin-right:auto; margin-top:100;">
<h2>Enter a word</h2>
<input type="text" id="input" ></input>
</div>
<div id="suggest">
</div>
Javascript:
<script type ="text/javascript">
$(document).ready(function(){
$("#input").keyup(function(){
var input = $("#input").val();
$.ajax({
url: "PathToPHPFileThatConnectsToDatabaseAndRetreivesValues",
data: "input"+input,
success: function(msg){
alert(msg);
$("#suggest").html(msg);
}
});
});
});
</script>
PHP:
<?php
$dbh=mysql_connect ("localhost", "~", "~") or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db ("~") or ("Database not found");
$input = $_REQUEST['input'];
$input = mysql_real_escape_string(trim($input));
$sql = "SELECT * FROM ~ WHERE ~ LIKE '%".$input."%'";
$data = mysql_query($sql);
$arrcnt = -1;
$dataArray = array();
while ($temp = mysql_fetch_assoc($data))
{
foreach($temp as $key=>$val) {
$temp[$key] = stripslashes($val);
$arrcnt++;
}
$dataarray[$arrcnt] = $temp;
}
$list = "<ul style='width:100;height:auto;'>";
foreach($dataArray as $val) {
$list .= "<li>".$val['DesiredColumnContainingDesiredData']."</li>";
}
$list .= "</ul>";
echo $list;
?>
Now, these codes are supposed to work together to autocomplete the div with id="suggest" then populate the text field with id="input" when selected ... I keep getting alert that reads: <ul style='width:100;height:auto;'></ul>
change ajax code like this,
$.ajax({
url: "PathToPHPFileThatConnectsToDatabaseAndRetreivesValues",
data: {"input":input},
success: function(msg){
alert(msg);
$("#suggest").html(msg);
}
});
The issue is because in php your variable name is different . You added $dataarray instead of $dataArray
Additionally for ajax
You can pass data as a string or as an object
data:{"input":input}
or
data:"input="+input
add type: 'POST' in ajax

Categories

Resources