image is not show in json page - javascript

the images from the database is not coming out in the json page and the html page but the image source name is outputted. how do I make the images show on the html page?
Thank you for your precious time.
linejson.php page
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$conn = new mysqli("localhost", "db_user", "db_pwd", "db_name");
$result = $conn->query("SELECT tbl_users.image, tbl_users.firstname, tbl_users.lastname, tbl_users.username, tbl_posts.post, tbl_posts.post_date
FROM tbl_posts INNER JOIN tbl_users ON tbl_users.id=tbl_posts.user_id
WHERE tbl_posts.user_id=3");
$outp = "[";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "[") {$outp .= ",";}
$outp .= '{"Image":"' . $rs["image"] . '",';
$outp .= '"Firstname":"' . $rs["firstname"] . '",';
$outp .= '"Lastname":"' . $rs["lastname"] . '",';
$outp .= '"Username":"' . $rs["username"] . '",';
$outp .= '"Post":"' . $rs["post"] . '"}';
}
$outp .="]";
$conn->close();
echo($outp);
?>
linejson.html page
<!DOCTYPE html>
<html>
<head>
<style>
table, th , td {
border-top: 1px solid purple;
border-collapse: collapse;
padding: 15px;
}
table tr:nth-child(odd) {
background-color: #f0f1f1;
}
table tr:nth-child(even) {
background-color: #ffffff;
}
</style>
</head>
<body>
<div id="timeline"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://www.outpaceng.com/linejson.php";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response) {
var arr = JSON.parse(response);
var i;
var out = "<table>";
for(i = 0; i < arr.length; i++) {
out += "<tr><td>" +
arr[i].Image +
"</td><td>" +
arr[i].Firstname +
" " +
arr[i].Lastname +
" " +
arr[i].Username +
"<br>" +
arr[i].Post +
"</td><tr>" ;
}
out += "</table>";
document.getElementById("timeline").innerHTML = out;
}
</script>
</body>
</html>

The code can be sipmlified and you should use json_encode for creating json
change this
$outp = "[";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "[") {$outp .= ",";}
$outp .= '{"Image":"' . $rs["image"] . '",';
$outp .= '"Firstname":"' . $rs["firstname"] . '",';
$outp .= '"Lastname":"' . $rs["lastname"] . '",';
$outp .= '"Username":"' . $rs["username"] . '",';
$outp .= '"Post":"' . $rs["post"] . '"}';
}
$outp .="]";
$conn->close();
echo($outp);
to
echo json_encode($result->fetch_all());
$conn->close();
and JavaScript
for(i = 0; i < arr.length; i++) {
out += "<tr><td><img src='" +
arr[i].image +
"' alt="img"/></td><td>" +
arr[i].firstname +
" " +
arr[i].lastname +
" " +
arr[i].username +
"<br>" +
arr[i].post +
"</td><tr>" ;
}

Related

Why after AJAX post, the URL redirect to a URL with the POST params like GET params in this case?

