Access JavaScript Variable in PHP - javascript

I have problem to set the AJAX variable in use in my PHP code
When I change the value of area the following function will be called:
function find_map(){
var value1 = $("#area").val();
var value2 = $("#city").val();
$.ajax({
url :"find_my_map.php", // json datasource
type: "post", // method , by default get
dataType:"json",
data:
{
area_id:value1,
city_id:value2
},
success: function(data)
{
console.log(data);
$.each(data, function(index, element) {
alert("area_name:" + element.area_name);
alert("city_name:" + element.city_name);
var map_area_name= element.area_name;
var map_city_name= element.city_name;
$("#map_area_name").val(map_area_name);
$("#map_city_name").val(map_city_name);
});
},
error:function(data){
console.log(data);
}
});
}
find_my_map.php file
include_once("config.php");
if(isset($_POST['area_id']) && isset($_POST['city_id']))
{
$area_id = $_POST['area_id'];
$city_id = $_POST['city_id'];
$sql = "SELECT * FROM area a, city c WHERE a.city_id=c.city_id AND c.city_id='$city_id' AND a.area_id='$area_id'";
$qry = mysql_query($sql);
while($fetch = mysql_fetch_array($qry))
{
$area_name=$fetch['area_name'];
$city_name=$fetch['city_name'];
$data[]=array(
'area_name' => $area_name,
'city_name' => $city_name
);
}
$json_data = array($data);
echo json_encode($data);
}
this is my php code
<?php
echo $address ="here i want to use **map_area_name AND map_city_name**"; // Google HQ
$prepAddr = str_replace(' ','+',$address);
$geocode=file_get_contents('https://maps.google.com/maps/api/geocode/json?address='.$prepAddr.'&sensor=false');
$output= json_decode($geocode);
$area_latitude = $output->results[0]->geometry->location->lat;
$area_longitude = $output->results[0]->geometry->location->lng;
echo "<br><input type='text' name='area_latitude' id='area_latitude'value='".$area_latitude."'> <br>";
echo "<input type='text' name='area_longitude' id='area_longitude' value='".$area_longitude."'>";
?>

Related

Submitted chat not posting and retrieving chat not working

I using the below php chat script to create chat section between two users on my web app. I am having a problem with the Ajax posting. When a user submits a chat it doesn't post or show in the chat window. I tried to inspect the error and this is the error message
Failed to load resource: the server responded with a status of 404 (Not Found)
The same error message is shown for submit.php and refresh.php.
Here's my code:
JS
//CHAT FUNCTION
var lastTimeID = 0;
$(document).ready(function() {
$('#btnSend').click( function() {
sendChatText();
$('#chatInput').val("");
});
startChat();
});
function startChat(){
setInterval( function() { getChatText(); }, 2000);
}
function getChatText() {
$.ajax({
type: "GET",
url: "refresh.php?lastTimeID=" + lastTimeID
}).done( function( data )
{
var jsonData = JSON.parse(data);
var jsonLength = jsonData.results.length;
var html = "";
for (var i = 0; i < jsonLength; i++) {
var result = jsonData.results[i];
html += '<div style="color:#' + result.color + '">(' + result.chattime + ') <b>' + result.usrname +'</b>: ' + result.chattext + '</div>';
lastTimeID = result.id;
}
$('#view_ajax').append(html);
});
}
function sendChatText(){
var chatInput = $('#chatInput').val();
if(chatInput != ""){
$.ajax({
type: "GET",
url: "submit.php?chattext=" + encodeURIComponent( chatInput )
});
}
}
chatClass.php
<?PHP
class chatClass
{
public static function getRestChatLines($id)
{
$arr = array();
$jsonData = '{"results":[';
$statement = $db->prepare( "SELECT id, usrname, color, chattext, chattime FROM chat WHERE id > ? and chattime >= DATE_SUB(NOW(), INTERVAL 1 HOUR)");
$statement->bind_param( 'i', $id);
$statement->execute();
$statement->bind_result( $id, $usrname, $color, $chattext, $chattime);
$line = new stdClass;
while ($statement->fetch()) {
$line->id = $id;
$line->usrname = $usrname;
$line->color = $color;
$line->chattext = $chattext;
$line->chattime = date('H:i:s', strtotime($chattime));
$arr[] = json_encode($line);
}
$statement->close();
$jsonData .= implode(",", $arr);
$jsonData .= ']}';
return $jsonData;
}
public static function setChatLines( $chattext, $usrname, $color) {
$statement = $db->prepare( "INSERT INTO chat( usrname, color, chattext) VALUES(?, ?, ?)");
$statement->bind_param( 'sss', $usrname, $color, $chattext);
$statement->execute();
$statement->close();
}
}
?>
submit.php
<?php
require_once( "chatClass.php" );
$chattext = htmlspecialchars( $_GET['chattext'] );
chatClass::setChatLines( $chattext, $_SESSION['usrname'], $_SESSION['color']);
?>
refresh.php
<?php
require_once( "chatClass.php" );
$id = intval( $_GET[ 'lastTimeID' ] );
$jsonData = chatClass::getRestChatLines( $id );
print $jsonData;
?>

