Use JSON result when ajax success - javascript

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

Related

error when post to php with ajax and json

I tried everything but it still don't work.
Without $_POST value it is working, without JSON it's working, with both it's not.
Function shows this error:
<b>Notice</b>: Undefined index: someVar1 in <b>C:\xampp\htdocs\ajax3\test.php</b> on line <b>2</b><br />
Array()
{"jeden":"Po obr\u00f3bce 123 123 ","dwa":null}"
script.js
$(document).ready(function(){
var data = {
someVar1: '123'
};
data = JSON.stringify(data);
$.ajax({
method: "POST",
url: "test.php",
dataType : 'json',
contentType: "application/json; charset=utf-8",
data: data,
success: function(json) {
$.each(json, function(i, ob) {
console.log(i, ob);
});
},
error: function(error) {
console.log(error);
}
});
});
and test.php
<?php
$someVar1 = $_POST['someVar1'];
$a = " 123 ";
$result = array();
$result['jeden'] = 'Po obróbce ' . $a . $a;
$result['dwa'] = $someVar1;
echo json_encode($result);
?>
It because you send data in JSON format. $_POST will be empty always
In this case you need to use I/O stream
Try this
$postData = json_decode(file_get_content('php://input'));
look more http://php.net/manual/en/wrappers.php.php

php sending values to ajax faild error

I Am trying to send value from ajax to php and retrieve it just to test that everything is work, when i click in a button to test i got error and alert('Failed') Appears , how can i fix it in order to get success? thanks
Ajax :
var a = "test";
$.ajax({
url: "search.php",
dataType: "json",
data: a ,
success: function(data) {
alert('Successfully');
},
error: function(data) {
alert('Failed');
}
})
PHP :
<?php
$pictures = "img1";
echo json_encode($pictures);
?>
I refined your code slightly and it works.
var a = "test";
$.ajax({
type: 'POST',
url: 'search.php',
data: 'a=' + a,
dataType: 'json',
cache: false,
success: function (result) {
alert('Successful');
},
error: function (result) {
alert('Failed');
}
});
If you're requesting a JSON, use the $.getJSON from jQuery, it's aready parse the JSON into a JSON object for you.
Seems that you're not return an actual JSON from server, maybe this is what is causing the error.
If you're seeing the 'Failed' message probably the problem is a 500 error which is a server error.
Try this code above.
Javascript:
var a = "test";
$.getJSON("search.php", {
a: a
}, function (json) {
console.log(json);
});
PHP:
<?php
$pictures = ["img1"];
echo json_encode($pictures);
The only way to this not work, is if you have a huge mistake on you webserver configuration.
Your ajax is wrong, it should be:
var a = "test";
$.ajax({
type: "POST",
url: "search.php",
dataType: "json",
data: {a:a},
success: function(data) {
alert('Successfully');
},
error: function(data) {
alert('Failed');
}
});

checking JSON data with jQuery