In the addonmodule Controller.php:
I append this order_detail function:
/**
* #param $vars
*/
public function order_detail($vars){
$modulelink = $vars['modulelink']; // eg. addonmodules.php?module=addonmodule
$version = $vars['version']; // eg. 1.0
$LANG = $vars['_lang']; // an array of the currently loaded language variables
$orderid = 28;//isset($_REQUEST['orderid']) ? $_REQUEST['orderid'] : '';
$sql = "SELECT tblhosting.id, tblhosting.regdate, tblhosting.domain, tblhosting.billingcycle, tblhosting.nextduedate, tblhosting.nextinvoicedate, tblhosting.termination_date, tblhosting.domainstatus, tblhosting.username, tblhosting.notes, tblhosting.dedicatedip, tblhosting.assignedips FROM tblhosting ";
// $sql .= "LEFT JOIN tblorders ON ";
// $sql .= "tblhosting.orderid = tblorders.id ";
$sql .= ("WHERE tblhosting.orderid = " . $orderid);
$tblhostings = Capsule::select($sql);
$table_tbody = "";
for($i = 0; $i < count($tblhostings); $i ++) {
$item = $tblhostings[$i];
$row = "<tr>";
$row .= ("<td><input type='text' id='tblhosting-id' name='id' class='form-control' readonly=\"readonly\" style='width:80px;' value='" . $item->id . "'></td>");
$row .= ("<td><textarea id='tblhosting-domain' name='domain' class='form-control' style='width:320px;'>" . $item->domain . "</textarea></td>");
//$row .= ("<td>" . $item->billingcycle . "</td>");
$row .= ("<td ><div style='width:80px;'>" . $item->nextduedate . "</div></td>");
$row .= ("<td ><div style='width:80px;'>" . $item->nextinvoicedate . "</div></td>");
//$row .= ("<td>" . $item->termination_date . "</td>");
//$row .= ("<td>" . $item->username . "</td>");
$row .= ("<td><textarea id='tblhosting-dedicatedip' name='dedicatedip' class='form-control' style='width:200px;'>" . $item->dedicatedip . "</textarea></td>");
$row .= ("<td><textarea id='tblhosting-assignedips' name='assignedips' class='form-control' style='width:200px;'>" . $item->assignedips . "</textarea></td>");
$row .= ("<td>" . $item->domainstatus . "</td>");
$row .= ("<td><div style='width:80px;'>" . $item->regdate . "</div></td>");
$row .= ("<td><textarea id='tblhosting-notes' type='textarea' name='notes' class='form-control' style='width:200px;'>" . $item->notes . "</textarea></td>");
$row .= ("<td> <button id='modify' type='submit' class='btn btn-warning'>modify</button> <button id='send-email' type='button' class='btn btn-success'>Send email</button> </td>");
$row .= "</tr>";
$table_tbody .= $row;
}
$div = "<div class='container'><div><h2>order ID: {$orderid} :</h2></div>";
$div .= "<div >";
$div .= "<form '><table class='table'>";
$div .= "<thead><tr>";
$div .= "<th>product ID</th>";
$div .= "<th>product name</th>";
//$div .= "<th>billingtype</th>";
$div .= "<th>nextdue</th>";
$div .= "<th>nextvoice</th>";
//$div .= "<th>terminate time</th>";
//$div .= "<th>username</th>";
$div .= "<th>dedicated IP</th>";
$div .= "<th>assigned IP</th>";
$div .= "<th>status</th>";
$div .= "<th>regdate</th>";
$div .= "<th>note</th>";
$div .= "<th>ope</th>";
$div .= "</tr></thead>";
$div .= "<tbody>";
$div .= $table_tbody;
$div .= "</tbody>";
$div .= "</table>";
$div .= "</div></div>";
$js = "<script>";
$js .= "
var origin_url = window.location.href;//\"http://192.168.33.10/whmcs-nlidc.com/whmcs/admin/addonmodules.php?module=addonmodule&action=order_detail&orderid=100\";
var url_array =origin_url.split(\"/admin/\")
var url = url_array[0] + \"/admin/api/admin_apis.php\";
jQuery(document).ready(function(){
$('#modify').click(function(){
//alert('modify');
var id = $('#tblhosting-id').val();
var domain = $('#tblhosting-domain').val();
var dedicatedip = $('#tblhosting-dedicatedip').val();
var assignedips = $('#tblhosting-assignedips').val();
var notes = $('#tblhosting-notes').val();
var params = {
admin_api:'update_tblhosting_support',
id: id,
domain: domain,
dedicatedip: dedicatedip,
assignedips: assignedips,
notes: notes,
}
$.post(url, params,function(data,status){
//alert(\"Data: \" + data + \"nStatus: \" + status);
var data_obj = JSON.parse(data);
if (status == 'url' && data_obj.status == 200) {
alert('update success');
alert(window.location.href(www.baidu.com);)
}else {
//alert('update fail');
}
});
})
});
jQuery(document).ready(function(){
$('#send-email').click(function(){
alert('send email');
})
});
";
$js .= "</script>";
$html = $div . $js;
return <<<EOF
$html
EOF;
}
}
I want to use this way to update the tblhosting entries. You see my jQuery code want to use post method to update the tblhosting entry.
when I click update button, it will execute the update url, but however it will redirect to this URL
http://192.168.33.10/whmcs/admin/addonmodules.php?id=28&domain=10.93.240.193-194(15M%29+HK-Z7-A15++E5-2650%282CPU%29%2F32G%2F500G+ssd%2F++&dedicatedip=10.93.240.193-194&assignedips=10.93.240.193%0D%0A10.93.240.194&notes=02442%2F66655%0D%0A10&intellisearch=1&token=ac271aed87528e68969608329e8a1f4d2a35c858&value=
As we know the ajax will not refresh a whole page, and will not redirect by default after request, why there goes different?
Who know the way to avoid the redirect?
I also tried use
window.location.href(origin_url);
to redirect to back after the wrong redirect, but it will not execute.

