I have been struggling with this for a while. There are tons of topics on the subject but none is actually working for me, but being a newbie might be the cause so please elaborate.
I simplified the code and it won't work, I posted the code below
I am queering the Database, and saving the values to an array in a function
I then need to pass that array to a jquery in the same function. I used json_encode but i am getting this error:
Uncaught SyntaxError: Unexpected token <
Here is the code:
function Test()
{
$query1 = $wpdb->get_results("SELECT(element_value) FROM wp_piic_formmaker_submits WHERE form_id = 13 AND element_label = 1 AND user_id_wd = 1 ORDER BY date asc", OBJECT);
if($query1)
{
foreach($query1 as $q)
{
$PHPArray[$i] = $q->element_value ;
$i = $i + 1;
}
}
$UserInput = "<script type='text/javascript'>
jQuery('#wdform_1_element13').on('change',function()
{
var test = <?php echo json_encode($PHPArray); ?>;
jQuery.each(test , function (i, elem)
{
alert('here');
});
});
</script>";
return $UserInput ;
}
Change it to this:
$UserInput = "<script type='text/javascript'>
jQuery('#wdform_1_element13').on('change',function()
{
var test = ".json_encode($PHPArray)."; //Notice the change here
jQuery.each(test , function (i, elem)
{
alert('here');
});
});
</script>";
return $UserInput ;
}
You have to escape the string correctly:
function Test()
{
$query1 = $wpdb->get_results("SELECT(element_value) FROM wp_piic_formmaker_submits WHERE form_id = 13 AND element_label = 1 AND user_id_wd = 1 ORDER BY date asc", OBJECT);
if($query1)
{
foreach($query1 as $q)
{
$PHPArray[$i] = $q->element_value ;
$i = $i + 1;
}
}
$UserInput = "<script type='text/javascript'>
jQuery('#wdform_1_element13').on('change',function()
{
var test = " . json_encode($PHPArray) . ";
jQuery.each(test , function (i, elem)
{
alert('here');
});
});
</script>";
return $UserInput ;
}
If you put PHP inside JavaScript the PHP part is only text, do this:
function Test()
{
$query1 = $wpdb->get_results("SELECT(element_value) FROM wp_piic_formmaker_submits WHERE form_id = 13 AND element_label = 1 AND user_id_wd = 1 ORDER BY date asc", OBJECT);
if($query1)
{
foreach($query1 as $q)
{
$PHPArray[$i] = $q->element_value ;
$i = $i + 1;
}
}
$UserInput = "<script type='text/javascript'>
jQuery('#wdform_1_element13').on('change',function()
{
var test = " . json_encode($PHPArray) . ";
jQuery.each(test , function (i, elem)
{
alert('here');
});
});
</script>";
return $UserInput ;
}
At least from what is shown, neither $i nor $PHPArray are initialized. PHP can be messy about these things, but you cannot directly refer to indexes of non-existent arrays, or variables that have not been declared.
I'll guess the token error was from your browser trying to deal with the text output of a PHP error being flushed, along the lines of 'undefiend' or 'undefined index.'
Also, the real (or at least convenient) purpose of the foreach construct is not fooling with indexes. Try the following substitute for your current loop:
$PHPArray = array(); // $PHPArray = [];
if($query1){
foreach($query1 as $q){
$PHPArray[] = $q->element_value;
}
}
Beyond that, "wpdb" suggests calls related to specific frameworks, but in case this is a mysqli_stmt call, i believe the call is singular: get_result.
I'm trying to make a application using phonegap. I am trying to make a select using php return the result to ajax function and print the result...but I don't know if I am doing right and what I need to put in my html code to show the result.
AJAX CODE:
$(document).ready(function() {
$.ajax({
url : 'http://ip/again/www/index.php',
dataType : "json",
success : function(data){
var html = "";
for($i=0; $i < data.length; $i++){
html += "<strong>Nome:</strong> "+data[$i].nome +" "+
data[$i].sobreNome;
html += " <strong>Cidade:</strong> "+data[$i].cidade;
html += "<br />";
}
$('body').html(html);
}
});
});
</script>
PHP CODE:
<?php
$hostname = 'localhost';
$username = 'root';
$password = 'pass';
$database = 'mydb';
try {
$pdo = new PDO("mysql:host=$hostname;dbname=$database", $username,
$password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
//echo 'Conexao efetuada com sucesso!';
}
catch(PDOException $e)
{
echo $e->getMessage();
}
$sql = 'SELECT * FROM incidente ORDER BY codigo' ;
try {
$recebeConexao = $pdo->prepare($sql);
$recebeConexao->execute();
$result = $recebeConexao->fetchAll();
if ( count($result) ) {
foreach($result as $row) {
$incid=$row;
echo (json_encode($incid));
}
} else {
$incid=0;
}
} catch (PDOException $ex) {
echo "Erro no Banco";
}
?>
You're writing the for loop incorrectly. You must declare your variable with the var keyword like so:
for(var $i = 0; $i < data.length; $i++) {
// ...
}
Since your script does not return an array, the length property will not be available.
When you're dealing with an object in Javascript, you will want to use the for...in syntax (making sure to validate that the property belongs to the object you're iterating over).
However, the code you provided will not return an object or an array, because the JSON is malformed.
The correct way for an API to return multiple, unordered Javascript objects would be to wrap them in an array, like so:
if(count($result)) {
$list = array();
foreach($result as $row) {
$list[] = $row;
}
echo json_encode($list);
}
$.ajax({
// ...
success: function (data) {
// Loop over each object, since your script should ideally return an array
for (var $i = 0; $i < data.length; $i++) {
var object = data[$i];
html += '<strong>Nome:</strong> ' + object.nome + ' ' + object.sobreNome;
// etc...
}
}
});
I've managed to get a value from a sql table in my AS3 code, but I don't understand why I can't get a second value.
In my php file I've got :
// create SQL
$sql = "SELECT * FROM dt_base where username = '$username'";
// execute SQL query and get result
$sql_result = mysql_query($sql, $connection) or die ("Couldn't execute query.");
// get number of rows in $result.
$num = mysql_numrows($sql_result);
$phpConfirm = "";
$phpConfirmSecond = "";
$counter = 0;
while ($row = mysql_fetch_array($sql_result)) {
$up= $row["up"];
$down= $row["down"];
if ($counter == 0) {
$phpConfirm .= $up;
$phpConfirmSecond .= $down;
} else {
// Use a item limiter "|" to seperate the records
$phpConfirm .= "|" . $up;
$phpConfirmSecond .= "|" . $down;
}
$counter++;
}
?>
And in my AS3 code :
function loadComplete(evt:Event):void {
//Display the value with variable name "totalItem"
total_txt.text = evt.target.data.totalItem
//Get the value (string) with variable name "phpConfirm"
var myResult:String = evt.target.data.phpConfirm;
trace(evt.target.data.phpConfirm);
var myResultSecond:String = evt.target.data.phpConfirmSecond;
trace(evt.target.data.phpConfirmSecond);
//Split the string into an Array
var myArray:Array = myResult.split("|");
var myArraySecond:Array = myResultSecond.split("|");
var finalString = "";
var finalStringSecond = "";
var i:int;
for (i = 0; i < myArray.length; i++) {
finalString = finalString + myArray[i] + "<br>";
finalStringSecond = finalStringSecond + myArraySecond[i] + "<br>";
}
output_txt.htmlText = finalString;
output_txtSecond.htmlText = finalStringSecond;
}
trace(evt.target.data.phpConfirm) results with the value of "up", so it's working.
But trace(evt.target.data.phpConfirmSecond) results with "undefined" instead of the value of "down".
Any idea why ?
EDIT
I've add that to my php file.
echo "phpConfirm=" . $phpConfirm . "&phpConfirmSecond=" . $phpConfirmSecond;
and I've change the line $username = "John"; in order to test it in the web browser.
The result is :
phpConfirm=6h20&phpConfirmSecond=14h32
So phpConfirmSecond has a value.
But my AS3 code produce an error when I had the PhpConfirmSecond in my php file.
Here's the error :
TypeError: Error #2007: Le paramètre text ne doit pas être nul.
at flash.text::TextField/set text()
at as3_php_mysql_01_fla::MainTimeline/loadComplete()
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at flash.net::URLLoader/onComplete()
If I erase every trace of PhpConfirmSecond of my php file, my AS3 code works and find the value PhpConfirm.
Found the problem. It was the line
//Display the value with variable name "totalItem"
total_txt.text = evt.target.data.totalItem
that was causing all the problem...
Thank you for your help.
I'm trying to do a realllly simple post of a javascript variable to a php file.
Jquery bit in keyinput.php:
<script type="text/javascript">
var imgArray = [<?php echo implode(',', getImages($cat, $site)) ?>];
$(document).ready(function() {
var img = document.getElementById("showimg");
img.src = imgArray[<?php echo $imgid ?>];
var imgIndex = <?php echo $imgid ?>;
$(document).keydown(function (e) {
var key = e.which;
int rightarrow = 39;
int leftarrow = 37;
int random = 82;
if (key != rightarrow && key != leftarrow && key != random) {
return;
}
else {
//next image: right arrow
if (key == rightarrow)
{
imgIndex++;
if (imgIndex > imgArray.length-1)
{
imgIndex = 0;
}
img.src = imgArray[imgIndex];
}
//last image: left arrow
if (key == leftarrow)
{
if (imgIndex == 0)
{
imgIndex = imgArray.length;
}
img.src = imgArray[--imgIndex];
}
//random: r
if (key == random)
{
imgIndex = Math.floor((Math.random()*(imgArray.length-1))+1);
img.src = imgArray[imgIndex];
}
}
$.post('./templates/viewcomic.php', {variable: imgIndex});
});
});
</script>
<?php
function getImages($catParam, $siteParam) {
include './scripts/dbconnect.php';
if ($siteParam == 'artwork') {
$table = "artwork";
}
else {
$table = "comics";
}
if ($catParam != null) {
$catResult = $mysqli->query("SELECT id, title, path, thumb, catidFK FROM $table WHERE catidFK = $catParam");
}
else {
$catResult = $mysqli->query("SELECT id, title, path, thumb, catidFK FROM $table");
}
$img = array();
while($row = $catResult->fetch_assoc())
{
$img[] = "'" . $row['path'] . "'";
}
return $img;
}
?>
PHP bit in viewcomic.php:
include './scripts/keyinput.php';
$JSIndex = $_POST['variable'];
echo "Index = " . $JSIndex;
//$JSIndex should be equal to the javascript variable imgIndex... but it outputs nothing
Any thoughts would be extremely helpful! I'm trying to get my comics website to go live.
Thanks!
Your logic is wrong: at the moment you define your key variable, e is undefined. Then you attach your event handler inside an if statement that will always evaluate to false so that will never work.
The assignment to key should be inside your event handler and the conditional needs to go, you already have that inside your event handler.
Edit: you should also only do your ajax call if one of your action keys is pressed (put it inside the event handler) and do something with the result.
Edit 2: Checkout the manual on $.post, you should add a callback function to process the return value of your php script.
For example:
$.post(
'./templates/viewcomic.php',
{ variable: imgIndex },
function(data) { /* data contains what you have echoed out in your php script */
alert(data);
}
);
I create a huge JSON-Object and save it in my database. But when I load the "string" and echo it in PHP, I can't access the JSON Object in JQuery. Do I have to consider something if I want to save my JSON Object in a MySQL Database (when I just create the Array and then echo it with "echo json_encode($arr);" it works fine, but I need to save the Object for caching).
{"247":{"0":"This is a
question","1":"","2":"247","3":"0","answers":[["Answer1","960","1"],["Answer
2","962","0"],["Answer
3","961","0"],["Answer
4","963","0"]]},{"248":{"0":"This is a
question","1":"","2":"247","3":"0","answers":[["Answer1","960","1"],["Answer
2","962","0"],["Answer
3","961","0"],["Answer
4","963","0"]]}}
just an excerpt
If I just echo this JSON-Object, everything works fine, but if I load the same string from the database and echo it, it doesn't work.
Update 1: forget to tell that I'm using a TEXT-Field with UTF8_general_ci collation
Update 2: Maybe a little bit more code:
function start() {
$(".start").click(function () {
$.post("load_script.php", { }, function(data){
alert(data[247][0]);
}, "json");
return false;
});
}
this loads the script and should alert "This is a question"
<?php
require_once('connect.php');
$ergebnis = mysql_query("SELECT text FROM cache_table ORDER BY RAND() LIMIT 1");
while($row = mysql_fetch_object($ergebnis)) {
$output = $row->text;
}
echo $output;
?>
this is the script, where I load the database entry with the JSON-Object.
Update 3:
I think I solved the problem. Some break sneaked into my JSON-Object so I do this, before the output:
$output = str_replace("\n", "", $output);
$output = str_replace("\r", "", $output);
$output = str_replace("\r\n", "", $output);
I'd suggest looking at what your javascript is seeing. Instead of asking jQuery to interpret the json for you, have a look at the raw data:
function start() {
$(".start").click(function () {
$.post("load_script.php", { }, function(data){
alert(data);
}, "text");
return false;
});
}
For example, if part of the string gets oddly encoded because of the UTF-8, this might cause it to appear.
Once you've done that, if you still can't spot the problem, try this code:
var data1, data2;
function start() {
$(".start").click(function () {
$.post("load_script.php", {src: "db" }, function(data){
data1 = data;
}, "text");
$.post("load_script.php", {src: "echo" }, function(data){
data2 = data;
}, "text");
if (data1 == data2) {
alert("data1 == data2");
}
else {
var len = data1.length < data2.length ? data1.length : data2.length;
for(i=0; i<len; ++i) {
if (data1.charAt(i) != data2.charAt(i)) {
alert("data1 first differs from data2 at character index " + i);
break;
}
}
}
return false;
});
}
And then change the PHP code to either return the data from the database or simply echo it, depending on the post parameters:
<?php
if ($_POST['src'] == 'db')) {
require_once('connect.php');
$ergebnis = mysql_query("SELECT text FROM cache_table ORDER BY RAND() LIMIT 1");
while($row = mysql_fetch_object($ergebnis)) {
$output = $row->text;
}
}
else {
$output = '{"247":{"0":"This is a question","1":"","2":"247","3":"0","answers":[["Answer1","960","1"],["Answer 2","962","0"],["Answer 3","961","0"],["Answer 4","963","0"]]},{"248":{"0":"This is a question","1":"","2":"247","3":"0","answers":[["Answer1","960","1"],["Answer 2","962","0"],["Answer 3","961","0"],["Answer 4","963","0"]]}}';
}
echo $output;
?>
Hope that helps!
I got this to work in a slightly different manner. I've tried to illustrate how this was done.
In Plain English:
use urldecode()
In Commented Code Fragments
$json = $this->getContent($url); // CURL function to get JSON from service
$result = json_decode($json, true); // $result is now an associative array
...
$insert = "INSERT INTO mytable (url, data) ";
$insert .= "VALUES('" . $url . "', '" . urlencode(json_encode($result)) . "') ";
$insert .= "ON DUPLICATE KEY UPDATE url=url";
...
/*
** Figure out when you want to check cache, and then it goes something like this
*/
$sqlSelect = "SELECT * FROM mytable WHERE url='" . $url . "' LIMIT 0,1";
$result = mysql_query($sqlSelect) or die(mysql_error());
$num = mysql_numrows($result);
if ($num>0) {
$row = mysql_fetch_assoc($result);
$cache = json_decode(urldecode($row['data']), true);
}
Hope this is helpful
Maybe you use varchar field and your string just doesn't fit in 255 chars?