json_encode return undefined - php

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);

Related

Getting JSON value from php using jquery ajax

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

Global variable inside Ajax function

I'm learning the Ajax method with jQuery. I've a simple code here. It's to load data from a csv file by jQuery Ajax method, and put it into an array for further use. But it seems the array lost outside of the Ajax function even I do make the array global in the first place.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="js/jquery/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
var db=[];
$(document).ready(function(){
$.ajax({
url: 'loaddata.php',
success: function(data){
var arr = data.split('|');
for(var i=0; i<arr.length; i++){
var miniArr = arr[i].split(',');
db.push(miniArr);
}
printTest(); //work here
}
});
printTest(); //not working and collapse here
});
function printTest(){
document.getElementById('test').innerHTML += db;
}
</script>
</head>
<body>
<div id="test" />
</body>
</html> `
My php file should be fine,
<?php
$database = file('database');
foreach($database as $item){
if ($item===end($database))
echo $item;
else
echo $item.'|';
}
?>
Thanks in advance.
Your second printTest() is where the .ajax parameters go, so there's a syntax error there. The reason the first call works is because it's inside the success callback, and since AJAX is asynchronous this is called when the call has completed.
If you put the printTest() call after the AJAX call, it will be called immediately after the AJAX call has started, not waiting until it completes, due to async.
You can't call your second printTest() here.
And for the record, try to use JSON to retrieve your datas, it's way much easier.

How to pass php variables to jquery AJAX?

I have started learning jquery AJAX. I have run into a problem, and was wondering if you guys could help me. I am trying to pass a php variable back to jquery, but it displays as [object Object]. I will be posting my code below.
index.html:
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function() {
$("p").text($.get("return.php"));
});
});
</script>
</head>
<body>
<p>This is a test!</p>
<button>Click Here</button>
</body>
</html>
return.php:
<?php
$message = "Another test!";
echo $message;
?>
So what is it that I need to do to pass php variable $message into the paragraph using jquery ajax?
I know I could simply do if I changed index.html to index.php, but then if $message later changes, I have to reload the page. I am trying to learn how to make dynamic content without having to reload the page.
Thanks ahead of time for any help you provide! :-)
You'll have to wait until the data is returned before you can use it:
$(document).ready(function(){
$("button").click(function() {
$.get("return.php", function(data) {
$("p").text(data);
});
});
});
Add a callback to get.
$.get("return.php", function(data) {
$("p").text(data);
});
You can use callback function in .get function.
$(document).ready(function(){
$("button").click(function() {
$.get("return.php",function(data){
$("p").text(data);
});
});
});
Here you can pass the datatype as well in which form you want the response from server.
Suppose you want to return anyother datatype(i.e. json)from server, just use datatype with it like this :
$(document).ready(function(){
$("button").click(function() {
$.get("return.php",function(data){
$("p").text(data);
},"json");
});
});
For more detail,refer : http://api.jquery.com/jQuery.get/

use php inside JavaScript

I have an ajax function that post to an PHP file.
Now since I'm using WordPress I can use the get_url function so I don't need to hard code the entire URL.
The WordPress function is an PHP so I'm trying to use PHP inside the ajax post. But it wont do the trick.
Any ideas ? and is it possible ?
This is what I have.
$(document).ready(function(){
$('#submit').click(function(){
$.post('<?php echo get_template_directory_uri(); ?>/send.php', $("#mycontactform").serialize(), function(response) {
$('#success').html(response);
//$('#success').hide('slow');
});
return false;
});
});
I have also tried the php echo inside quotes like this.
$.post(' "<?php echo get_template_directory_uri(); ?>" /send.php' ....
ether way I get this path
http://mysite.com/%27%3C?php%20echo%20get_template_directory_uri();%20?%3E%27/send.php&email=&message=&name=&sent=1
Javascript to PHP = nope you cant embed javascript to php, only php can embed html and javascripts.
the better way to do it is to create a .php file and insert the javascript there...
Example: js.php
<?php
function doSubmit() {
?>
<script>
$('#submit').click(function(){
$.post('<?php echo get_template_directory_uri(); ?>/send.php', $("#mycontactform").serialize(), function(response) {
$('#success').html(response);
//$('#success').hide('slow');
});
return false;
});
</script>
<?php
}
?>
call the js.php using "include(js.php);" and call the functions inside another php
Inside your index.php
<?php
include('js.php');
?>
<html>
<head><script><?php doSubmit();?></script></head>
<body>
</body>
</html>

Pass PHP value to javascript using Ajax

I have a php code that provides the database values. I need those values in the javascript variable.
Javascript Code
<script src="http://code.jquery.com/jquery-1.8.0.js"></script>
<script type="text/javascript">
function text() {
var textVal=$("#busqueda_de_producto").val();
$.ajax(
{
type:"POST",
url:"index.php", //here goes your php script file where you want to pass value
data: textVal,
success:function(response)
{
// JAVSCRIPT VARIABLE = varable from PHP file.
}
});
return false;
}
</script>
PHP FILE CODE:
<?php
$q11 = "select * from sp_documentocompra_detalle where dcd_codigo".$_GET['codigo'];
$res11 = mysql_query($q11);
$row11 = mysql_fetch_array($res11);
?>
Your returning data is in the response parameter. You have to echo your data in PHP to get the results
Using JSON format is convenient
because of its key-value nature.
Use json_encode to convert PHP array to JSON.
echo the json_encoded variable
you will be able to receive that JSON response data through $.ajax
JavaScipt/HTML:
<script src="http://code.jquery.com/jquery-1.8.0.js"></script>
<script type="text/javascript">
function text()
{
var textVal=$("#busqueda_de_producto").val();
$.post('index.php', { codigo:textVal }, function(response) {
$('#output').html(response.FIELDNAME);
}, 'json');
return false;
}
</script>
<span id="output"></span>
PHP:
$q11 = "select * from sp_documentocompra_detalle where dcd_codigo='".mysql_escape_string($_POST['codigo'])."'";
$res11 = mysql_query($q11);
$row11 = mysql_fetch_array($res11);
echo json_encode($row11);
You aren't echoing anything in your PHP script.
Try altering your PHP to this:
<?php
$q11 = "select * from sp_documentocompra_detalle where dcd_codigo".$_GET['codigo'];
$res11 = mysql_query($q11);
$row11 = mysql_fetch_array($res11);
echo $row11; //This sends the array to the Ajax call. Make sure to only send what you want.
?>
Then in your Ajax call you can alert this by writing alert(response) in your success handler.
Tips
Send your data to the server as a URL serialised string : request=foo&bar=4. You can also try JSON if you fancy it.
Don't use mysql_* PHP functions as they are being deprecated. Try a search for PHP Data Objects (PDO).
i see lots of things that needs to be corrected
the data in your ajax do it this way data: {'codigo':textVal}, since you are using $_GET['codigo'], which leads to the second correction, you used type:"POST" so you must also access the $_POST variable and not the $_GET variable and lastly the target of your ajax does not display / return anything you either echo it or echo json_encode() it
The best solution is to use
echo json_encode("YOUR ARRAY/VALUE TO BE USED");
and then parse JSON in the javascript code as
obj = JSON.parse(response);

Categories