Getting value from file called by ajax request using json - javascript

This file is called by ajax request. And result coming here I want to place into two different in calling function.
<?php
//Some processing gives $text
$s=nl2br($text);
$data['x'] = $p;
$data['y'] = $q;
//Start from here
echo "<b>Positive count : $x with $p % </b>"; echo "</br>";
echo "<b>Negative count : $y with $q % </b>"; echo "</br>";
echo "</br>";
echo "Page content : ";
echo "</br>";
echo "</br>";
echo $s;
//End. This content should be place in <div1>. Want to send this as a json string
and
//Start from here
echo "First 5 post";
$result = mysqli_query($con,"select post from facebook_posts where p_id > (select MAX(p_id) - 5 from facebook_posts)");
while ($row = $result->fetch_array(MYSQLI_ASSOC))
{
echo $row['post'];
echo '<br/>';
}
//End. This content should be placed in <div2> Want to send this as a json string
If there is single variable then we can easily do it using :
$resultArray = array("resultOne" => $result1,"resultTwo" => $result2);
echo json_encode($resultArray);
at receiving end:
document.getElementById("myFirstDiv").innerHTML=xmlhttp.responseText.resultOne;
document.getElementById("mySecondDiv").innerHTML=xmlhttp.responseText.resultTwo;
But how above complex result could be place into to json variable?

You could use output buffering in PHP:
ob_start();
// Generate content for div 1...
$div1 = ob_get_clean();
ob_start();
// Generate content for div 2...
$div2 = ob_get_clean();
$result = array("div1" => $div1, "div2" => $div2);
echo json_encode($result);

Related

how to store php variable passed as id to javascript in a javascript variable

I am trying to pass div id to javascript and print it out on console as :
<?php echo 67;?>
The 67 is id here. I was wondering how can I store this value in my javascript variable storeid as var storeid = 67?
My code:
echo "<h2 class='editme' id='<?php echo $id;?>' contentEditable='true'> Hello</h2>";
echo "<script>
$('h2.editme').click(function(){
console.log(this.id);
var storeid;
});
</script>";
Also, I want to use that id value to update the values in my sql. I can only test my code once I could somehow get the value of that id. How can I store the value of the id to javascript variable?
My code (This is to update sql once I get the id) - Not sure if it's right I can test it after getting id value:
echo "<h2 class='editme' id='<?php echo $id;?>' contentEditable='true'> Hello</h2>";
echo "<script>
$('h2.editme').click(function(){
var content2 = $(this).html();
console.log(this.id);
var storeid;//once I get the id
$.ajax({
url: 'updateDescription(storeid, content2)',
success: function(respon) {
$('.editme').html(respon);
}
});
});
</script>";
function updateDescription($user_unique_id, $content2)
{
try {
require "testing.php";
$sql = "UPDATE icecream SET
desc = :desc
WHERE id = :id";
$stmt->bindParam(':desc', $content2, PDO::PARAM_STR);
$stmt->bindParam(':id', $user_unique_id);
$stmt->execute();
echo 'Record updated';
} catch (PDOException $e) {
echo 'Connection failed ' . $e->getMessage();
}
}
this way:
echo '<script>
var storeid = '. $id .'
</script>';
more readable way:
// somefile.php
<?php
$id = 67;
?>
<h2 class='editme' id='<?php echo $id;?>' contentEditable='true'> Hello</h2>
<script>
var storeid = <?php echo $id; ?>
// rest of javascript code
</script>
<?php
// rest of the php code

Alert() javascript function not working in php

