I want to fetch data from mysql, and echo it by a json_encode. then my JQUERY will catch JSON via $.getJSON and append the result into my <ul>.
im trying to figure out why the data being captured by JQUERY is not printing on my index.php
this is my index.php
<html>
<?php
include_once('connect.php');
$sql = "SELECT * FROM data";
$query = mysql_query($sql);
$result = array();
while($row = mysql_fetch_array($query))
array_push($result,
array(
'name' => $row[1],
'msg' => $row[2]));
echo json_encode(array("key" => $result));
?>
<body>
<ul>
//insert fetch data here
</ul>
<script type="text/javascript" src="./js/jquery.js"></script>
<script type="text/javascript" src="./js/custom.js"></script>
</body>
</html>
and here is my JQUERY
function my_function() {
$.getJSON("index.php", function(data) {
$.each(data.key, function(){
$("ul").append("<li>Name: "+this['name']+"</li>"
"<li>message: "+this['msg']+ "</li>");
});
});
}
You don't need to fetch your data via JSON as you're echo-ing the JSON on the same page.
you could do something like this:
<ul id="jsonData" data-json-data="<?php echo json_encode($result;)?>"
And in your js file:
var myData = $('#jsonData').data('json-data');
first: check your index.php output by itself to see if it's displaying valid json. ¿Are there invalid UTF8 characters? In that case json_encode's output is null.
second: I'd use plain ajax method hinting json as dataType:
jQuery.ajax({
url: 'index.php',
dataType: 'json'
}).done(function(data) {
for (i=1;i<data.length;i++) {
datarow=data[i];
$("ul").append("<li>Name: "+datarow.name+"</li>");
$("ul").append("<li>message: "+datarow.msg+ "</li>");
}
});
third: don't use the same script to generate the json and to display it, it makes no sense to decouple view from app if you do it all in the front. In that case you might as well use plain php to generate it all, as the previous answer told. (#Abdoul Sy)
Related
When call php from jquery via ajax ,have any response .I changed the dataTypeand put jsoninstead html.I´m thinking the issue is that,for the ajax call never trigger the php code,it seems $_POST['retriveForm'] never carries a value.
PHP:
if(isset($_POST["retriveForm"])) {
$data_json =array();
$id = $_POST['retriveForm'];
$sql = "SELECT * FROM mytable WHERE Id = $id";
while ($row = mysqli_fetch_array($db->consulta($sql)) {
$data_json = array('item1' => $row['item1'],'item2' => $row['item2']) ;
}
$data_json['item_array'] = call_a_function_return_array();//this works
echo json_encode($data_json);
}
and jQuery :
$(document.body).on('click', '.edit', function() {
var id = $(this).data('id');
$.ajax({
type: "POST",
url: "is_the_same_page.php",
data: {
retriveForm: id
},
dataType: "json",
success: function(response) {
$('#myForm').find('input').eq(1).val(response.item1);
}
});
});
Code is all in the same page if that may be important.
Since the AJAX code is in the same script, make sure you don't output any of the normal HTML in this case. Your PHP code should be at the very beginning of the script, before any HTML is output. And you should exit the script after echoing the JSON. Otherwise your JSON will be mixed together with HTML, and jQuery won't be able to parse the response.
Also, you're not correctly adding to $data_json in your loop. You're overwriting the variable each time instead of pushing onto it.
<?php
// code here to set up database connection
if(isset($_POST["retriveForm"])) {
$data_json =array();
$id = $_POST['retriveForm'];
$sql = "SELECT * FROM mytable WHERE Id = $id";
while ($row = mysqli_fetch_array($db->consulta($sql)) {
$data_json[] = array('item1' => $row['item1'],'item2' => $row['item2']) ;
}
$data_json['item_array'] = call_a_function_return_array();//this works
echo json_encode($data_json);
exit();
}
?>
<html>
<head>
...
Then in the success function, you'll need to index the elements of response, since it's an array, not a single object.
I am trying to make a little application which lists some pics and text from database on index page, and when I click on specific title it takes me to details page where I can find that picture with title and text.
I have made query which lists everything on index page but I can't figure out how exactly should I target the details page, because when I click on the post ID it takes me to details page but it pulls all the other posts with it.
Could someone help me?
My index page:
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery.ajax({
url:"",
type : "POST",
dataType : "json",
data : "param=no",
success : function (html) {
var DOM = jQuery('#DOM');
console.log(html);
jQuery.each(html, function(key, value){
console.log(value);
DOM.append("<li><h3><a href='details.php?post_id="+value.post_id+"'</h3> "+value.post_title+"</a></h3>
<p>"+value.post_author+"</p>
<img src='admin/news_images/"+value.post_image+"' width='100' height='100'</li>");
});
},
error : function (e){
alert(e);
}
});
});
</script>
This is my fetchdata.php:
<?php
header ('Access-Control-Allow-Origin:*');
$con= mysqli_connect ("localhost","root","","mycms");
$query= mysqli_query ($con, "select * from posts ");
$arr = array ();
while ($r = mysqli_fetch_object($query)) {
array_push($arr, array("post_id" => $r->post_id, "post_title" => $r->post_title, "post_author" => $r->post_author,
"post_image" => $r->post_image));
}
print_r(json_encode($arr));
?>
print_r(json_encode($arr)); will not get you a valid json string. print_r() makes your variable human readable and is mainly useful for debugging.
You need:
echo json_encode($arr);
I really have never done this before and I am getting frustrated because I'm not sure how it fits together. I have a function that I want to call my php (one php file selects info from a database and the second inserts into the database)... I need to use ajax in the way my site is setup but I don't know how to pass data from and to the php files.
In first .js file:
q1LoadVar();
This is my ajax function in second .js file that I have so far (not working):
//ajax code has been edited here since original post:
function q1LoadVar() {
alert("called"); //works!
$.get( "q1LoadVar1.php", function( data ) {
console.log(data); //nothing happens!
// alert(data); //nothing happens!
}, "json" );
}
And here is the code I have in q1LoadVar1.php that I want to select data back from and be able to populate a text area in my html:
/*works when I type this file path directly into the url;
but the file is not communicating back to the ajax function on the
.js file that is calling it*/
<?php
$config = parse_ini_file('../config.ini');
$link = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
if(mysqli_connect_errno()){
echo mysqli_connect_error();
}
echo '<script type="text/javascript">alert("working from php!");</script>';
$query = "SELECT * FROM Game1_RollarCoaster";
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_array($result)) {
$newRow[] = $row;
}
$json = json_encode($newRow);
echo $json; //works on php file directly!
/*while ($row = mysqli_fetch_array($result)) {
echo $row[Q1_AnswerChoosen];
}*/
mysqli_free_result($result);
mysqli_close($link);
?>
Can someone help me understand how to make this all work together? Thank you, Kristen
You can retrieve post data from ajax in php with
$_POST['action']
//in your case will return: test
To return data to ajax you need to use echo
If the success: callback function doesnt get called try to remove datatype: 'json'
I also think that you need to echo $newrow instead of $row.
If this still doesnt work you can catch the error with the error: callback function to see what is wrong.
Try to start with a simple request and work from there.
$(document).ready(function() {
$.ajax({
type: "POST",
url: "yourphp.php",
data: {simplestring: "hi"},
success: function(result){
alert(result);
}
});
});
and yourphp.php
<?php
$simplestring = $_POST['simplestring'];
echo $simplestring;
I'm using dataTable and I'm having the Json parse error. Here is my code:
jQuery(function($){
$('#allusers').dataTable({
"sAjaxSource": document.URL+"/allusers.php"
});
$.ajax({
url: document.URL+"/allusers.php",
success: function(data){
alert (data);
}
});
});
So inserted the $.ajax part so that I could see the data being returned. (Well I could also see it using firebug, just wanna make sure) and the response that I am getting is the HTML code instead of the JSON object.
here is the snippet of allusers.php:
$dataArr['aaData'] = Array();
$res = $mysqli->query($query);
$numrows = $res->num_rows;
$output = array('iTotalRecords' => $numrows, "iTotalDisplayRecords" => 10, "aaData" => array() );
if ($res = $mysqli->query($query)){
while($row = $res->fetch_array(MYSQLI_ASSOC)){
$r = Array();
foreach($row as $key=>$value){
$r[] = $value;
}
$output['aaData'][] = $r;
}
} else
die(mysql_errno());
$output['err'] = 'hello';
header('Content-Type: application/json');
echo json_encode($output);
exit();
I already tried var_dump($r) to check the contents of $output and I don't see a problem with it.
So the result that I'm getting is:
<!DOCTYPE html>
<html class="home">
<head>
<title>User List</title>
...
it basically returns the html content of the whole page.
Is the problem within the javascript or php?
Thanks in advance for the help!
Not sure if your PHP framework respects requested datatypes, but you could start by requesting JSON specifically. Either specify:
$.ajax({
url: document.URL+"/allusers.php",
dataType: "application/json",
success: function(data){
alert (data);
}
});
or use the jquery json shortcut:
$.getJSON("url", data, callbackFuntion);
The default for the $.ajax() method is to intelligently guess the output, so it seems weird it doesn't pick up on your content-type.
My last idea would be that you specified php headers and footers globally somehow, so they are added to your output?
I've already fixed this problem. Since I'm using a MVC, I put the function in the controller then just added a code like this:
if (isset($_GET["var"]))
function();
also I removed the
header('Content-Type: application/json');
I don't know why, but when I removed that it worked. Thanks all for pitching in your ideas. :)
This is arrivalPlay.php. This page is loaded if user click data from arrivalRead.php and make the url become arrivalPlay.php?id=1 (2,3,4,5 and so on).
<?php
$con = mysqli_connect("localhost","admin","admin","flight_status");
$id = $_GET['id'];
$getrow = mysqli_query($con, "SELECT * FROM arrival WHERE id='$id'");
$row = mysqli_fetch_array($getrow);
mysqli_close($con);
$order = array(1,2,3,4);
foreach ($order as $o) {
$res[$o][f] = $row[$o];
}
json_encode($res);
?>
This is getData.js file. The file file receive res and will be passed to 'mp'.
<script>
function aha() {
$.ajax({
url:'arrivalPlay.php',
data:{id:3},
dataType:'json',
type:'GET',
success:function(data){
document.write(data[1].f);
document.write(data[2].f);
document.write(data[3].f);
document.write(data[4].f);
}
});
}
</script>
Page arrivalPlay.php only has data if the url become arrivalPlay.php?id=X. Is there any way to retrieve data from the 'dynamic' php to the javascript page? Feel free to change my approach if you think it is odd. Thank you...
Try this:
First in your server page apply echo before json_encode($res);
It should be echo json_encode($res);
And then if it not works then try this code
<script>
$(document).ready(function(){
$(document).on('click','#a',function(e){
e.preventDefault();
$.ajax({
url:'arrivalPlay.php',
data:{id:1},
dataType:'json',
success:function(data){
$('#res').html(data);
}
});
});
});
</script>
If you want json from server then only json data should be passed from server
like in your code
<?php
$con = mysqli_connect("localhost","admin","admin","flight_status");
$id = $_GET['id'];
$getrow = mysqli_query($con, "SELECT * FROM arrival WHERE id='$id'");
$row = mysqli_fetch_array($getrow);
mysqli_close($con);
$res=array();
$order = array('airline','flight','origin','status');
foreach ($order as $o) {
$res[$o] = $row[$o];
}
echo json_encode($res);// echo the json string
// remember that no other output should be generated other than this json
return; //so you can use this line
?>
is enough
but you don't want json then you use this code
echo implode(',',$res); instead of echo json_encode($res);
also in javascript remove this option dataType:'json', in this case.
Read jquery.ajax
Since you are receiving JSON data, I doubt that you would like to place them into an HTML element. I would either change my PHP file to produce HTML elements, or implement som javascript logic to create elements based on the JSON data the server provides.