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
Related
I'am trying to get php response data with ajax. I want to check if there is a specific string in testing.txt from my input and if the string is found, php should echo "1" but no matter what I try AJAX always says the output isn't 1
This is my code:
<?php
if (isset($_POST['table'])) {
$file = file("testing.txt");
if (in_array($_POST['table'], $file)) {
echo "1";
} else {
echo "0";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<input type="text" name="text" id="text">
<button id="button">NEXT</button>
<script type="text/javascript" src="jquery.js"></script>
<script>
var text;
document.getElementById('button').onclick = function () {
text = document.getElementById('text').value;
post(text);
};
function post(vally) {
var table = vally;
$.post('test.php', {table:table}, function(data) {
})
.done(function (data) {
if (data == 1) {
console.log("the output is 1")
} else {
console.log("the output isn't 1")
}
});
console.log('posted');
}
</script>
</body>
</html>
testing.txt:
abc
def
ghi
The response I get if i console.log(data):
0<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<input type="text" name="text" id="text">
<button id="button">NEXT</button>
<script type="text/javascript" src="jquery.js"></script>
<script>
var text;
document.getElementById('button').onclick = function () {
text = document.getElementById('text').value;
post(text);
};
function post(vally) {
var table = vally;
$.post('test.php', {table:table}, function(data) {
})
.done(function (data) {
if (data == 1) {
console.log("the output is 1")
} else {
console.log(data)
}
});
console.log('posted');
}
</script>
</body>
</html>
I have tried using .done(), .fail() and .always() but I always get the output isn't 1(I am using JQuery 3.2.1).
Can someone tell me what I'm doing wrong?
EDIT: I would like to point out something I haven't before. I'm looking for a one page solution. I know that it can easily be done with two pages but I was wondering if there was a one page solution.
The problem is the Ajax request is sent to the home page, so it receives everything after '0' or '1'. Split that.
Move your PHP code in anoter file, say 'ajax.php'
And change your $.post() settings to call ajax.php instead of test.php.
So the Ajax request will only receive the '0' or '1' string.
Notice how your AJAX response is the entire page, prepended with the single digit that you're looking for. You don't need to send the whole page to the browser twice. Move your PHP logic into its own file with nothing but that logic. Let's call it checkTable.php for the sake of demonstration:
<?php
if (isset($_POST['table'])) {
$file = file("testing.txt");
if (in_array($_POST['table'], $file)) {
echo "1";
} else {
echo "0";
}
}
?>
Then make your AJAX call to that page:
$.post('checkTable.php', {table:table})
Then the response will contain only what that PHP code returns, not the whole page. (It's worth noting that this PHP code will return an empty response if table isn't in the POST data.)
Aside from that, your code is currently returning a 0 for whatever input you're providing, so it's still going to be true that "the output isn't 1". For that you'll need to double-check your input and data to confirm your assumptions.
Because I wanted everything in one file I decided to use data.slice(0, 1); to trim off everything except the first character which will be a 0 or 1, and thanks to David for reminding me that there may be a whitespace issue, which there was. Now I added text.trim() to remove all of the whitespace from the input and array_filter(array_map('trim', $file)); to remove all of the whitespace from the strings written in the file.
This is the finished code:
<?php
if (isset($_POST['table'])) {
$file = file("testing.txt");
$file = array_filter(array_map('trim', $file));
if (in_array($_POST['table'], $file) == true) {
echo "1";
} else {
echo "0";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<input type="text" name="text" id="text">
<button id="button">NEXT</button>
<script type="text/javascript" src="jquery.js"></script>
<script>
var text;
document.getElementById('button').onclick = function () {
text = document.getElementById('text').value;
post(text.trim());
};
function post(vally) {
var table = vally;
console.log(vally);
$.post('test.php', {table:table}, function(data) {
var cut = data.slice(0, 1);
if (cut == 1) {
console.log("the output is 1")
} else {
console.log(cut);
}
});
console.log('posted');
}
</script>
</body>
</html>
I would like to thank everyone who helped me resolve my issue, which has been bugging me for the last 2 days.
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
I'm making an aplication with phonegap and I'm stuck trying to send JSON data from the PHP on the server to JavaScript on the device. I want to do something like:
var JSON = '{ "Table" : ' + "http://www.hel.net/LoadDB.php=?table=exhibitions" + '}';
the php works fine and returns somethig like:
"[{"id":"1","name":"Art for everyone","image":null,"name2":"June 29, 2013: 11:00am.","description":"With reservation\r\nFree entrance","description2":null}]"
I want that result in a javascript variable to work later with:
var obj = eval ("(" + JSON + ")");
document.getElementById("rName").innerHTML=obj.Table[1].name;
document.getElementById("lname").innerHTML=obj.Table[1].name2;
What I want to do is something like:
var JSON = '{ "Table" : ' + "http://www.hel.net/LoadDB.php=?table=exhibitions" + '}';
var obj = eval ("(" + JSON + ")");
document.getElementById("rName").innerHTML=obj.Table[1].name;
document.getElementById("lname").innerHTML=obj.Table[1].name2;
How can I make the first line work? is it possible to make the first line work?
PS. I do not have much experience with JSON arrays.
Ok I tried ajax and works, I used:
console.log("before");
var jqxhr = $.ajax( "http://www.hel.com/LoadDB.php?table=exhibitions" )
.done(function(data) { console.log(data); })
.fail(function() { console.log("error"); })
.always(function() { console.log("complete"); });
console.log("after");
more info in:
api.jquery.com
I think all you need is var obj = <?php echo $myjsonencodedvar; ?>
or
var obj = <?php echo json_encode($myarray_or_object); ?>
Since I said "I think..." I decided to test it out. I found the following dump() function here on SO.
$arr=array(1,'biscuit'=>'gravy',3,4,5);
$json=json_encode($arr);
?>
<script>
j=<?php echo $json; ?>;
document.write(dump(j));
function dump(obj) {
var out = '';
for (var i in obj) {
out += i + ": " + obj[i] + "\n";
}
return out;
}
</script>
output:
0: 1 biscuit: gravy 1: 3 2: 4 3: 5
Try this:
PHP: (json.php)
<?php
header("Content-Type: text/json");
//the data format your question mentioned
$data = array("Table"=>array(array("id"=>"1","name"=>"Art for everyone","image"=>null,"name2"=>"June 29, 2013","description"=>"With reservation\r\nFree entrance","description2"=>null)));
echo json_encode($data);
?>
Front-end:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$.get("json.php",function(json){
alert(json.Table[0].name);
});
</script>
</body>
</html>
Hope this is helpful for you.
using JSONP (no callbacks), and on the client side use $.getJSON() it will parse it from json string to js object.
I want to execute any JavaScript function that is part of a JSON using eval() but obviously I can't do it right, and can't figure out where exactly is the mistake/s. I'm using two very simple files, just for trying - the first is index.php and is at it is:
<!DOCTYPE html>
<html>
<head>
<title>Simple form sending and receiving a JSON object to/from PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var data =
{
"sales": [
{ "firstname" : "John", "lastname" : "Brown" },
{ "firstname" : "Marc", "lastname" : "Johnson" }
] // end of sales array
}
var dataString = JSON.stringify(data);
$.post('simpleformSubmi.php', { data: dataString}, showResult, "text");
});
function showResult(res)
{
var data = eval('(' + res + ')');
$("#fullresponse").html("Full response: " +data);
}
</script>
<div id="fullresponse"></div>
</head>
<body>
and the second one is simpleformSubmi.php :
<?php
$logFile = 'logFile';
$res = json_decode(stripslashes($_POST['data']), true);
$arr = "function(){alert('Hi')}";
echo json_encode($res);
echo json_encode($arr);
So what I expected was after executing echo json_encode($arr); to get and alert but instead I get a mistake, and in Firebug the console shows error "missing ) in parenthetica". So the question is - how to send a valid JS function this way and to execute it properly?
Thanks
Leron
Why you are json_encodeing $arr. You may just return it as a string echo $arr and eval('(' + res + ')()') in the JavaScript (notice the () in the JS to execute the function). You may need to remove echo json_encode($res) just to get this to work for now.
You can't. A JSON object cannot contain functions, only values.
You will have to setup some sort of webservice that actually prints JavaScript, which you in turn can call through a <script src="/your/endpoint"></script> declaration client side.
You can send the js function as data.
$data = array("something"=>"12345");
$js = "alert('hi!')";
$data["autoexec"] = $js;
echo json_encode($data);
Then on the clientside do something like eval(data["autoexec"]);
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);