I know this is frequently asked question however I have tried using :
script language='javascript'
placed header in else after alert
script type='text/javascript'
Still I don't get alert box, while else parts executes perfectly.
Here's my code:
<?php
/* header('Content-Type: application/json');
$response = array(); */
if (isset($_GET['sid'])){
$con = mysqli_connect("localhost", "root", "", "kaemiphk_greivance");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$checkdata=mysqli_query($con,"SELECT * FROM officer_master WHERE pf_no = '".$_GET['sid']."'");
$query_data=mysqli_num_rows($checkdata);
if ($query_data == 0) {
//echo alert "welcome";
echo '<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.0.min.js">';
echo "alert('PF No. Does not exist. Please Contact Admin!!!');";
echo '</script>';
}
else{
header('Content-Type: application/json');
$response = array();
$select="SELECT m.officer_name,m.email,m.department,m.mobile_no,m.designation,n.quarter_no,n.address,n.colony,n.blueprint_quarter,n.type_of_quarter, n.area FROM officer_master m, quarter_master n WHERE n.pf_no='".$_GET['sid']."' AND m.pf_no = n.pf_no";
$result = mysqli_query($con, $select); //mysql_query($qry);
while ($row = mysqli_fetch_assoc($result)) {
array_push($response, $row);
}
}
echo json_encode($response);
}
?>
What am I missing here.
Thanks
You have your js files mixed up.
Include jquery and then your script, inside separate tags:
echo '<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.0.min.js" ></script>';
echo '<script type="text/javascript">';
echo "alert('PF No. Does not exist. Please Contact Admin!!!');";
echo '</script>';
By the way, you do NOT need jquery for a simple alert, as it is plain javascript. Try to avoid including external library if not needed, you will end up with a bloated code.
And printing js with php it's a bit of a hack. Why not just print it into your html or js file?
Javascript inside a script tag that has an src attribute does not get executed, you have to create a second script tag after the jquery one.
<?php
/* header('Content-Type: application/json');
$response = array(); */
if (isset($_GET['sid'])){
$con = mysqli_connect("localhost", "root", "", "kaemiphk_greivance");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$checkdata=mysqli_query($con,"SELECT * FROM officer_master WHERE pf_no = '".$_GET['sid']."'");
$query_data = mysqli_num_rows($checkdata);
if ($query_data == 0) {
//echo alert "welcome";
echo '<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.0.min.js">';
echo '</script>';
echo "<script>alert('PF No. Does not exist. Please Contact Admin!!!');</script>";
} else {
header('Content-Type: application/json');
$response = array();
$select="SELECT m.officer_name,m.email,m.department,m.mobile_no,m.designation,n.quarter_no,n.address,n.colony,n.blueprint_quarter,n.type_of_quarter, n.area FROM officer_master m, quarter_master n WHERE n.pf_no='".$_GET['sid']."' AND m.pf_no = n.pf_no";
$result = mysqli_query($con, $select); //mysql_query($qry);
while ($row = mysqli_fetch_assoc($result)) {
array_push($response, $row);
}
}
echo json_encode($response);
}
}
?>

Fill a javascript array with php variable

I want to fill a javascript array with my php variable $jaar. But when I print it in the js file I don't get the right output.
php file
<?php
$jaar = "[";
$result = mysql_query("SELECT jaar FROM agenda");
while( $row=mysql_fetch_array($result, MYSQL_NUM) ) {
$jaar .= "\"" . $row[0] . "\"";
$jaar .= ",";
}
$jaar{ strlen($jaar)-1 } = ']';
echo "<script type='text/javascript'>var db_jaar = '" . $jaar ."'</script>";
?>
<script src="js/calender.js"></script>
js file
//Get the variable from the php file
alert(db_jaar);
//printed: ["2018","2018"]
//When I make the variable local
var db_jaar = ["2018","2018"];
alert(db_jaar);
//printed: 2018,2018 <-- This is what I want
Some changes required:
while( $row=mysql_fetch_array($result, MYSQL_NUM) ) {
// create $jaar[]
$jaar[] = $row[0];
}
// echo using json_encode
?><script type='text/javascript'>var db_jaar = <?php echo json_encode($jaar); ?>;</script>";<?php
Read more:
json_encode()

PHP echo selected value from html dropdown list

In my dropdown list, i put all the "pack_name(s)" the user has posted and I display it all in the list for the user to select and update. So when the user selects one and hits submit, i want to get that "value" submitted and use it for later purposes but ive been researching and only found "pre-set" values with html and the value was given using Jquery. So i wondering if its possible to basically take the "pack_name" selected and when the user hits submit, echo out the selected value.
PHP
<?php
session_start();
if(empty($_FILES) && empty($_POST) && isset($_SERVER['REQUEST_METHOD']) && strtolower($_SERVER['REQUEST_METHOD']) == 'post'){ //catch file overload error...
$postMax = ini_get('post_max_size'); //grab the size limits...
echo "<p style=\"color: #F00;\">\nPlease note files larger than {$postMax} will result in this error!</p>"; // echo out error and solutions...
return $postMax;
}
if(isset($_COOKIE['id'])){
if($_SESSION['came_from_upload'] != true){
setcookie("id", "", time() - 60*60);
$_COOKIE['id'] = "";
header("Location: developerLogin.php");
exit;
}
try{
// new php data object
$handler = new PDO('mysql:host=127.0.0.1;dbname=magicserver', 'root', '');
//ATTR_ERRMODE set to exception
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
die("There was an error connecting to the database");
}
$userid = $_SESSION['id'];
$stmt = $handler->prepare("SELECT * FROM pack_profile WHERE pack_developer_id = :userid");
$stmt->bindParam(':userid', $userid, PDO::PARAM_INT);
$stmt->execute();
echo "<select>";
while($result = $stmt->fetch()){
echo "<option>" . $result['pack_name'] ."</option>";
}
echo "</select>";
if($_SERVER['REQUEST_METHOD'] =="POST"){
$token = $_SESSION['token'];
}
}
?>
You need to give the select element a name attribute, and give each option element a value attribute.
For example:
echo "<select name=\"pack\">";
while($result = $stmt->fetch()){
echo "<option value=\"" . $result['pack_name'] . "\">" . $result['pack_name'] ."</option>";
}
echo "</select>";
Of course you should be escaping anything which could contain &, < or " with something like htmlspecialchars().

