I've got a game which refreshes info every 10 seconds from a MySQL database. There will be a JS function which is called each time this happens. I can't get the success function to execute, and I have no idea why. No errors on the console, either.
Javascript:
function refreshStats() {
console.log("number 1");
$.ajax({
url: "refreshData.php",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType : 'json',
data: { },
cache: false,
async: true,
success: function (msg) {
if(msg){
console.log("number 2");
var arr = JSON.parse(msg);
document.getElementById("interface_stats").innerHTML =
"Fatigue: " + arr[0];
}
}
});
}
PHP:
<?php
$username = $_POST['user'];
ini_set('display_errors', 1);
error_reporting(E_ALL);
$con = mysql_connect("localhost","redacted","redacted");
if (!$con)
{
die('SQL error! Aborting: ' . mysql_error($con));
}
$db = mysql_select_db("aftertheend",$con) or die("Database error! Aborting. Inform the admin.");
$query = "SELECT fatigue, food, water, radiation, condition FROM users WHERE username='TheMightyThor'";
$result = mysql_query($query, $con);
$data = mysql_fetch_row($result);
$stats = [
"fatigue" => $data[0],
"food" => $data[1],
"water" => $data[2],
"radiation" => $data[3],
"condition" => $data[4]
];
echo json_encode($stats);
?>
I think your PHP is returning an error, rather than the JSON you are expecting. Since you have dataType: 'json', jQuery attempts to parse the response, but fails. When that happens, jQuery does not call the success callback.
If you can, use Firebug to see what is being returned by the ajax call. Another way would be to temporarily change to dataType: 'html' and then change your success callback to:
success: function(msg) { alert(msg); }
Hopefully when you see the message being returned, it will help identify the problem. One thing you should do though, is add code to handle the cases where the query fails to execute and where no row is fetched from the database. You could add the following code to the PHP file:
$result = mysql_query($query, $con);
if (!$result) {
die('Could not run query: ' . mysql_error($con));
}
if (mysql_num_rows($result) < 1) {
echo 'null';
exit;
}
$data = mysql_fetch_row($result);
There are also a few issues with the Ajax call though:
(1) You are specifying contentType: "application/json; charset=utf-8", but then you are not sending JSON. You should do something like this:
data: JSON.stringify({}),
But if you do this, you cannot get the data on the server using the $_POST function. Therefore, you might want to get rid of the contentType setting instead. See this SO answer for more information.
(2) When you specify dataType: 'json', JQuery will parse the response to an object before calling the success callback, so the msg parameter should already be an object. Therefore, you should not call JSON.parse(msg).
(3) You are returning an associative array from the PHP file. That will be converted to a JavaScript object, not an array.
I think you should try the following:
$.ajax('refreshData.php', {
type: 'post',
dataType: 'json',
data: { },
cache: false,
success: function (data) {
if (data) {
$('#interface_stats').html('Fatigue: ' + data.fatigue);
}
}
});
Related
I have the following script:
$("#spid").blur(function() {
$.ajax({
url: 'getsponsor.php',
type: "POST",
dataType:'json',
data: ({ spid: $("#spid").val() }) ,
contentType: 'application/json; charset=utf-8',
success: function (result) {
$("#sponname").text(result);
},
error: function () {
$("#sponname").text("Cannot fetch the sponsor name.");
}
});
});
Note: #sponname is a label tag.
Following is the php code of getsponsor.php:
if(!isset($_POST['spid']) || empty($_POST['spid']))
echo json_encode("No Data");
else {
$spid=$_POST['spid'];
$stmt = $con->prepare("SELECT name FROM users WHERE id=?");
$stmt->bind_param("s",$spid);
$stmt->execute();
$stmt = $stmt->get_result();
if ($stmt->num_rows >0) {
$row = $stmt->fetch_object();
echo json_encode($row->name);
}
else {
echo json_encode("No Records");
}
}
When I Inspect the page and goto Network->Params, I get the right value from the textbox:
spid=1125468
But, when I go to Network->Response, I get the following message
"No Data"
Please tell what wrong I am doing?
Get rid of this line:
contentType: 'application/json; charset=utf-8',
The data is being sent URL-encoded, not as JSON. jQuery will send the correct Content-type header by itself.
I have a javascript that sends an array through AJAX to a server side PHP script.
I am attaching relevant code snippets of my javascript AJAX function below:
$.ajax({
url: "bar2.php",
type: "POST",
data:{data:x},
dataType: "json",
contentType: "application/json; charset=utf-8",
error: function(xhr, status, error) {
console.log(status);console.log(error);
},
success:function(data){
//do stuff
}
}
);
x is my array which I am sending.
I access this array in my PHP script as shown below:
$data = $_REQUEST['data'];
$len = $data.length;
$x=format_array($data);
function format_array($data){
return "'" . implode("', '", $data) . "'";
}
$myquery = "
select state,count(device_id) as c_num from base_data where state
IN($x)group by state order by c_num DESC limit 10;
";
$query = mysql_query($myquery);
But when I run it I get the error:
Warning: implode(): Invalid arguments passed in **** on line 16
Please help. I have spent an hour on this and am not able to figure it out. Am I sending the data in the correct way?
Any pointers would be appreciated.
You need to convert your array to JSON then send it to PHP (server side):
$.ajax({
url: "bar2.php",
type: "POST",
data: {data: JSON.stringify(x)},
dataType: "json",
contentType: "application/json; charset=utf-8",
error: function(xhr, status, error) {
console.log(status);console.log(error);
},
success:function(data){
//do stuff
}
});
PHP:
$data = json_decode($_REQUEST['data']);
$len = count($data);
//.....
//.....
Remove contentType: "application/json; charset=utf-8", and you will receive as array of form encoded data (application/x-www-form-urlencoded) which is $.ajax default
Also use count() instead of length in php
I need help to do something small but I don't know how to solve it.
I have a javascript file with ajax inside like this
$.ajax({
data: "mc_id="+someid,
url: "includes/getDataPrs.php",
type: "GET",
dataType: "json",
async: false,
success: function(msg){
//some function here
}
});
in getDataPrs.php
<?php
include_once 'db_connect.php';
include_once 'functions.php';
sec_session_start();
header('Content-Type: application/json');
$id = null;
$date = null;
$limit = 0;
if (isset($_GET['mc_id'])) {
$id = $_GET['mc_id'];
}
//some process here $data
echo json_encode($data);
I can get data from $_GET['mc_id'] but when I need more data and I change the parameters in javascript like this
$.ajax({
data: "{'mc_id':'"+someid+"','limit':'"+somelimit+"'}",
url: "includes/getDataPrs.php",
and then I got nothing in php $_GET['mc_id'] or $_GET['limit']
in my desperate to solve it, I put in url "includes/getDataPrs.php?mc_id=someid&limit=somelimit
any comment or suggestion I truly appreciated
thanks in advance
passing multiple variable in ajax should be like
$.ajax({
data: {mc_id: someid, limit: some_limit},
url: "includes/getDataPrs.php",
type: "GET",
dataType: "json",
async: false,
success: function(msg){
//some function here
}
});
It is always better to use data: {mc_id: someid, limit: some_limit} because it will treated like object itself.
Try using following syntax for sending data in ajax function:
...
data:{mc_id:someid,limit:somelimit},
...
Without using quotes.
Change from
data: "{'mc_id':'"+someid+"','limit':'"+somelimit+"'}",
To
data: "mc_id="+someid+"&limit="+somelimit,
Follow the below steps:
1) Replace `data: "mc_id="+someid,` with `data: { mc_id: someid},`. (required)
2) Now you can get your data in PHP file like `$_POST['mc_id']` (optional). It is better to use `type: 'POST'`in your jQuery code.
So below is your whole code:
$.ajax({
data: { mc_id: someid},
url: "includes/getDataPrs.php",
type: 'POST',
dataType: "json",
async: false,
success: function(msg){
//some function here
}});
in getDataPrs.php
<?php
include_once 'db_connect.php';
include_once 'functions.php';
sec_session_start();
header('Content-Type: application/json');
$id = null;
$date = null;
$limit = 0;
if (isset($_POST['mc_id'])) {
$id = $_POST['mc_id'];
}
//some process here $data
echo json_encode($data);
?>
You try this
$.ajax({
type: "POST",
url: "includes/getDataPrs.php",
data: {'mc_id': someid, 'limit': somelimit}.done(function (response) {
//
});
});
I have this code:
function openIzmeni(value) {
$.ajax({
url: "getRzaizmenu.php",
type: "POST",
async: true,
data: { vrednostid:value}, //your form data to post goes here as a json object
dataType: "html",
success: function(data) {
console.log(data);
$('#brojracuna1').val(data[0].br);
console.log(data[0].br);
console.log(data.br);
so as you can see I call getRzaizmenu.php to get JSON output.
getRzaizmenu.php code is:
try {
$result = $db->prepare("SELECT * FROM racuni WHERE ID=:id AND user_id=:user_id");
$result->execute(array(':id' => $_POST['vrednostid'], ':user_id' => $user_id));
$result = $result->fetchAll();
$r= json_encode($result);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
echo $r;
and this php return me output:
[{"ID":"22","0":"22","prefiks":"","1":"","br":"14321","2":"14321","sufiks":"993.67","3":"993.67","kupac":"Pavle Aleksov","4":"Pavle Aleksov","adresa":"Desanka Maksimovic 6\/a","5":"Desanka Maksimovic 6\/a","grad":"18320 Dimitrovgrad","6":"18320 Dimitrovgrad","pib":"567890","7":"567890","total":"1200.00","8":"1200.00","valuta":"Din","9":"Din","nacin":"gotovinsko","10":"gotovinsko","datum":"2015-05-25","11":"2015-05-25","rok":"2015-05-25","12":"2015-05-25","isporuka":"2015-05-25","13":"2015-05-25","naplaceno":"0000-00-00","14":"0000-00-00","napomene":"","15":"","interne":"","16":"","jezik":"","17":"","status":"","18":"","sifra":"yyx5y","19":"yyx5y","user_id":"1","20":"1"}]
So this code return me "0":22 and "ID":22 but its the same column.
and you can see I try to use this data into ajax success function like this:
success: function(data) {
console.log(data);
$('#brojracuna1').val(data[0].br);
console.log(data[0].br);
console.log(data.br);
but I get undefined.
How I can use data in success?
Change
dataType: "html",
to
dataType: "json",
And try again.
you have encoded the data, that's ok.
But while parsing you are not decoding the data. So you have to decode the data using JSON.parse() and parse function.
You need to parse the JSON, try like this
success: function(data) {
$.each(data, function(index, element) {
console.log(index);
console.log(element);
});
});
Okay now i am having a weird issue here, sometime back i learned how to encode and decode a json array properly here on stackoverflow but now i am having a weird issue on my godaddy server that i cannot comprehend, maybe i may have made i typo or something somewhere in code but i honestly cannot tell what is wrong here. The code works okay on my localhost but not when i upload it too my godaddy server.
The code here is basically supposed to pass an id as a json to the php server which is then supposed to execute a query using the id as a parameter.
Here is the jquery code:
<script text="text/javascript">
$(document).ready(function() {
$('#download').click(function(e) {
// e.preventDefault();
var tid = $('#id').val().trim();
var data = {
ID:tid
};
$.ajax({
type: "POST",
url: "xxxxx-xxxxxxx.php",
data: {
data: JSON.stringify(data)
},
dataType: "json",
success: function(response) {
}
});
});
});
</script>
and this is the php code:
<?php
if (isset($_POST['data']))
{
$Data = $_POST["data"];
$arr = json_decode($Data);
$id = $arr->ID;
$sql = $pdo->prepare("update ********** set ******** = ******** + 1 where id=:id");
$sql->bindValue("id", $id, PDO::PARAM_INT);
$sql->execute();
unset($_POST['data']);
}
?>
Now i checked if the value was being sent to the server using my browser console and it was. I also checked if the $_POST['data'] on the server contained any data using var_dump and it did in fact have the data i wanted.
in the ajax set the content type to contentType: "application/json",
so:
$.ajax({
type: "POST",
url: "xxxxx-xxxxxxx.php",
data: {
data: JSON.stringify(data)
},
contentType: "application/json",
success: function(response) {
}
});
and in the php use:
$json = file_get_contents('php://input');
$data = json_decode($json);