show only one value from ajax return array

How can I display only one thing from the array. Now it shows the whole array but I only want to show the reason from the array. because the rest is't really important. I have added index.php to show what I do there. I would like that it only showed the reason from data.
test.js
$(document).ready(function() {
var date = "";
var begin = "";
var tijdsduur = "";
var aantal = "";
$('#datum').change(function() {
date = $("#datum").val();
console.log(date);
});
$('#beginTijd').change(function() {
begin = ($(this).val());
console.log(begin);
});
$('#Tijdsduur').change(function() {
tijdsduur = ($(this).val());
console.log(tijdsduur);
});
$('#aantalSloepen').change(function() {
aantal = ($(this).val());
console.log(aantal);
$.ajax({
type: "POST",
url: "index.php",
data: {
date: date,
begin: begin,
eind: tijdsduur,
quantity: aantal
},
success: function(data) {
$('#testajax').html(data);
console.log(data);
}
});
});
});
index.php
<?php
$date = "";
$begin = "";
$tijdsduur = "";
$aantal = "";
if (isset($_POST['date']) && isset($_POST['quantity'])) {
if (isset($_POST['date'])) {
print_r($_POST);
// echo "Yes, mail is set";
$date = $_POST['date'];
$begin = $_POST['begin'];
$tijdsduur = $_POST['eind'];
$aantal = $_POST['quantity'];
$eind = $begin + $tijdsduur;
$startTijd = "$date " . $begin;
$eindTijd = "$date " . $eind . ":00";
// echo $date . "<br>";
// echo "$startTijd". "<br>";
// echo "$eindTijd". "<br>";
// echo $aantal. "<br>";
$canmakereservation = "https://www.planyo.com/rest/?method=can_make_reservation&api_key=YOURKEY&resource_id=110556&start_time=$startTijd&end_time=$eindTijd&quantity=$aantal";
$cleancanmakereservation = preg_replace("/ /", "%20", $canmakereservation);
$reservationavailable = file_get_contents("$cleancanmakereservation");
$reservationAvailable = json_decode($reservationavailable, true);
// echo "$cleancanmakereservation";
echo json_encode($reservationAvailable);
}
else {
echo "No, mail is not set";
}
exit;
}
?>
console.log
Set the dataType: 'json' in ajax request like
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$.ajax({
type: "POST",
url: "indextest.php",
dataType: 'json',
data: {
date: '',
begin: '',
eind: '',
quantity: ''
},
success: function(data) {
console.log(data.date);
}
});
</script>
and in php
<?php
$data = array('date' => '10-10-2010','date2' => '10-10-2010');
echo json_encode($data);
?>

only show some data of array on ajax return

Is there a way to only show [reason] from the array and not everything inside data? somebody said that I need to use JSON but I tried contentType: "application/json" with stringify() but then success: function(data) returns my whole HTML instead of the array.
My question is how can I show only [reason] in $('#testajax').html(data); instead of everything inside data?
console.log
script.js
$(document).ready(function(){
var date = "";
var begin = "";
var tijdsduur = "";
var aantal = "";
$('#datum').change(function() {
date = $("#datum").val();
console.log(date);
});
$('#beginTijd').change(function(){
begin =( $(this).val() );
console.log(begin);
});
$('#Tijdsduur').change(function(){
tijdsduur =( $(this).val() );
console.log(tijdsduur);
});
$('#aantalSloepen').change(function() {
aantal = ($(this).val());
console.log(aantal);
$.ajax({
type: "POST",
url: "index.php",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
data: {
date: date,
begin: begin,
eind: tijdsduur,
quantity: aantal
},
success: function(data) {
$('#testajax').html(data);
console.log(data);
}
});
});
});
UPDATED index.php
<?php
$date = "";
$begin = "";
$tijdsduur = "";
$aantal = "";
if (isset($_POST['date']) && isset($_POST['quantity'])) {
if (isset($_POST['date'])) {
print_r($_POST);
echo "Yes, mail is set";
$date = $_POST['date'];
$begin = $_POST['begin'];
$tijdsduur = $_POST['eind'];
$aantal = $_POST['quantity'];
$eind = $begin + $tijdsduur;
$startTijd = "$date " . $begin;
$eindTijd = "$date " . $eind . ":00";
echo $date . "<br>";
echo "$startTijd". "<br>";
echo "$eindTijd". "<br>";
echo $aantal. "<br>";
$canmakereservation = "https://www.planyo.com/rest/?method=can_make_reservation&api_key=YOURKEY&resource_id=110556&start_time=$startTijd&end_time=$eindTijd&quantity=$aantal";
$cleancanmakereservation = preg_replace("/ /", "%20", $canmakereservation);
$reservationavailable = file_get_contents("$cleancanmakereservation");
$reservationAvailable = json_decode($reservationavailable, true);
echo "$cleancanmakereservation";
echo json_encode($reservationAvailable);
}
else {
echo "No, mail is not set";
}
exit;
}
?>
console.log(date[0].reason);
console.log(date);
Return data in json_encode from your index.php
Then in your ajax success function just get it by
success: function(data) {
console.log(data.reason); //if its comming then add it to your html.
$('#testajax').html(data.reason);
}

