Ajax JSON Not Returning Data - php

I am attempting to use jQuery/Ajax to call a PHP file returning all the required data in JSON format, however the page just gets stuck with the text "loading" at the bottom of the screen.
I have read various other posts on this but none have helped solve this issue for me.
$(document).ready(function() {
$.ajax({
type: 'POST',
dataType: 'json',
url: 'php/process.php',
data: data,
success: function(data) {
$('.data').html(data['name']);
}
});
});
Simply including the PHP file in the page echoes the JSON with no problem, it's just calling it through jQuery/Ajax that isn't working for me.
<?php
$mysqli = new mysqli('localhost', 'test', 'pass#word1', 'test');
$sql = "SELECT * FROM test_json";
$result = $mysqli->query($sql);
$data = array();
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
array_push($data, $row);
}
}
echo json_encode($data);
?>
Any help is greatly appreciated. Thanks.

You might try adding a header
<?php
header('Content-Type: application/json; charset=utf-8');
right click and Inspect element.
Select the Network Tab
Select XHR at the bottom of the window
check the Response Header and the Response body.
Add
echo sql_error();
print_r($data);
From the Inspector I do not see a Request to "process.php"
I do see one to fetchposts()
fetchposts returns 3 line feeds and and a zero with a content length of 5 bytes

Related

ajax and php: how to select variables from database and insert in database using ajax

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;

Creating a Callback with JSONP

I'm attempting to access data cross domain (testing locally) but the data keeps failing to load.
$.ajax({
type: 'POST',
url: 'http://localhost/php/ajax/json.php',
dataType: 'jsonp',
data: {action: 'get_json'},
success: function(data) {
console.log(data);
},
error: function() {
console.log("Error loading data");
}
});
The PHP is as follows (function is called through a switch statement earlier in the file).
function get_json() {
$mysqli = db_connect();
$sql = "SELECT * FROM json_test";
$result = $mysqli->query($sql);
$rows = array();
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
array_push($rows, $row);
}
}
echo $_GET['callback']."(".json_encode($rows).");";
}
Headers are set at the start of the PHP document.
header('Content-Type: application/json');
The error I am receiving (if I run the PHP file by itself) is Undefined index: callback. The json string echoes fine as text after this error. (I have tried echo $_POST[...] as well).
How can I get this callback to work or how do I define it properly? Any help is appreciated.
add this parameter:
&jsoncallback=?
I was able to fix the error in the PHP file by changing the callback to the following:
$callback = "";
if (array_key_exists('callback', $_GET) == TRUE) {
$callback = $_GET['callback'];
}
echo $callback."('".json_encode($rows)."');";
The AJAX query now also retrieves the JSON data successfully.

$.ajax call doesnt work with dataType:'json'

Please excuse me if this sounds stupid but I have been at it for quite some time now and cant figure out the problem.
so what I am trying to do is :
--Make a ajax call to a php script that queries mongodb collection for some documents
-- This ajax calls gets a json back and renders it on browser.
The problem I am having is at the first step itself.
here's my ajax call :
$.ajax({
type :'get',
url: "get_data.php",
dataType : 'json',
success: function(msg){
alert(msg);
}
});
here's the php code:
$n = new MongoClient();
$dbname = "wsd";
$db = $n->$dbname; //get the collections..
$collection = $db->raretweets;
$cursor = $collection->find();
header('Content-type: application/json');
echo json_encode($cursor);
I suspected the problem might be with the $cursor object , So I tried the following basic stuff
$data = 3;
header("Content-Type: application/json", true);
/* Return JSON */
echo json_encode($data);
Even this gives me an error "No element found" in console logs of firebug.
I was wondering if anybody can hint me about the problem.
What if you try something really basic, something like this:
$.get(url, function(data){
if(data!='Error') {
alert(data);
}
And in PHP
$data = 3;
if($data) {
echo number_format($data);
} else {
die('Error');
}
Does this give you a result?

Error with JSON Ajax get method

I am using a jquery ajax get method to fetch information from the server however I am having trouble parsing the information so that I may use it. My website has a gallery of products that will filter its items based on category.
Here is the jQuery ajax function:
$('.category').click(function() {
var category;
if ($(this).hasClass('Shirts')) {
category = 'shirts';
}
if ($(this).hasClass('Hats')) {
category = 'hats';
}
if ($(this).hasClass('Acc')) {
category = 'acc';
}
$.ajax({
type: 'GET',
url: 'galleryfetch.php',
data: { 'category' : category },
dataType: 'json',
success: function(data) {
arr = $.parseJSON(data);
alert(arr);
}
});
});
This is the php script that the information is posted to:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$category = $_GET['category'];
$conn = mysqli_connect('localhost', '*****', '*****', 'clothing');
$rows = mysqli_query($conn, "SELECT * FROM products WHERE category = '".$category."'");
while ($row = mysqli_fetch_array($rows)) {
$arr[] = $row;
}
echo json_encode(array('data' => $arr));
}
I using the alert in the success function to see if the information is passed succesfully but at the moment there is no alert and i get an:
Unexpected token o error.
I'm not sure if I'm parsing the information correctly or if Im not correctly using JSON
tl;dr: $.parseJSON(data); should be removed.
Your server is returning JSON (but claiming it is sending HTML, you should have header("Content-Type: application/json")).
You have told jQuery to ignore the claim that it is HTML and parse it as JSON. (This would be redundant if you fixed the above problem)
dataType: 'json',
The parsed data is passed to your success function.
You then pass that data to JSON.parse so it gets converted to a string (which will look something like [ [Object object], ... and is not valid JSON) and then errors.
Remove:
arr = $.parseJSON(data);
And just work with data.

JSON returns an HTML result

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. :)

Categories