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. :)
Related
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 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
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?
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)
I've been trying to figure out what I have done wrong but when I use my JavaScript Console it shows me this error : Cannot read property 'success' of null.
JavaScript
<script>
$(document).ready(function() {
$("#submitBtn").click(function() {
loginToWebsite();
})
});
</script>
<script type="text/javascript">
function loginToWebsite(){
var username = $("username").serialize();
var password = $("password").serialize();
$.ajax({
type: 'POST', url: 'secure/check_login.php', dataType: "json", data: { username: username, password: password, },
datatype:"json",
success: function(result) {
if (result.success != true){
alert("ERROR");
}
else
{
alert("SUCCESS");
}
}
});
}
</script>
PHP
$session_id = rand();
loginCheck($username,$password);
function loginCheck($username,$password)
{
$password = encryptPassword($password);
if (getUser($username,$password) == 1)
{
refreshUID($session_id);
$data = array("success" => true);
echo json_encode($data);
}
else
{
$data = array("success" => false);
echo json_encode($data);
}
}
function refreshUID($session_id)
{
#Update User Session To Database
session_start($session_id);
}
function encryptPassword($password)
{
$password = $encyPass = md5($password);
return $password;
}
function getUser($username,$password)
{
$sql="SELECT * FROM webManager WHERE username='".$username."' and password='".$password."'";
$result= mysql_query($sql) or die(mysql_error());
$count=mysql_num_rows($result) or die(mysql_error());
if ($count = 1)
{
return 1;
}
else
{
return 0;;
}
}
?>
I'm attempting to create a login form which will provide the user with information telling him if his username and password are correct or not.
There are several critical syntax problems in your code causing invalid data to be sent to server. This means your php may not be responding with JSON if the empty fields cause problems in your php functions.
No data returned would mean result.success doesn't exist...which is likely the error you see.
First the selectors: $("username") & $("password") are invalid so your data params will be undefined. Assuming these are element ID's you are missing # prefix. EDIT: turns out these are not the ID's but selectors are invalid regardless
You don't want to use serialize() if you are creating a data object to have jQuery parse into formData. Use one or the other.
to make it simple try using var username = $("#inputUsername").val(). You can fix ID for password field accordingly
dataType is in your options object twice, one with a typo. Remove datatype:"json", which is not camelCase
Learn how to inspect an AJAX request in your browser console. You would have realized that the data params had no values in very short time. At that point a little debugging in console would have lead you to some immediate points to troubleshoot.
Also inspecting request you would likely see no json was returned
EDIT: Also seems you will need to do some validation in your php as input data is obviously causing a failure to return any response data
Try to add this in back-end process:
header("Cache-Control: no-cache, must-revalidate");
header('Content-type: application/json');
header('Content-type: text/json');
hope this help !
i testet on your page. You have other problems. Your postvaribales in your ajax call are missing, because your selectors are wrong!
You are trying to select the input's name attribute via ID selector. The ID of your input['name'] is "inputUsername"
So you have to select it this way
$('#inputUsername').val();
// or
$('input[name="username"]').val();
I tried it again. You PHP script is responsing nothing. Just a 200.
$.ajax({
type: 'POST',
url: 'secure/check_login.php',
dataType: "json",
data: 'username='+$("#inputUsername").val()+'&password='+$("#inputPassword").val(),
success: function(result) {
if (result.success != true){
alert("ERROR");
} else {
alert("HEHEHE");
}
}
});
Try to add following code on the top of your PHP script.
header("Content-type: appliation/json");
echo '{"success":true}';
exit;
You need to convert the string returned by the PHP script, (see this question) for this you need to use the $.parseJSON() (see more in the jQuery API).