i want to use multiple select2 onchange function in a dynamic way

I want to put select2 function in my code but don't know where to put that .select2() function
i have this .append($(<?php echo json_encode($property_address1); ?>))
my model `
function property_address1()
{
$query = $this->db->query('SELECT host,price,city,property_thumbnail, apartments_type, contactnumber, contactperson,photographlinks,emailid, propertyaddress FROM tbl_contacts')->result();
$output = '<select id="neww" class="property_add_ form-control">';
foreach ($query as $row)
{
//echo $row->location;
$output .= "<option value='". $row->propertyaddress ."'";
$output .= " data-propertyaddress='" . $row->propertyaddress ."'" ;
$output .= " data-host_name='" . $row->host ."'" ;
$output .= " data-apartments_type ='" . $row->apartments_type."'" ;
$output .= " data-city ='" . $row->city."'" ;
$output .= " data-property_thumbnail='" . $row->property_thumbnail."'" ;
$output .= " data-price='" . $row->price."'" ;
$output .= " data-contactperson='" . $row->contactperson ."'" ;
// $output. = $row->pincode.", ".$row->city.", ".$row->location;
$output .= " data-photographlinks='" . $row->photographlinks ."'" ;
$output .= " data-emailid='" . $row->emailid ."'" ;
$output .= " data-contactnumber='". $row->contactnumber . "'>" ;
$output .= $row->host . ' , '.$row->propertyaddress . ' ,'.$row->price. ' ,'.$row->apartments_type. ' , '. $row->contactperson . ' , ' . $row->contactnumber. "</option>";
}
$output .= '</select>';
//var_dump($output);
return $output;
}`
my controller
public function test($id = null)
{
$this->layout->set(
array(
'property_address1' => $this->mdl_quotes->property_address1()
)
);
$this->load->model('mdl_quotes');
$this->layout->buffer('content', 'quotes/test');
$this->layout->render();
}
Dhaval Panchal check this updated screenshot
This is screenshot for better understanding.. please have a look Thanks
Insert CSS & JS file in your page then after JS file insert this code in your page.
<script type="text/javascript">
$(document).ready(function() {
$('#neww').select2();
});
</script>
To update options, see below code.
var option = new Option("text", "id");
$("#neww").append(option);
$("#neww").trigger("change");

Javascript function runs only once

