I have a php function to generate a list of numbers, and an ajax call to retrieve that array of numbers. I can alert the list and it works fine, however when I try to print it into an HTML table I get the error "Uncaught TypeError: Cannot use 'in' operator to search for 'length' in Infinity"
Any help would be appreciated.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<script>
$.ajax({
type: "POST",
url: "primeNumbers.php",
datatype: 'JSON',
success: function(data){
var d = $.each(JSON.parse(data));
var output;
$.each(d,function(i,e){
output += '<tr><td>'+e.data+'</tr></td>';
});
$('#table').append(output);
alert(data);
}
});
</script>
<h1>Heading</h1>
<table id="table">
<tr>
<td>Name</td>
</tr>
</table>
</body>
</html>
primeNumbers.php
<?php
function prima($n){
for($i=1;$i<=$n;$i++){
$counter = 0;
for($j=1;$j<=$i;$j++){
if($i % $j==0){
$counter++;
}
}
if($counter==2){
echo json_encode($i);
}
}
}
prima(100);
?>
The actual error means that $.each is probably getting the wrong data type. E.g. a string when in should be passed an object it can iterate over. In your case, both the javascript and the PHP code have some errors. Your PHP code just echoed the prime number. So you ajax function got back a concatenated string of numbers (the reason for your Uncaught TypeError). You have to push the numbers to an array, convert that to a json string and return that result, so you can echo it anywhere you need it.
Regarding only your ajax function. Loose $.each() in your variable declaration.
So:
var d = $.each(JSON.parse(data));
becomes:
var d = JSON.parse(data);
UPDATE added PHP fix
Here is the fixed/refactored PHP function.
function prima($n){
$res = []; // Initiate result array
for($i=1;$i<=$n;$i++){
$counter = 0;
for($j=1;$j<=$i;$j++){
if($i % $j==0){
$counter++;
}
}
if($counter==2){
$res[] = $i; // store value to array
}
}
return json_encode($res); // return converted json object
}
header('Content-Type: application/json'); // tell browser what to expect
echo prima(100); // echo the json string returned from function
Related
Hi friends can anyone me for this plz. im new to this chapter..i am trying to get JSON format value from PHP but while im running i got this output "SyntaxError: JSON.parse: unexpected characte".. i think i had done mistake in php conversion ...plz help me friends
my .html file
<html>
<head>
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<title>Display Page</title>
</head>
<body>
<button type='button' id='getdata'>GetData.</button>
<button type='button' id='get'>sample</button>
<script type='text/javascript'>
$('#get').click(function() {
alert("laksjdflk");
});
$(document).ready(function() {
$('#getdata').click(function() {
$.ajax({
url:'neww.php' ,
dataType:'json' ,
success:function(output_string) {
alert(output_string);
},
error:function(xhr,ajaxOptions,thrownError){
alert(xhr.statusText);
alert(thrownError);
}
});
});
});
</script>
</body>
</html>
generatephp.php
<?php
mysql_connect("localhost","root","");
mysql_select_db("androidlogin");
$sql=mysql_query("SELECT* FROM trysave");
$temp="";
$i=0;
while($row=mysql_fetch_assoc($sql)){
$temp=$row['stringss'];
$temp.=$row['integerr'];
$array[i]=$temp;
i++;
}
echo json_encode($array);// this will print the output in json
?>
This may because of Undefined array variable notice you have to define array in case no records found
Also you missed a $ before variable i which gives error(treated as CONSTANT, and which is undefined in your code), i should be $i like,
$array=array();// define here to prevent from "Notice"
while($row=mysql_fetch_assoc($sql))
{
$temp=$row['stringss'];
$temp.=$row['integerr'];
$array[$i]=$temp;// use $ before i
$i++;// use $ before i
}
echo json_encode($array);// this will print the output in json
One more thing you have mentioned PHP file name as generatephp.php and you are using url:'neww.php' , in $.ajax(), you have to check your code once.
Obvious problems (cough MySQL_*) aside, your PHP file should specify in the response headers that the output will be of type JSON. The output defaults to text/html and Javascript cannot parse it as a valid JSON object.
You can do it like this
<?php
header('Content-type: application/json');
// Rest of the code remains intact
i wold use something different ...
php:
<?php
mysql_connect("localhost","root","");
$sql=mysql_query("SELECT stringss, integerr FROM androidlogin.trysave");
$temp=array();
$i=0;
while($row=mysql_fetch_assoc($sql)){
$temp[] = $row;
}
echo json_encode($temp);// this will print the output in json
?>
//you do not need the $i variable since you will get in java str.length = that $i
<script type='text/javascript'>
$('#get').click(function() {
alert("laksjdflk");
});
$(document).ready(function() {
$('#getdata').click(
function() {
jQuery.getJSON( "neww.php") //no get vars
.done(function(a) {
//console.clear();
console.log(a);
show_data(a);
})
.fail(function(a) {
console.log( "error" );
});
});
});
function show_data(a){
for(var i=0; i<a.length; i++)
var stringss = a[i].stringss;
var integerr = a[i].integerr;
var nuber_temp = i;
//do stuff with them ...
}
</script>
if problem persists ... try http://php.net/manual/ro/function.urlencode.php
I have a JQuery that creates an Ajax call to a PHP script. My PHP script echos 2 strings: check_1 and check_2. The alert() is displaying both the strings in the output. How to get only one string in the output?
PHP:
<?php
echo "check_1";
echo "check_2";
?>
JQuery:
$.get("check_ajax.php", function(data) {
alert(data);
});
send the server response as json ... and get it...
try this
jquery
$.get("check_ajax.php", function(data) {
alert(data.check_1); //alert the first object "check_1"
alert(data.check_2); //alert the second object "check_2"
},'JSON');
php
<?php
echo json_encode(array("check_1"=>"check_1","check_2"=>"check_2"));
?>
there is couple of ways to do this. one way is string manipulation and removing the text after the new line char of the first string. The other method is actually send your data from php to javascript using json. So in your php file you would create a data structure like an array.
<?php
$string = array("check_1", "check_2");
echo json_encode($string);
?>
in the javascript side then you can retrieve the first element from that json array.
$.get("check_ajax.php", function(data) {
alert(data[0]);
});
You can use like this : -
<?php
$html = "check_1";
$html1 = "check_2";
echo $html.'~~~'.$html1;
?>
JQuery:
$.get("check_ajax.php", function(data) {
var res = data.split('~~~');
alert(res[0]);
});
We have the same problem before, but what I do as an alternative solution was to have a conditional statement to separate multiple values returned by php
if(your condition here) {
echo "check_ 1";
} else {
echo "check_ 1";
}
Hope it helps :)
PHP:
<?php
$text = array("check_1", "check_2");
die(json_encode($text));
?>
jQuery:
$.get("check_ajax.php", function(data) {
var response = JSON.parse(data);
alert(response[0]); // for "check_1"
alert(response[1]); // for "check_2"
});
We have designed a Progress bar, using Jquery Ui. we need a program that can deliver data in numeric value.
That code is not working
PHP CODE
<?php
ob_start();
$array = array(10,20,30,40,50,60,70,80,90,100);
foreach($array as $a ){
echo $a;
sleep(1);
ob_end_clean();
}
echo 100 ;
?>
PHP code for echo a single item, it clears the existing data, so that our Ajax program can get the actual numeric data.
Thanks
You need to send a request to your php script with a parameter if you don't have an actual update:
$(function() {
$("#progressbar").progressbar({ value: 0 });
setTimeout(function(){ updateProgress(0); }, 500);
});
function updateProgress(data) {
$.get(url+'?progress='+data, function(data) {
// data contains whatever that page returns
if (data < 100) {
$("#progressbar").progressbar({value: parseInt(data)});
$("#progresstext").html("<p> Loading...<p>");
setTimeout(function(){ updateProgress(data); }, 500);
} else {
$("#progressbar").progressbar({value: 100});
}
});
}
and your PHP script:
<?php
echo (int)$_GET['progress']+10;
?>
I have a php script that watches for the newest json file in a directory (below). Then in a javascript I parse and display the data from that file. The javascript reloads the data every x minutes.
I won't have the name of the file just that it will contain json data and to use the newest one.
The PHP script stores the most recent file stored in array fileList[0]. I want to pass that to the javascript without a full page refresh so I checked this stackoverflow post and found that an ajax call can be made to a php script but the example updates an element on the page.
Is there a way to update a javascript variable? I thought of maybe placing the filename as a hidden element and the grabbing before I refresh the data, but that seemed crude.
<?php
date_default_timezone_set('America/New_York');
$files = glob('json/*.*', GLOB_BRACE);
usort($files, 'filemtime_compare');
function filemtime_compare($a, $b)
{
return filemtime($b) - filemtime($a); // Order newest to oldest
}
$i = 0;
$show = 1; // Number of new files to show.
$fileList = array();
foreach($files as $file)
{
if($i == $show) break; else ++$i;
array_push($fileList, $file);
}
//echo $fileList[0] // DEBUG: Make sure I have the right file.
?>
AJAX:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
// This will send a request to a PHP page
$.ajax({
var jsonURL = "";
url: "phpDir.php",
dataType: "html",
success: function(data){
// Place the returned data into your content
}
jsonURL = $fileList[0];
});
</script>
</head>
<body>
To answer your question "Is there a way to update a javascript variable?"
You would do this:
var jsonURL = '';
function loadXMLDoc() {
// This will send a request to a PHP page
$.ajax({
url: "phpDir.php",
dataType: "JSON",
success: function(data){
jsonURL = data.url;
}
});
}
For ease of communication I have set the dataType to JSON. So PHP output would need to be json_encoded()ed:
<?php
$output = array('url' => $fileList[0]); // or whatever URL you want to return
echo json_encode($output);
?>
My script returns undefined value from my json_encode php
index.php
<?php
$returnThis['user'] = "Robin098";
$returnThis['id'] = "08465";
echo json_encode($returnThis);
?>
sample.html
<head>
<script>
function clickHere(){
$.get("index.php", function(data) {
alert(data.user);
});
}
</script>
</head>
<body>
<input type="button" onclick = "clickHere();" value="ClickHere!"/>
</body>
How can I fix this?
Use the jQuery.getJSON method instead of .get, if you want your JSON to be parsed. Also, make sure that the jQuery library is correctly loaded.
function clickHere(){
$.getJSON("index.php", function(data) {
alert(data.user);
});
}
Currently, you're using $.get(url, function(data){...}). In this context, data is a string containing the response from the server:
{"user":"Robin098","id":"80465"}
Using alert(data) inside the function will show this string.
It looks like you're setting up $returnThis, but then returning $aReturn. Don't you want:
$returnThis['user'] = "Robin098";
$returnThis['id'] = "08465";
echo json_encode($returnThis);