How to convert xmlhttp.responseText to js array
this is my {"name":"Eswara Manikanta Varma","email":"eswar1251#gmail.com","mobile":"9966578911"} getting from xmlhttp.responseText so now i want to convert in js array..
when ever i'm alerting var object the alert seem like this [object Object]
I would like to print it as jsarray[mobile]
my page 1 :
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Invoice</title>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
<script>
function showUser(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4)
{
var object = JSON.parse(xmlhttp.responseText);
alert(object);
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<header>
<h1>Invoice</h1>
<address contenteditable>
<p>Jonathan Neal</p>
<p>101 E. Chapman Ave<br>Orange, CA 92866</p>
<p>(800) 555-1234</p>
</address>
<span><img alt="" src="logo.png"><input type="file" accept="image/*"></span>
</header>
<article>
<h1>Recipient</h1>
<address contenteditable>
<p>Some Company<br>c/o Some Guy</p>
</address>
<form>
<table class="meta">
<tr>
<th><span contenteditable>Invoice #</span></th>
<td><span contenteditable>101138</span></td>
</tr>
<tr>
<th><span contenteditable>Date</span></th>
<td><span contenteditable>January 1, 2012</span></td>
</tr>
<tr>
<th><span contenteditable>Amount Due</span></th>
<td><span id="prefix" contenteditable>$</span><span>600.00</span></td>
</tr>
</table>
<table class="inventory">
<thead>
<tr>
<th><span contenteditable>Item</span></th>
<th><span contenteditable>Description</span></th>
<th><span contenteditable>Rate</span></th>
<th><span contenteditable>Quantity</span></th>
<th><span contenteditable>Price</span></th>
</tr>
</thead>
</body>
</html>
page 2 :
<?php
$q = $_GET['q'];
$con = mysqli_connect('localhost','root','enter','esmart');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,'esmart');
$sql="SELECT * FROM suppliers WHERE name LIKE '%$q%'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
$x['name']=$row['name'];
$x['email']=$row['email'];
$x['mobile']=$row['mobile'];
}
echo json_encode($x);
mysqli_close($con);
?>
I think your problem is in the PHP code.
with this:
while($row = mysqli_fetch_array($result))
{
$x['name']=$row['name'];
$x['email']=$row['email'];
$x['mobile']=$row['mobile'];
}
echo json_encode($x);
You're going to get only the last row of your query.
To be able to get an array you may need something like this:
$response = array();
while($row = mysqli_fetch_array($result))
{
$x['name']=$row['name'];
$x['email']=$row['email'];
$x['mobile']=$row['mobile'];
$response[] = $x;
}
echo json_encode($response);
Now you'll get [{"name":"Eswara Manikanta Varma","email":"eswar1251#gmail.com","mobile":"9966578911"}, ...] and after JSON.parse it will be an array of objects.
try to use:
mysqli_fetch_assoc($result)
instead of
mysqli_fetch_array($result)
Related
I have posted this question in multiple places, but haven't had any responses so going to try here. I am creating a Wordpress plugin. Part of the plugin loads a dropdown from a database. When an option is selected from the dropdown, a form is loaded from an external page using Javascript. The issue I am having is that when I try to load the wp_editor, it is only partially loaded. It is missing the toolbars. Any help is appreciated.
Here is an image of what I am getting.
Here is the javascript used to load the page:
function showeditevent(str) {
var location1 = window.location.href;
var directoryPath = '<?php echo plugins_url(); ?>';
//alert(directoryPath);
if (str == "") {
document.getElementById("txtEditevent").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtEditevent").innerHTML = this.responseText;
}
};
xmlhttp.open("GET",directoryPath+"/events/editevent.php?q="+str,true);
xmlhttp.send();
}
}
And here is editevent.php
<script src="../../../wp-includes/js/tinymce/tiny_mce_popup.js"></script>
<script src="../../../wp-includes/js/tinymce/tinymce.min.js"></script>
<?php
require_once('../../../wp-load.php');
require_once('../../../wp-includes/class-wp-editor.php');
//require_once('../../../wp-admin/admin-ajax.php');
global $wpdb;
$id = $_GET["q"];
$sql = $wpdb->get_row("SELECT * FROM " . $wpdb->prefix . "cmc_events where id=$id");
$title = $sql->title;
$date = $sql->date;
$time = $sql->time;
$info = $sql->info;
$filename = $sql->filename;
$newdate = DateTime::createFromFormat('m-d-Y', $date)->format('Y-m-d');
?>
<form name="editevent" action="" method="post" enctype="multipart/form-data">
<table>
<tr>
<th align="right" valign="top">Title:</th>
<td><input type="text" name="title" placeholder="Title" value="<?php echo $title; ?>" /></td>
</tr>
<tr>
<th align="right" valign="top">Date:</th>
<td><input type="date" name="newdate" value="<?php echo $newdate; ?>" /></td>
</tr>
<tr>
<th align="right" valign="top">Time:</th>
<td><input type="time" name="newtime" value="<?php echo $time; ?>" /></td>
</tr>
<tr>
<th align="right" valign="top">Information:</th>
<td>
<?php
$content = $info;
$editor_id = 'info';
$settings = array(
'textarea_name' => 'info',
'textarea_rows' => 10,
'tinymce' => array(
'width' => 1000
)
);
wp_editor( $content, $editor_id, $settings );
?>
</td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" name="save_edit_event" value="Save Edit"></td>
</tr>
</table>
</form>
Do you check if the current user can richedit by user_can_richedit() function? WP_Editor will only fully load when users can richedit.
I have an HTML table which I want to update every 1 second on page. It have few div and classes within. So I tried AJAX to update it every 1 second. HTML is this:-
<div class="abcd">
<div style='float: left;'>
<br><br>
<p style="padding-left:16px; font-size: 20px;">Amount(<?php echo $market; ?>) | Price(<?php echo $bm; ?>)   | Total(<?php echo $bm; ?>)</p>
<div class="panel-hello scrollbar" id="style-11">
<div class="data-table">
<table class="table table-hello table-bordered table-hover force-overflow" id="btcaddresses">
<tbody style="border: 1px solid green; height: 300px; overflow-y: scroll;">
</tbody>
</table>
</div>
</div>
</div>
And AJAX script:-
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementsById("btcaddresses").innerHTML=xmlhttp.responseText; // your div
}
}
xmlhttp.open("GET","getdatabase.php",true); //your php file
xmlhttp.send();
}
window.setInterval(function(){
loadXMLDoc();
}, 1000);
And getdabase.php contains:-
<?php
require('../setup.php');
$seql = "select price, sum(total), sum(aleft) from trade where status = 'active' and bm = 'USD' and m = 'BTC' and type = 'sell' group by price";
$query100 = mysqli_query($conn, $seql);
while ($row = mysqli_fetch_array($query100))
{
echo '<tr style="cursor: pointer; font-size: 15px;">
<td>'.number_format($row['sum(aleft)'], 8).'</td>
<td>'.number_format($row['price'], 8).'</td>
<td>'.number_format($row['sum(total)'], 8).'</td>
</tr>';
}
mysqli_close($conn);
?>
Problem is , it is not working and even if does it's not having any table classes specified in class.
<?php
require('../setup.php');
$seql = "select price, sum(total), sum(aleft) from trade where status = 'active' and bm = 'USD' and m = 'BTC' and type = 'sell' group by price";
$query100 = mysqli_query($conn, $seql);
$result = '';
while ($row = mysqli_fetch_array($query100))
{
$result .= '<tr style="cursor: pointer; font-size: 15px;">
<td>'.number_format($row['sum(aleft)'], 8).'</td>
<td>'.number_format($row['price'], 8).'</td>
<td>'.number_format($row['sum(total)'], 8).'</td>
</tr>';
}
mysqli_close($conn);
echo $result;
?>
This should work, but indeed you should return a json.
Edit : full html code working fine for me : (I had to remove some php parts)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div class="abcd">
<div style='float: left;'>
<br>
<br>
<!-- <p style="padding-left:16px; font-size: 20px;">Amount(<?php echo $market; ?>) | Price(<?php echo $bm; ?>)   | Total(<?php echo $bm; ?>)</p> -->
<div class="panel-hello scrollbar" id="style-11">
<div class="data-table">
<table class="table table-hello table-bordered table-hover force-overflow" id="btcaddresses">
<tbody style="border: 1px solid green; height: 300px; overflow-y: scroll;">
</tbody>
</table>
</div>
</div>
</div>
<script type="text/javascript">
function loadXMLDoc() {
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("btcaddresses").innerHTML = xmlhttp.responseText; // your div
}
}
xmlhttp.open("GET", "getdatabase.php", true); //your php file
xmlhttp.send();
}
window.setInterval(function () {
loadXMLDoc();
}, 1000);
</script>
</body>
</html>
I'm trying to make a poll, but the poll_results.txt file won't get written. I've tried on my Windows pc and my Linux server.
I'm using this example
index.html
<html>
<head>
<script>
function getVote(int) {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("poll").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","poll_vote.php?vote="+int,true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="poll">
<h3>Do you like PHP and AJAX so far?</h3>
<form>
Yes:
<input type="radio" name="vote" value="0" onclick="getVote(this.value)">
<br>No:
<input type="radio" name="vote" value="1" onclick="getVote(this.value)">
</form>
</div>
</body>
</html>
poll_vote.php
<?php
$vote = $_REQUEST['vote'];
//get content of textfile
$filename = "poll_result.txt";
$content = file($filename);
//put content in array
$array = explode("||", $content[0]);
$yes = $array[0];
$no = $array[1];
if ($vote == 0) {
$yes = $yes + 1;
}
if ($vote == 1) {
$no = $no + 1;
}
//insert votes to txt file
$insertvote = $yes."||".$no;
$fp = fopen($filename,"w");
fputs($fp,$insertvote);
fclose($fp);
?>
<h2>Result:</h2>
<table>
<tr>
<td>Yes:</td>
<td>
<img src="http://www.w3schools.com/php/poll.gif"
width='<?php echo(100*round($yes/($no+$yes),2)); ?>'
height='20'>
<?php echo(100*round($yes/($no+$yes),2)); ?>%
</td>
</tr>
<tr>
<td>No:</td>
<td>
<img src="http://www.w3schools.com/php/poll.gif"
width='<?php echo(100*round($no/($no+$yes),2)); ?>'
height='20'>
<?php echo(100*round($no/($no+$yes),2)); ?>%
</td>
</tr>
</table>
I've tried changing permission, but they all looked correct. Is there something wrong with the example?
I have an Ajax code that am using to get data from my php page, but it is not returning any data back to the Ajax, returning null value.
function getType(str){
$("#selectCat").html("Select the Catagory of " +str);
if (str.length == 0){
return;
}
if(window.XMLHttpRequest)
{ // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}else
{ // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById('category').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","OrderItem.php?q="+str,true);
xmlhttp.send();
}
and here is my php code
session_start();
$currentUser = $_SESSION["userID"];
include("include/dbcommon.php");
$value = $_GET['q'];
//echo $value;
$sqlString = "";
if($value == "dish"){
$sqlString = "select name from dishcategory";
}else if($value == "drinks"){
$sqlString ="select name from drinkscategory";
}else if($value == "desserts"){
$sqlString = "select name from dessertcategory";
}
$rs = customQuery($sqlString);
while($data= db_fetch_array($rs)){
echo "<option value='".$data['name']."'>".$data['name']."1</option>";
}
and my HTML part
<TABLE style="WIDTH:85%" cellSpacing=1 cellPadding=1 width="75%">
<TBODY>
<TR>
<TD> <STRONG>Ordered Item Category</STRONG></TD></TR>
<TR>
<TD> <input type="Radio" name="itemType" id="" class="selebtn" value="dish" onClick="getType(this.value)"> Dish <input type="Radio" name="itemType" id="" class="selebtn" value="drinks" onClick="getType(this.value)"> Drinks <input type="Radio" name="itemType" id="" class="selebtn" value="desserts" onClick="getType(this.value)"> Desserts
</TD></TR></TBODY></TABLE>
<TABLE>
<TBODY>
<TR><TD><span id="selectCat"></span></TD></TR>
<TR><TD><span id="selePan"><select name="itemcat" id="itemcat"><option value="">select</option><span id="category"></span></select></span></TD></TR>
</TBODY>
</TABLE>
please i can't get the why it is returning null value?
thanks in advance
Your HTML is invalid. You cannot have a span element as a child element of a select. Your problem is probably due to the browser performing error recovery and discarding the span element (that is certainly how Chrome reacts to your code).
Use a validator.
<!--viewservice.php-->
On blur i send data to get_service_category.php with the help of ajax function getservice_search. Before sending i alert the variable it give full string as Buff & Gelcoat [Acrylic Nail Enhancement] but when it is posted to get_service_category.php and then echoed back to the page it just print Buff after that it is trimmed
<label>Search Service</label>
<input type='text' name='country' id="select_service" value='' class='auto' onblur="getservice_search(this.value)"/>
<img src="img/icons/search-50.png" height="22" width="22" style="padding-left:5px;margin-bottom:-5px;cursor:pointer;" id="search" alt="Search" title="Click To Search" />
<script type="text/javascript" src="../js/jquery-1.9.1.js"></script>
<script type="text/javascript" src="../js/jquery-ui-1.10.3.custom.min.js"></script>
<script type="text/javascript">
$(function() {
//autocomplete
$(".auto").autocomplete({
source: "search_services.php",
minLength: 1
});
});
</script>
<script type="text/javascript">
function getservice_search(x)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("box1").innerHTML=xmlhttp.responseText;
}
}
var select_service = document.getElementById("select_service").value;
alert(select_service);
xmlhttp.open("GET","get_service_category.php?select_service="+select_service,true);
xmlhttp.send();
}
</script>
enter code here
<!--get_service_category.php -->
<?php
include('../config/connect.php');
include('unset_super_admin.php');
function clean($str)
{
$str = #trim($str);
if(get_magic_quotes_gpc())
{
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
if(isset($_GET['service_category']))
{
$service_category = $_GET['service_category'];
$sql ="select * from services where service_cat_id='$service_category' ";
}
else if($_GET['select_service'])
{
$select_service=clean($_GET["select_service"]);
$sql ="select * from services where service_name='$select_service' ";
}
else if($_GET['select_service']=="")
{
$sql ="select * from services";
}
$result_services = mysql_query($sql);
if($result_services)
{
echo $select_service;
?>
<table style="text-align:center;" class="viewcustomer">
<tr>
<th>Id</th>
<th>Service Name</th>
<th>Price</th>
<th>Action</th>
</tr>
<?php
while($rowresult=mysql_fetch_array($result_services))
{
echo "<tr>";
echo "<td>$rowresult[service_id]</td>";
echo "<td>$rowresult[service_name]</td>";
echo "<td>$rowresult[service_price]</td>";
echo '<td><Img src="img/icons/button_edit.gif" title="EDIT" alt="EDIT SERVICE" /> </td>';
echo "</tr>";
}
}
?>
You neglected to URL-encode your values properly – & in a query string separates parameters from each other, so ?select_service=Buff & Gelcoat… would mean one parameter named select_service with value Buff, and then a second parameter named Gelcoat….
Use encodeURIComponent on the value before putting it into the query string.