Inside a php class I am defining a table which displays a list of clients which one need to contact. In column 7 I have integrated a checkbox so when the user call the client, he/she ticks into this checkbox.
The problem is that the JS function runs the first-time and then the second time it says: default.php?page=_PhoneBankingP1:1 Uncaught ReferenceError: contacted is not defined(…)
The modules in use are listed below:
public function phonebank($townCode,$streetCode){
$query = "SELECT clientId, clientFirstname1, clientLastname1, clientAddress, ";
$query .= " clientMailshot, clientPhone1, clientMobile1, clientContacted, min(clientDoB) ";
$query .= "FROM _clients ";
$query .= "WHERE _clients.streetCode = '{$streetCode}' and ";
$query .= " _clients.townCode = '{$townCode}' and ";
$query .= " _clients.GE = 'Y' ";
$query .= "GROUP BY clientAddress ";
$result = $this->db->query($query);
$output = "";
if ( $result->num_rows > 0 ){
$output .= "<div class='alert alert-info'><strong>Information!</strong> All the residents shown below have been extracted from the last Electoral Register.</div>";
$output .= "<table class='table table-striped' style='font-size:10pt;' id='myTable' >";
$output .= "<thead>";
$output .= "<tr>";
$output .= "<th>ID #</th>";
$output .= "<th>Name</th>";
$output .= "<th>Address</th>";
$output .= "<th>T</th>";
$output .= "<th>Phone</th>";
$output .= "<th>Mobile</th>";
$output .= "<th class='text-center'>Contacted</th>";
$output .= "</tr>";
$output .= "</thead>";
$output .= "<tbody>";
while ( $record = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$output .= "<tr>";
$output .= "<td><a href='default.php?page=_clientDetails&id=".$record['clientId']."&mode=edit' style='color: #000;'><span class='pb-clientId'>".$record['clientId']."</span></a></td>";
$output .= "<td><span class='pb-fullname'>".$record['clientFirstname1']." ".$record['clientLastname1']."</span></td>";
$output .= "<td>".$record['clientAddress']."</td>";
$output .= "<td>".$record['clientMailshot']."</td>";
$output .= "<td>".$record['clientPhone1']."</td>";
$output .= "<td>".$record['clientMobile1']."</td>";
// Makes a checkbox selected
if ( $record['clientContacted'] == 'Y'){
$optContacted = ' checked ';
} else {
$optContacted = '';
}
//$output .= "<td class='text-center' ><button id='btn-contacted-".$record['clientId']."' onclick='street.clientContacted("{$record['clientId']}","{$record['clientContacted']}")' class='btn btn-success'>Contacted</button></td>";
$output .= "<td align='center'>";
$output .= "<input type='checkbox' id='col7-".$record['clientId']."' onclick='contacted("".$record['clientId']."");' value='1' ".$optContacted." />";
$output .= "</td>";
$output .= "</tr>";
}
$output .= "</tbody>";
$output .= "</table>";
$output .= "<br/>";
echo $output;
} else {
echo "No Clients Found in this street";
}
}
Then the test JS function required to update the MYSQL is:
function contacted(id) {
var clientId = id;
var col7 = "col7-"+clientId;
var col7value = $("#"+col7).is(':checked');
var data = id+"\n"+col7+"\n"+col7value;
alert(data);
//Read checkbox state
if (col7value =='false'){
contacted = 'N';
} else {
contacted = 'Y';
}
$.ajax({
type: "POST",
url: "_backend/_core/_database/update_Phonebank.php",
data: {
"id": clientId,
"contacted": contacted
},
dataType: "text",
success: function(data){
}
})
}
I will appreciate if you can help me out to decide my the function is not being read the second time.
You define a function:
function contacted(id) {
//...
}
But within that function, you overwrite the function with a value:
contacted = 'N';
So the next time you try to invoke contacted() you're trying to call a string as if it was a function.
Give your variables unique names:
var wasContacted = '';
//...
wasContacted = 'N';
// etc.
That way you're not overwriting things you don't want to overwrite.
Additionally, using the var keyword to declare your variables will define them within that specific scope (such as within that function), instead of just putting them on the window object. (You can have variables of the same name in different scopes without affecting each other.)

Create html table in php using foreach() and strpos()