Create session variables out of looped database values

I am attempting to create a variable from a database array when an HTML link is clicked. The goal is to redirect the user to a form populated using one piece of array data. In other words, the database will be queried and form populated according to which link is clicked (whatever the values of $row[1], $row[2], and $row[3] are).
<?php
ini_set('display_errors',1); error_reporting(E_ALL);
$DATE = date('Y-m-d');
require_once 'IRCconfig.php';
$connection = new mysqli($db_hostname, $db_username, $db_password, $db_database);
if ($connection->connect_error) die($connection->connect_error);
$query = "SELECT * FROM CLIENT_CHECKIN1 WHERE DATE>='$DATE'";
$result = $connection->query($query);
if (!$result) die ("Database access failed: " . $connection->error);
$rows = $result->num_rows;
for ($j = 0 ; $j < $rows ; ++$j)
{
$result->data_seek($j);
$row = $result->fetch_array(MYSQLI_NUM);
echo <<<_END
<pre>
$row[1] $row[2] $row[3]
</pre>
_END;
}
?>
If anyone can provide me with some incite as to how I could accomplish this I'd appreciate it greatly.
Please read more about sessions here
Then, to answer your question:
First you need to start the session, as simple as session_start(); on the top of your script.
Second you need to instantiate session variables with the DB values like this: $_SESSION['var'] = $value;.
Third, in the html file or whatever, where the form relies, just check for it:
if(isset($_SESSION['var'])) {
echo '<input type="text" value="'.$_SESSION['var'].'" />';
} else {
echo '<input type="text" value="" />';
}
and use the value if it is set.
L.E:
So... first thing's first... session_start(); without it, there is no point of having session.
Second, you create it like $_SESSION['some_name'] = $row[1] so that var will keep the value from $row[1]. I am presuming that it's the value you need. Do NOT do do it like $_SESSION['$row1'] because first of all this is incorrect, you will NOT have the value of row1 there. You need an unique name so that you can call it where you have the form.
The above code will become something like this:
<?php
session_start();
ini_set('display_errors',1); error_reporting(E_ALL);
$DATE = date('Y-m-d');
require_once 'IRCconfig.php';
$connection = new mysqli($db_hostname, $db_username, $db_password, $db_database);
if ($connection->connect_error) die($connection->connect_error);
$query = "SELECT * FROM CLIENT_CHECKIN1 WHERE DATE>='$DATE'";
$result = $connection->query($query);
if (!$result) die ("Database access failed: " . $connection->error);
$rows = $result->num_rows;
for ($j = 0 ; $j < $rows ; ++$j)
{
$result->data_seek($j);
$row = $result->fetch_array(MYSQLI_NUM);
$_SESSION['first_row'] = $row[1];
$_SESSION['second_row'] = $row[2];
$_SESSION['third_row'] = $row[3];
echo <<<_END
<pre>
$row[1] $row[2] $row[3]
</pre>
_END;
}
?>
and, where you have the form and the <input type = "text" value = "" /> so where you need the value, just do it like this:
<input type = "text" value = "<?php echo (isset($_SESSION['first_row']) ? $_SESSION['first_row'] : ''); ?>" />
<input type = "text" value = "<?php echo (isset($_SESSION['second_row']) ? $_SESSION['second_row'] : ''); ?>" />
<input type = "text" value = "<?php echo (isset($_SESSION['third_row']) ? $_SESSION['third_row'] : ''); ?>" />
Hope this helps! :D

Categories

Resources