why can't I pass the data as json using Ajax and Jquery to the php side?

function delete_user(email)
{
//if(confirm("Do you want to remove this user with mail id: "+email))
//{
var z = {email : email}
console.log(z)
$.ajax({
url: "delete_user.php",
type: 'POST',
data: z,
success: function (data) {
console.log(data);
return false;
var i=0;
var element = "<table style='border-collapse: collapse;'>"
while(data[i] != null)
{
element = element + "<tr style='height:15px' onmouseover='rowbig(this)' onmouseout='rowsmall(this)'><td>"+data[i].fname+"&nbsp"+data[i].lname+"</td><td>"+data[i].email+"</td><td>"+data[i].dob+"</td><td><button onclick='delete_user(\""+data[i].email+"\")'><img src='delete.png' style='height:20px;width:20px'/></button></td></tr>";
i++;
}
element = element + "</table>";
$("#response").html( element );
},
cache: false,
contentType: false,
processData: false
});
//}
}
<?php
header("Content-Type:application/json");
$email ="";
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
function deliver_res($status_message,$result)
{
header("$status_message");
$response['status_message']=$status_message;
$response['result']=$result;
$json_response=json_encode ($response);
echo $json_response;
}
$servername = 'localhost';
$username = 'root';
$password = '';
$dbname = 'webdata';
$conn = mysqli_connect($servername, $username, $password, $dbname);
if(isset($_POST['email']))
{
$email = test_input($_POST["email"]);
}
else
{
deliver_res("name not received","false");
exit();
}
$sqll="DELETE FROM admindata WHERE email='".$email."';";
$result = mysqli_query($conn,$sqll);
$return_arr = array();
$sqll="SELECT * FROM admindata ORDER BY id DESC ;";
$result = mysqli_query($conn,$sqll);
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
$row_array['fname'] = $row['fname'];
$row_array['lname'] = $row['lname'];
$row_array['email'] = $row['email'];
$row_array['dob'] = $row['dob'];
array_push($return_arr,$row_array);
}
echo json_encode($return_arr);
echo "\n";
mysqli_close($conn);
?>
I just can't seem to pass the data as JSON using AJAX and Jquery to the PHP side. Is there anything anything wrong with the syntax?

My Ajax code is only getting the value of one row from Mysql database rows

create table comment(id int not null auto_increment primary key, comment text);
$result = mysqli_query($con, "select * from comment order by id desc");
while($rows = mysqli_fetch_assoc($result)) {
$main_id = $rows["id"];
$comment = $rows["comment"];
echo "<input type='hidden' id='main_id' value=\"$main_id\"/>";
echo "<input type='hidden' id='comment' value=\"$comment\"/>";
echo "<div id='edit_field'><p>$comment</p></div>" . "\n";
echo "<a href='#' id='edit'> edit</a>" . "\n";
}
$(document).ready(function() {
$('#edit').click(function() {
var id = $('#main_id').val();
var comment = $('#comment').val();
var varData = 'id='+id+'&comment='+comment;
$.ajax ({
type: "POST",
url: "edit_field.php",
data: varData,
success: function(data) {
$("#edit_field").html(data);
}
});
});
require_once('lib/functions.php');
$con = connect();
$result = mysqli_query($con, "select * from comment where id = $_POST[id]");
while($rows = mysqli_fetch_assoc($result)) {
$id = $rows["id"];
$comment = $rows["comment"];
echo "<textarea cols='40' name='comment' rows='4'>$comment</textarea>";
}
while($rows = mysqli_fetch_assoc($result)) {
$main_id = $rows["id"];
$comment = $rows["comment"];
echo "<input type='hidden' class='main_id' id='main_id_$main_id' value=\"$main_id\"/>";
echo "<input type='hidden' class='comment' id='comment_$main_id' value=\"$comment\"/>";
echo "<div class='edit_field'><p>$comment</p></div>" . "\n";
echo "<a href='#' class='edit' id='edit_$main_id'> edit</a>" . "\n";
}
$(document).ready(function() {
$('.edit').click(function() {
var lnk = $(this);
var rowId = lnk.attr('id');
var rowIdParts = rowId.split('_');
var id = rowIdParts[1];
var comment = $('#comment_'+id).val();
var varData = 'id='+id+'&comment='+comment;
$.ajax ({
type: "POST",
url: "edit_field.php",
data: varData,
success: function(data) {
$("#edit_field").html(data);
}
});
});

Categories

Resources