A table is being built with every product/brand/condition/qty added and sent to my email. However, if one is left blank, it will destroy the table format. I have tried if/ else statements, isset/!empty, along with anything else I can think of. I want to add blank columns/ rows to insert if left blank.
Since I am using a counter (product_1, product_2) with every added item and there is no limit, I am using strpos to find and "quickly" add to the table.
-- I am unable to attach pictures with this being my first post. --
Here's what I have now and works great when no fields are left blank:
$content .= "<table rules='all' style='border-color: #666; width: 800px; border: 1px solid black; border-collapse: collapse; margin: 0 auto;'>\r\n";
foreach($_POST as $key => $value) {
$partqty = strpos($key, 'Part_Quantity');
$partcond = strpos($key, 'Part_Condition');
$partbrand = strpos($key, 'Part_Brand');
$partmodel = strpos($key, 'Part_Model');
if ($partqty === 0) {
$content .= "<tr>\r\n";
$content .= " <td style='width:15%;'><input value='" . $value . "' style='border: none; width:100%;'></td>\r\n";
}
if ($partcond === 0) {
$content .= " <td style='width:65%;'><input value='" . $value . "' style='border: none; width:100%;'></td>\r\n";
}
if ($partbrand === 0) {
$content .= " <td style='width:10%;'><input value='" . $value . "' style='border: none; width:100%;'></td>\r\n";
}
if ($partmodel === 0) {
$content .= " <td style='width:10%;'><input value='" . $value . "' style='border: none; width:100%;'></td>\r\n";
$content .= "</tr>\r\n";
}
}
$content .= "</table>\r\n";
This is an idea of what I would like to do but doesn't work.
foreach($_POST as $key => $value) {
$partqty = strpos($key, 'Part_Quantity');
$partcond = strpos($key, 'Part_Condition');
$partbrand = strpos($key, 'Part_Brand');
$partmodel = strpos($key, 'Part_Model');
if ($partqty === 0) {
$content .= "<tr>\r\n";
$content .= " <td style='width:15%;'><input value='" . $value . "' style='border: none; width:100%;'></td>\r\n";
}
if ($partqty === false) {
$content .= "<tr>\r\n";
$content .= " <td style='width:15%;'><input value='empty' style='border: none; width:100%;'></td>\r\n";
}
if ($partcond === 0) {
$content .= " <td style='width:65%;'><input value='" . $value . "' style='border: none; width:100%;'></td>\r\n";
}
if ($partcond === false) {
$content .= " <td style='width:65%;'><input value='empty' style='border: none; width:100%;'></td>\r\n";
}
if ($partbrand === 0) {
$content .= " <td style='width:10%;'><input value='" . $value . "' style='border: none; width:100%;'></td>\r\n";
}
if ($partbrand === false) {
$content .= " <td style='width:10%;'><input value='empty' style='border: none; width:100%;'></td>\r\n";
}
if ($partmodel === 0) {
$content .= " <td style='width:10%;'><input value='" . $value . "' style='border: none; width:100%;'></td>\r\n";
$content .= "</tr>\r\n";
}
if ($partmodel === false) {
$content .= " <td style='width:10%;'><input value='empty' style='border: none; width:100%;'></td>\r\n";
$content .= "</tr>\r\n";
}
}
Print_r example :
Array (
[Part_Quantity_1] => 1
[Part_Condition_1] => New
[Part_Brand_1] => brand1
[Part_Model_1] => model1
[Part_Quantity_2] => 2
[Part_Condition_2] => New
[Part_Brand_2] => 2
[Part_Model_2] => 2
[Estimated_Total] => 0
[Estimated_Hours] => 0
[Name] => JohnDoe
[Email] => test#test.com
[Email_Verify] => test#test.com
[Confirmation] => I agree
[NameID] => form2-name
[EmailID] => form2-email
[HoursID] => form2-hours
[AjaxCall] => form2_ajax
)
try this.
// set dummy $_POST
$_POST = [
'Part_Quantity_1' => '1',
'Part_Condition_1' => 'New',
'Part_Brand_1' => 'brand1',
'Part_Model_1' => 'model1',
'Part_Quantity_2' => '2',
'Part_Condition_2' => 'New',
'Part_Brand_2' => '2',
'Part_Model_2' => '2',
'Part_Quantity_3' => '3',
'Estimated_Total' => '0',
'Estimated_Hours' => '0',
'Name' => 'JohnDoe',
'Email' => 'test#test.com',
'Email_Verify' => 'test#test.com',
'Confirmation' => 'I agree',
'NameID' => 'form2-name',
'EmailID' => 'form2-email',
'HoursID' => 'form2-hours',
'AjaxCall' => 'form2_ajax'
];
$parts = [];
foreach ($_POST as $key => $value) {
if (preg_match('#^Part_(?<type>Quantity|Condition|Brand|Model)_(?<counter>\d+)$#', $key, $matches) === 1) {
if (!isset($parts[$matches['counter']])) {
$parts[$matches['counter']] = array_fill_keys(['Quantity', 'Condition', 'Brand','Model'], 'empty');
}
$parts[$matches['counter']][$matches['type']] = $value;
}
}
$rows = array_map(function($part) {
$cells = [];
foreach ($part as $key => $value) {
$value = htmlspecialchars($value);
$width = null;
switch($key) {
case 'Quantity':
$width = "15%";
break;
case 'Condition':
$width = "60%";
break;
case 'Brand':
case 'Model':
$width = "10%";
break;
}
$cells[] = " <td style=\"border: none; width: {$width};\"><input value=\"{$value}\"></td>";
}
return implode("\n", $cells);
}, $parts);
$table = "<tr>\n" . implode("\n<tr>\n", $rows) . "\n</tr>\n";
echo $table;
Not sure what the expected output or the post data is but this should work, it's untested though. I also noticed you aren't outputting the heading of the rows anywhere
foreach($_POST as $key => $value) {
switch($key) {
case 'Part_Quantity':
$width = "15%";
break;
case 'Part_Condition':
$width = "60%";
break;
default:
$width = "10%";
break;
}
$content = "<tr>";
$content .= "<td style='width:".$width.";'><input value='" . (is_int($value) ? $value : 'empty' . "' style='border: none; width:100%;'></td>";
$content .= "</tr>";
}

Using JSON xmlHttprequest to read database from web server and to display the data?

I am new to JSON and phonegap, i am try to develop an application to display the data from webserver but i can't display the data in web-view on the mobile device, i don't know what mistake i made. Here is my main html code:
<html>
<head>
<style>
h1 {
border-bottom: 3px solid #cc9900;
color: #996600;
font-size: 30px;
}
table, th , td {
border: 1px solid grey;
border-collapse: collapse;
padding: 5px;
}
table tr:nth-child(odd) {
background-color: #f1f1f1;
}
table tr:nth-child(even) {
background-color: #0055cc;
}
</style>
</head>
<body>
<div id="id01"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://databaseofalrais.site90.net/";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response) {
var arr = JSON.parse(response);
var i;
var out = "<table>";
for (i = 0; i < arr.length; i++) {
out += "<tr><td>" +
arr[i].Name +
"</td><td>" +
arr[i].Street +
"</td><td>" +
arr[i].Phone +
"</td><td>" +
arr[i].Pincode +
"</td><td>" +
arr[i].Water +
"</td><td>" +
arr[i].Elec +
"</td></tr>";
}
out += "</table>"
document.getElementById("id01").innerHTML = out;
}
</script>
</body>
</html>
My database hosted in the url i mention in the code and here is the php code to access the database and make it as an array.
header("Access-Control-Allow-Origin: *");
header("Content-Type: text/html; charset=UTF-8");
$mysql_host = "mysql3.000webhost.com";
$mysql_database = "a4217438_data";
$mysql_user = "a4217438_admin";
$mysql_password = "admin123";
$conn = new mysqli($mysql_host, $mysql_user, $mysql_password, $mysql_database);
$result = $conn->query("SELECT * FROM Propertylist");
$outp = "[";
while ($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "[") {
$outp .= ",";
}
$outp .= '{"Name":"' . $rs["CompanyName"] . '",';
$outp .= '"Street":"' . $rs["street"] . '",';
$outp .= '"Phone":"' . $rs["phone"] . '"}';
$outp .= '"Pincode":"' . $rs["pincode"] . '"}';
$outp .= '"Water":"' . $rs["water"] . '"}';
$outp .= '"Elec":"' . $rs["ele"] . '"}';
}
$outp .="]";
$conn->close();
echo($outp);
If you need to use the data in mobile you have to try json array or xml. Try json_encode($return) to convert the output in array object.
I give you example try to use it in:
$result = mysqli_query($con, "SELECT * FROM Propertylist'");
while ($row = mysqli_fetch_array($result)) {
$return1['Area'] = $row['CompanyName'];
$return['result'][] = $return1;
}
$return['error'] = 'Yes';
echo json_encode($return);
exit;

Categories