I have written a php script:
cch.php:
$stmtcheck = $mysqli->prepare("SELECT id,email,location FROM members WHERE email=? AND unlock_code=?");
$stmtcheck->bind_param("si", $_SESSION['unlockemail'], $_POST['code']);
$stmtcheck->execute();
$stmtcheck->bind_result($id,$email,$location);
$stmtcheck->fetch();
$array=array($id,$email,$location);
json_encode($array);
$stmtcheck->close();
And jquery for submitting form is
recover.php:
$("#formUnlock").submit(function(e)
{
e.preventDefault();
$.ajax(
{
url: '../scripts/cch.php',
method: 'POST',
data: $(#formUnlock).serialize(),
dataType: 'JSON',
success: function()
{
}
});
});
The script is returning more than one variable and the returned data should be in JSON format.
How do I read the data in jQuery?
$("#formUnlock").submit(function(e)
{
e.preventDefault();
$.ajax(
{
url: '../scripts/cch.php',
method: 'POST',
data: $(#formUnlock).serialize(),
dataType: 'JSON',
success: function(data) //parameter missing
{
var json = $.parseJSON(data);
console.log(json);
//in console you will get the result response
}
});
});
Hello your php code should echo the JSON output like this:
<?php
$stmtcheck = $mysqli->prepare("SELECT id,email,location FROM members WHERE email=? AND unlock_code=?");
$stmtcheck->bind_param("si", $_SESSION['unlockemail'], $_POST['code']);
$stmtcheck->execute();
$stmtcheck->bind_result($id,$email,$location);
$stmtcheck->fetch();
$array=array($id,$email,$location);
$stmtcheck->close();
echo json_encode($array);
?>
Now, in your javascript, you can use JSON.parse method to get the JSON.
Also, specifying your response type as JSON will automatically return a JSON object.
$("#formUnlock").submit(function (e) {
e.preventDefault();
$.ajax({
url: '../scripts/cch.php',
method: 'POST',
data: $('#formUnlock').serialize(),
dataType: 'JSON',
success: function (json_string) {
var res = JSON.parse(json_string);
console.log(res);//This should output your JSON in console..
}
});
});

How do i parse json data retrieved from php script in javascript or jquery

Please somebody help me, am new to ajax, i have been trying to read json data from php script but just no success.
when i console.log the data i get this,
{"name":"JOHN","surname":"FIGO","sex":"M","Records_id":"1","student":""}.
and when i do this console.log(data[2]); i simply get n character. what i want is to get the values, for example, console.log(data['name']); should give JOHNor console.log(data[0]); should give JOHN. when i use either javascript or jquery parse methods, i get an error, i dont understand. Here is are the codes;
<?php
$conn= new mysqli('localhost', 'root', '', 'Goldfinger');
$query= 'SELECT * FROM records';
$result= $conn->query($query);
while($row = $result->fetch_assoc()) {
echo json_encode($row);
}
?>
and jquery;
$('#one').click(function () {
$.ajax({
url: 'ajaxtesting.php',
type: 'POST',
success: function (data) {
if (data) {
console.log(data['name']);
};
},
error: function () {
$('div:not(#one)').text('error dude!');
}
})
})
pardon my code if it's very poor. Thank you in advance.
Put dataType : 'json', inside ajax setting like so :
$.ajax({
url: 'ajaxtesting.php',
type: 'POST',
dataType : 'json', //<------------- here
success: function (data) {
if (data) {
console.log(data['name']);
};
},
error: function () {
$('div:not(#one)').text('error dude!');
}
})
or simply parse inside success callback :
$.ajax({
url: 'ajaxtesting.php',
type: 'POST',
success: function (data) {
var myData = $.parseJSON( data ); //<------- here
if ( myData ) {
console.log(myData['name']);
};
},
error: function () {
$('div:not(#one)').text('error dude!');
}
})

Ajax response undefined or strange

i'm trying to send an array to JS, but i can't have the answer i want.
this is my PHP code:
$output = array('total'=>(float)$BHoras[1]'gastas'=>(float)$BHoras[2]);
echo json_encode($output);
and this is my JS code:
function ProjectSelect()
{
var proj = document.getElementById('ProjetosSelect').value;
$.ajax({
url: 'CRM files/TSread.php',
type: "POST",
data: ({ProjetosSelect: proj}),
complete:function(data)
{
var Horas = data.responseText;
alert(Horas); // response -> {"total":146,"gastas":84.5}
alert(Horas[3]); // response -> o
}
});
}
i only want the "146" and "84.5".
i tried to do, alert(Horas['total']), alert(Horas.total), but give me undefined
Just specify dataType: "json" and jQuery will parse response for you:
function ProjectSelect()
{
var proj = $('#ProjetosSelect').val();
$.ajax({
url: 'CRM files/TSread.php',
type: "POST",
data: ({ProjetosSelect: proj}),
dataType: "json",
success: function(Horas)
{
alert(Horas.total);
}
});
}
On server side you could try TracKer note. And you can add a header too.
<?php
$output = array('total'=>(float)$BHoras[1], 'gastas'=>(float)$BHoras[2]);
header('Content-type: application/json');
echo json_encode($output);

Categories

Resources