I have the following jquery statement:
$("#add").click(
function(event){
var groupName = $("#groupName option:selected").text();
var studentsToAdd = $('select#mainList').val();
var mode = "exempt";
$.post(
"addToList.php",
{ studentsToAdd: studentsToAdd, mode: mode },
function(data) {
$('#groupList').html(data[exemptList]);
$('#mainList').html(data[nonexemptList]);
}
);
});
With the following php code:
$studentsToAdd = $_REQUEST['studentsToAdd'];
$arrayLength = count($studentsToAdd);
$exemptList = "";
$nonexemptList = "";
for ($i=0;$i<$arrayLength;$i++){
$result = mysql_query("UPDATE students SET exempt=1 WHERE id = '$studentsToAdd[$i]'");
}
$result = mysql_query("SELECT * from students WHERE exempt = 1");
while($row = mysql_fetch_array($result))
{
$exemptList = $exemptList . "<option value=\"" . $row['id'] . "\">" . $row['last'] . ", " . $row['first'] . "</option>";
}
$result = mysql_query("SELECT * from students WHERE exempt = 0");
while($row = mysql_fetch_array($result))
{
$nonexemptList = $nonexemptList . "<option value=\"" . $row['id'] . "\">" . $row['last'] . ", " . $row['first'] . "</option>";
}
$data = array(
'exemptList' => $exemptList,
'nonexemptList' => $nonexemptList
);
echo json_encode($data);
I am trying to update both mainList and exemptList select elements with the single jQuery .post. It is not working. Thoughts?
If your php code is in another page or in a function, which you haven't mentioned, return $data instead of return json_encode($data) should work and leave it as an array. Otherwise you are getting a json string back, from json_encode(), which you need to parse into a javascript object, so try:
var decoded = $.parseJSON(data);
$('#groupList').html(decoded.exemptList);
$('#mainList').html(decoded.nonexemptList);
At least from what i can tell at first glance and 11 pm.
Edit: You can always try console.log(data) with Firefox Firebug plugin and see what you are getting from the server and then see if you need to decode what you are getting, change how you write the array or quotes or whatever.
A possible solution is to decode the JSON object when it is returned. Additionally, the stuff inside the [] needs to have quotes around it:
function(data) {
var json = JSON.parse(data);
$('#groupList').html(json["exemptList"]);
$('#mainList').html(json["nonexemptList"]);
}
Also, maybe try $.ajax, and set dataType to json (even though the default is intelligent guess, which should work anyway since the PHP is sending a JSON object.)
Maybe you could try:
function(data) {
$('#groupList').html(data["exemptList"]);
$('#mainList').html(data["nonexemptList"]);
}
exemptList and nonexemptList were probably treated as variables instead of names.
Related
Ajax call to the mysql data base using data1.php file with pdo returns hmtl strings that are put into an array, encoded with json and sent to the ajax response function for display in html. Of course the elements in the array have tags and quotations, which are difficult to remove. Easiest and closest solution so far is to replace the quotes in the strings with javascript .replace(). This doesn't work for the array of arrays unless the single element is referenced. What's the way around this? Here is the code.
Ajax call:
function processForm_L(){
var topic = $("#topic").val();
// send data
$.ajax({
url: "../php/get_data1.php",
data: {
topic1:topic},
type: 'POST',
dataType: 'json',
success: processResult_L
}); // end .onclick
}
The response function:
function processResult_L(data, textStatus){
// Required Callback Function
if(data['status']['response'] == 1){
//if(data[0] == 1){
table_1 = [];
table_2 = [];
table_3 = [];
table_1 = data.table['a'].replace( /"/g,"");
table_2 = data.data.replace(/"/g,"");
table_3 = data.table['b'].replace( /"/g,"");
//table_1 = JSON.parse(data.table['a']);
//table_2 = JSON.parse(data.data);
//table_3 = JSON.parse(data.table['b']);
//console.log(table_1);
console.log(table_2);
//console.log(table_3);
}//end if response == 1
else if(data.response == 0){
//var response = data + textStatus;
var table_4 = data.error;
$('#display').html(table_4);
}//end if response==0
}//end process results
The query part of get_data1.php
<?php
$ret_s = Array();//return status
$ret_t = Array();//return table
$ret_d = Array();//return data
$result = Array();
$row_1 = 1;
if(!empty($_POST)){
try{
if(!empty($_POST)){
//connect to database and insert data
// include "db_connect_df.php";
// select everything from the raw_data database
$sql = "SELECT * FROM `raw_data`";
// prepare the sql statement
$stmt_s = $db->prepare($sql);
$stmt_s->execute();
$result = $stmt_s->fetchAll(PDO::FETCH_ASSOC);
//set response variable
$ret_s['response'] = 1;
//table header
$ret_t['a'] ="<table id='display_table'><tr><th>ID</th><th>Organization</th><th>Contact Names</th><th>Telephone</th><th>Email</th><th>Website</th><th>Country</th><th>Region</th><th>City</th><th>Street</th><th>Unit</th><th>Postal Code</th><th>Topic</th><th>Message</th><th>Date</th></tr>";
//fetch each row from database as html
foreach($result as $row){
$ret_d[$row_1] = "<tr>" ."<td>" . $row['ID'] . "</td>" ."<td>" .
$row['Organization'] . "</td>" ."<td>" . $row['Telephone'] . "</td>" . "<td>" . $row['Email'] . "</td>" ."<td>" . $row['Website'] . "</td>" ."<td>" . $row['Country'] . "</td>" ."<td>" . $row['Region'] . "</td>" ."<td>" . $row['City'] . "</td>" ."<td>" . $row['Street'] . "</td>" ."<td>" . $row['Unit'] . "</td>" ."<td>" . $row['Postal_Code'] . "</td>" ."<td>" . $row['Topic'] . "</td>" ."<td>" . $row['Message'] . "</td>" ."<td>" . $row['ts'] . "</td>" ."</tr>";
$row_1++;
}
// end table tag
$ret_t['b'] = "</table>";
//echo and encode array
echo json_encode(array('status' => $ret_s, 'table' => $ret_t,'data'=> $ret_d),JSON_HEX_QUOT|JSON_HEX_TAG);
// echo json_encode(stripslashes_nested(array('status' => $ret_s, 'table' => $ret_t,'data'=> $ret_d)),JSON_HEX_QUOT|JSON_HEX_TAG);
}//end connect
}//end try
catch (PDOException $e) {
$error16 = '<span class="error_s">Try again another time.</span>';
$error17 = '<span class="error_s">ERROR:' . $e->getMessage();
$ret_s['response'] = 0;
$ret_s['error'] = $error16 . $error17;
echo json_encode($ret_s);
} //end failure
}//end if is !empty($_POST)
?>
Note: this queries a localhost database served through xampp. This isn't all the code but everything works just fine except the following:
1) table_2 = data.data.replace(/"/g,""); returns 'data.data.replace() is not a function, because the array is an object not a string
2) when comment out above line and comment in only console.log(table_1); result in console is:
<table id='display_table'><tr><th>ID</th><th>Organization</th><th>Contact Names</th><th>Telephone</th><th>Email</th><th>Website</th><th>Country</th><th>Region</th><th>City</th><th>Street</th><th>Unit</th><th>Postal Code</th><th>Topic</th><th>Message</th><th>Date</th></tr> So that works.
3) similarly commenting in only console.log(table_3); returns in console:
</table> so that also works.
4) if comment in table_2 = data.data; and enter table_2 into console result is:
undefined
5) tried this code to remove quotes from the array of arrays:
a) putting a function in the js init file for the page:
function replace_quotes(x){
for(var i=0; i < x.length; i++) {
x[i] = x[i].toString().replace(/"/g,"");
}
}
and using that function on the data array in the data object created by the response callback function (so x = data.data)
result is undefined, and it doesn't work.
JSON.parse(table_1); just runs into a < right away and won't parse, for any of the strings in the data array (table_2 or table 3).
adding JSON_HEX_QUOT | JSON_HEX_TAG didn't work.
Presumably looping through the array data.data with a function and using .replace() and a reg exp to replace quotes with nothing should be the easiest solution. Any tips on how to loop through a json_encoded array of html strings in an array returned in an ajax callback?
Don't replace anything anywhere. The only thing you need is to add htmlspecialchars() when you building the HTML string.
<?php
// ...
$rows = [];
foreach ($result as $r) {
$rows[] = '<tr><td>'.htmlspecialchars($r['id'])
.'</td><td>'.htmlspecialchars($r['phone_number'])
.'</td></tr>';
}
header('Content-Type: application/json; encoding=utf-8');
echo json_encode(array('table_rows' => join("\n", $rows)));
Then, when you receive such JSON, just put it into HTML as it is.
$('table#display').html(received_data.table_rows);
But there is better way to implement this. -- Send only data without markup via JSON and build markup in JS:
<?php
// ...
$rows = [];
foreach ($result as $r) {
$rows[] = [
'id' => $r['id'],
'phone_number' => $r['phone_number']
];
}
header('Content-Type: application/json; encoding=utf-8');
echo json_encode(array('table_rows' => $rows));
And then:
// ...
for(var i = 0; i < received_data.table_rows.length; i++) {
var r = received_data.table_rows[i];
$table.append($('<tr>')
.append($('td').text(r.id))
.append($('td').text(r.phone_number))
);
}
PHP case 0, file called from ajax dropdown selector form submission:
if(!empty($_POST)){
//connect to database and insert data
// include "db_connect_df.php";
include "db_connect_df_test.php";
//switch statement for mysql queries based on dropdown selected
switch($topic_2){
case "Address":
//set response variable
$ret_s['response'] = 0;
// select organization address
$sql = "SELECT IFNULL(ID, '--') AS ID,
IFNULL(Organization, '--') AS Organization,
IFNULL(Contact_Names, '--') AS Contact_Names,
IFNULL(City, '--') City,
IFNULL(Street, '--') AS Street,
IFNULL(Unit, '--') AS Unit,
IFNULL(Postal_Code, '--') AS Postal_Code,
IFNULL(Region, '--') AS Region,
IFNULL(Country, '--') AS Country,
IFNULL(ts, '--') AS ts
FROM `raw_data`";
// prepare the sql statement
$stmt_s = $db->prepare($sql);
$stmt_s->execute();
$result = $stmt_s->fetchAll(PDO::FETCH_ASSOC);
// extract table rows
foreach($result as $row){
$ret_d[$row_1] = [
'Id'=> $row['ID'],
'Organization' => $row['Organization'],
'Contact_Names' => $row['Contact_Names'],
'City'=> $row['City'],
'Street'=> $row['Street'],
'Unit' => $row['Unit'],
'Postal_Code' => $row['Postal_Code'],
'Region' => $row['Region'],
'Country'=> $row['Country'],
'Date'=> $row['ts']
];//end load data from data base
$row_1++;
}//end table data as rows
break;
Javascript init file, case 0 section of ajax response function:
function processResult_L(data, textStatus){
// Required Callback Function
//create dom elements for table head and body
//to check variables in dev console remove 'var'(make public)
var $table = $("<table id='display_table'>");
$table.append($('<tbody>'));
//create response array
var response = {};
response = data['status']['response'];
//create row array for building table data
var r = [];
switch(response){
case 0: /*Address case */
// build table header
$table.append($('<tr>')
.append($('<th>').text('ID'))
.append($('<th>').text('Organization'))
.append($('<th>').text('Contact'))
.append($('<th>').text('City'))
.append($('<th>').text('Street'))
.append($('<th>').text('Unit'))
.append($('<th>').text('Post Code'))
.append($('<th>').text('Region'))
.append($('<th>').text('Country'))
.append($('<th>').text('Date')));
// build table content
for(var i = 0; i < data.table_rows.length; i++) {
r[i] = data.table_rows[i];
$table.append($('<tr>')
.append($('<td>').text(r[i].Id))
.append($('<td>').text(r[i].Organization))
.append($('<td>').text(r[i].Contact_Names))
.append($('<td>').text(r[i].City))
.append($('<td>').text(r[i].Street))
.append($('<td>').text(r[i].Unit))
.append($('<td>').text(r[i].Postal_Code))
.append($('<td>').text(r[i].Region))
.append($('<td>').text(r[i].Country))
.append($('<td>').text(r[i].Date))
); // end append table content
} // end build table content
break;
I´m stuck for 3 days trying to figure it out what is the cause of this problem. Lets go to the details:
A jquery ajax call loads a php file named HELPER, wich when loaded includes another php file called F1 that creates html table trough mysqli queries. Ajax get the response and paste the string in a html DIV. The response is a html table. The web server is apache2.2.
Problem is, the code runs in less than 1 second, but the response takes about 50 seconds. The response is only 20 KB.
Some simple HTML table code.
<?php
if (!$res = $sql->query("A QUERY")) { die('custom error 46'); }
if (!$res->num_rows > 0) { die('custom error 47'); }
$myStr = '';
while ( $row = $res->fetch_object() ) {
if ($row->summary == "1") {
$mysum = " class='qtfck-table-summary'";
$myIsSum = "Sim";
} else {
$mysum = "";
$myIsSum = "";
}
if(intval($row->id_centrodecusto) > 0) {
$mycc = "<input type='checkbox' name='" . $row->id_task . "' value='" . $row->id_centrodecusto . "' CHECKED />";
} else {
$mycc = "<input type='checkbox' name='" . $row->id_task . "' value='' />";
}
$myj = " style='padding-left:" . intval($row->depth) * 10 . "px'";
$myStr = "<tr%s><td>%s</td><td><center>%s</center></td><td><center>%s</center></td><td%s>%s</td><td><center>%s</center></td><td><center>%s</center></td></tr>";
echo sprintf($myStr,$mysum,$row->wbs,$row->depth,$myIsSum,$myj,$row->name,$row->uniqueid,$mycc);
}
?>
Html Table closure
The timmings:
PHP START: 0.92 sec
PHP END: 0.98 sec
JS RECEIVED DATA: 49.50 sec
JS PROCESSED DATA: 49.56 sec
I did some digging and it looks like the apache/httpd process (shell via top command) is going nuts, taking 100% CPU load during the full 50 seconds of wait.
BUT here´s something funny. If I change the string generated by the sprintf function and, let´s say, set some random string, there´s no problem at all.
Some simple HTML table code.
<?php
if (!$res = $sql->query("A QUERY")) { die('custom error 46'); }
if (!$res->num_rows > 0) { die('custom error 47'); }
$myStr = '';
while ( $row = $res->fetch_object() ) {
if ($row->summary == "1") {
$mysum = " class='qtfck-table-summary'";
$myIsSum = "Sim";
} else {
$mysum = "";
$myIsSum = "";
}
if(intval($row->id_centrodecusto) > 0) {
$mycc = "<input type='checkbox' name='" . $row->id_task . "' value='" . $row->id_centrodecusto . "' CHECKED />";
} else {
$mycc = "<input type='checkbox' name='" . $row->id_task . "' value='' />";
}
$myj = " style='padding-left:" . intval($row->depth) * 10 . "px'";
echo "<TR><TD>eZ6OnMCZgygePZeUQHcqbOmHQDxhDF4KzfkgOd198xhPFV2rRezlIqBdJLY2TcNlO0PLUmK6CQI9PQMZgkLrcoeYIYhM0x9xK4yQXIFb5SLdq32</TD><TD>UTuQPG9WCbOswuJMdkkckMoAW49C71IN9qKdk8OAdRRV3ZuCYxM5GEZKrXXrwE7cWHKTcXTiO4KwGjh1ejENvduZvEVkwA3zoHbWkzEjtFa1GMaNzD2rqswEDSoQix2CLziBNiHD8zliSWu5rvU8wd6dodWBvubvog</TD></TR>";
}
?>
Html Table closure
The response to this request is 50 KB in size.
The timmings:
PHP START: 0.78 sec
PHP END: 0.81 sec
JS RECEIVED DATA: 1.13 sec
JS PROCESSED DATA: 1.19 sec
What I have already tried:
Use ob_start() and ob_end_flush().
Set apache mpm prefork SendBufferSize to a higher value, but I believe it was a long shot, as the longer response (50KB) has no problem.
Use echo instead of sprintf.
Anyone has a clue?
Best regards.
I don´t know why but the problem was caused by the "center" html tags. Somehow the presence of the center tags slowdown the response. I just removed them and created appropriate css classes using "text-align: center" and the problem was gone.
I also did try avoiding PHP to echo the HTML. Even then the tags causes problems again.
Here´s the fix. I just don´t have an explanation for it.
I am using jQuery sortable to manipulate image order and write to a DB. That functionality works well.
PHP
echo "<div class='revisionNum'>";
echo "<ul id='sortable_" . $count ."'>";
while($row = mysql_fetch_array($result)) {
$sortImageName = $row['OrgImageName'];
$sortPath = "../data/gallery/" . $galleryID . "/images/album/" . $sortImageName;
echo "<li class='sortPhotos' id='item_{$row['id']}' >";
echo '<img class="sortImage" src="'. $sortPath .'"/>';
echo "<p>" . $sortImageName . "</p>";
echo "</li>";
}
echo "</ul>";
echo "</div>";
jQuery
//make sortable
$(".revisionNum").each(
function(e) {
num = e + 1;
$("#sortable_" + num).sortable(
{stop:function(i) {
serial = $("#sortable_" + num).sortable("serialize");
$.ajax({
type: "GET",
url: "../albumUploader/queries/sort.php",
data: serial
});
},
opacity:1.0,
//cursor: move
});
});
MYSQL
foreach($_GET['item'] as $key=>$value) {
mysql_query(" UPDATE galleryimage
SET sort = '{$key}'
WHERE id = '{$value}'
");
}
The issue is when I have multiple <div class=''revisionNum> i am only grabbing the serial = $("#sortable_" + num) of the last UL if the [.revisionNum], not the actual UL that I am sorting. Thanks for the help on this. Let me know if further clarification is needed.
I am not sure I fully understand your question, but I think you are looking for the following:
The variable num will change every loop you make in the each-loop. But at the end it will have the value of the last loop. Because num seems to be a global variable you can't call it in the stop function. Then it will just use the last value it had. The value of the last loop. (Explains your problem)
To solve this I recommend to change your code to:
$(".revisionNum").each(
function(e) {
$(this).children("ul").sortable(
{stop:function(i) {
num = $(this).children("ul").attr("id").replace("sortable_", "");
serial = $(this).children("ul").sortable("serialize");
...
$(this) refers to the $(".revisionNum") you are looping through and it will be remembered, also in the stop function.
Here's my problem: I have two select fields in my web application.
The second one depends on the choice made on the first one. The first one is populated from my database with the classical:
<?php
//connection to database in an include file
$query = "SELECT DISTINCT platform
FROM Appversions";
$res = mysql_query($query);
while($row = mysql_fetch_array($res)) {
echo "<option value=\"\"" . $row['platform'] . "</option>\n";
}
?>
which is working just fine.
But then I need to populate my second select with a query that would look like:
SELECT version
FROM Appversions
WHERE platform = <choice made in first select>;
I understand that I need to use JavaScript with an onChange function call to do that, but I can't figure out what that function should look like or how it will have access to my query result.
Usually i have this jquery code:
$('#select1').change(function(){
if($(this).val() == ''){
$('#select2').attr('disabled', 'true');
}else{
var select1 = $(this).val();
$.getJSON('index.php',
{
option: "com_spin",
controller: "guest",
task: "getProvincieByRegionId",
idRegione: idRegione
},
function(json){
$('#select2').html(json.html);
}
);
$('#select2').removeAttr('disabled');
}
});
in php i have something like this (basically i return the html for the options:
Zend_Loader::loadClass ( 'Zend_Json' );
$idRegione = JRequest::getVar ( "idRegione" );
$modelProvince = new Spin_lkpprovincia ();
$provincie = $modelProvince->getElencoProvinciePerRegione ( $idRegione );
$html = "<option value=''>Selezionare una voce</option>";
foreach ( $provincie as $provincia ) {
$html .= "<option value='" . $provincia ['idProvincia'] . "'>" . $provincia ['nome'] . "</option>";
}
$json = array (
success => "OK",
html => $html );
$json = Zend_Json::encode ( $json );
echo $json;
die ();
I have a php loop that is echoing out geolocation values. How can I get it to write those values to a javascript array, so I can then use them to plot points on an HTML5 canvas?
The php loop is as follows
<ul id = "geo-list">
<?php foreach($data as $phrase) { ?>
<li><?php
if ($phrase->geo != false) {
echo " | From (";
echo $phrase->geo->coordinates[0];
echo ",";
echo $phrase->geo->coordinates[1];
echo ")";
} else {
echo " | No Location Data";
}
?>
</li>
<?php } ?>
</ul>
Did you try
var myJavascriptData = <?= json_encode($php_data) ?>;
You might want to take advantage of the JSON library for PHP.
The cleanest way to pass data to a browser's javascript program is to put it into a "hidden" html table.
The html should look something like
echo "\n<TABLE style='display: none;' id='DATTAB' >" ;
get_rows();
while ($cf = next_row()) {
echo "\n <TR>";
echo "\n<TD>" . $cf['KEY'] . "</TD>";
echo "\n<TD>" . $cf['COL1'] . "</TD>";
echo "\n<TD>" . $cf['COL2'] . "</TD>";
echo " </TR>";
}
echo "\n</TABLE>";
This table is then easily accessable from your javascript:-
var dtab = document.getElementById("DATATAB");
var rows = dtab.getElementsByTagName("tr");
for (var r = 0; r < rows.length ; r++) {
row = rows[r];
item_key = row.cells[0].innerHTML;
item_col1 = row.cells[1].innerHTML;
item_col2 = row.cells[2].innerHTML;
// do your thing here ......
}
Alternatively you could look at using the AJAX libraries like prototype or dojo
which have the all javascript components for accessing data from a "REST" type service.
You then need to write a separate service which gets the XML or JSON required for your page.
My suggestion is to dump a script block to the output and set them in a variable there.
The array definition will have to actually be in the javascript code that gets output to the page.
e.g., you'll need an output of something like:
<script type="text/javascript">
var coords = new Array(2);
coords[0] = new Array(2);
coords[0][0] = 123.45;
coords[0][1] = 987.65;
coords[1] = new Array(2);
coords[1][0] = 234.56;
coords[1][1] = 876.54;
</script>
There are more efficient ways to create this array statically, but this is just an example.
A more efficient way (in terms of code) would be to build up a string that defined the literal array, then dump out a javascript definition. The output would be something like:
<script type="text/javascript">
var coords = [[123.45,987.65],[234.56,876.54]];
</script>
so in your loop within php, you'd build up a string which would ultimately contain var coords = [[123.45,987.65],[234.56,876.54]]. Outside your loop, you wrap it in the script blocks and output it to the page.