I have difficulty parsing JSON date from my PHP file
{"date":"20\/12\/2022","result":"£13000.00","medias":"BBC","country":"UK"}
but when I try to parse it and to see the data in the console.log - it's empty
Please help
My Ajax Function
function ajax_call(){
const style2 = $("#style1").val();
const radio_btn = $('input[name="drone"]:checked').val();
if(style2==""){
document.getElementById("error").innerHTML = "Error: Please enter style code !";
return false;
}
{
$.ajax({
type: 'post',
url: "t.php",
data: { styles: style2 , country: radio_btn},
dataType: "json",
success: function(data){
var jsondata = $.parseJSON(data);
console.log(jsondata);
}
})
}
}
My PHP
<php
header('Content-type: application/json');
$date = "20/12/2020";
$end_result = "£13000.00";
$medias = "BBC";
$country = "UK";
$sortjson = array('date' => $date,
'result' =>iconv('Windows-1252', 'UTF-8', $end_result),
'medias' => $medias,
'country' => $country
);
echo json_encode($sortjson, JSON_UNESCAPED_UNICODE);
?>
I believe there is a typo in the PHP code, you need to change the first line from:
<php
to
<?php
If the first line is <php, the output won't be valid JSON.
Complete PHP code:
<?php
header('Content-type: application/json');
$date = "20/12/2020";
$end_result = "£13000.00";
$medias = "BBC";
$country = "UK";
$sortjson = array('date' => $date, 'result' =>iconv('Windows-1252', 'UTF-8', $end_result), 'medias' => $medias, 'country' => $country);
echo json_encode($sortjson, JSON_UNESCAPED_UNICODE);
?>
Also, I'm not 100% sure you need the iconv call, you could try the below code:
<?php
header('Content-type: application/json');
$date = "20/12/2020";
$end_result = "£13000.00";
$medias = "BBC";
$country = "UK";
$sortjson = array('date' => $date, 'result' => $end_result, 'medias' => $medias, 'country' => $country);
echo json_encode($sortjson, JSON_UNESCAPED_UNICODE);
?>
You have a error in your Success method:
use JSON.parse() method instead of $.parseJSON()
success: function(data){
var jsondata = JSON.parse(data);
console.log(jsondata);
}
You have to use JSON.parse()
function ajax_call(){
const style2 = $("#style1").val();
const radio_btn = $('input[name="drone"]:checked').val();
if(style2==""){document.getElementById("error").innerHTML = "Error: Please enter style code !"; return false;} {
$.ajax({
type: 'post',
url: "t.php",
data: { styles: style2 , country: radio_btn},
dataType: "json",
success: function(data){
var jsondata = JSON.parse(data);
console.log(jsondata);
}
})
}
}
Related
I'm trying to get some data trough AJAX but am getting an error with an empty responseText.
My code is as follows:
JS:
function getFounder(id) {
var founder = "";
$.ajax({
url: '/data/founder_info.php',
data: {founder: id},
dataType: 'json',
async: false,
type: 'post',
success: function(json) {
//founder = json.username;
console.log(json);
},
error: function(ts) {
console.log("Error: " + ts.responseText);
}
});
return founder;
}
PHP:
<?php
require_once '../core/init.php';
if($_POST['founder']) {
$u = new User();
$user_info = $u->find(escape($_POST['founder']));
$user_info = $u->data();
echo json_encode($user_info);
exit();
}
I cannot find the issue as to why it is throwing the error.
I fixed it using a method to convert everything to UTF-8.
function utf8ize($d) {
if (is_array($d))
foreach ($d as $k => $v)
$d[$k] = utf8ize($v);
else if(is_object($d))
foreach ($d as $k => $v)
$d->$k = utf8ize($v);
else
return utf8_encode($d);
return $d;
}
This was posted as an answer to this question
My problem is now solved!
I am trying to get the results from an AJAX call, but I keep getting the error results of the function and I have no idea why.
Here is the javascript:
var curfrndurl = "http://www.website.com/app/curfrnd.php?frndid=" + secondLevelLocation + "&userid=" + items;
$("#loadpage1").click(function(event){
event.preventDefault();
$.ajax({
url: curfrndurl,
dataType: 'json',
type: "GET",
success: function (data){
if (data.success) {
alert("Hi");
$("#curstatus").html(data);
$("#curstatus2").hide();
$("#subtform").hide();
}
else
{
alert("Bye");
$("#curstatus2").html(data);
$("#curstatus").hide();
$("#addform").hide();
}
},
error: function() {
alert('Doh!');
}
});
});
The PHP file is:
<?php
$userdbme = $_GET['userid'];
$frndid = $_GET['frndid'];
$query2 = mysql_query("SELECT * FROM follow WHERE yoozer1='$userdbme' AND yoozer2='$frndid' ORDER BY followid DESC LIMIT 0,1");
$numfriends = mysql_num_rows($query2);
if ($numfriends!=0)
{
echo json_encode(array(
'success' => true
//'user_name' => $userdb
));
echo "<h4>Current Friends</h4>";
}
else {
echo json_encode(array('success' => false));
echo "<h4>Not Friends</h4>";
}
?>
Any help would be greatly appreciated! Thanks!
If you want to echo JSON data, then you need to make sure you don't echo anything else before or after the data.
echo json_encode(array(
'success' => true
));
echo "<h4>Current Friends</h4>";
This is not parsable as JSON, because of the "extra" stuff after the JSON data. Try this:
echo json_encode(array(
'success' => true,
'html' => "<h4>Current Friends</h4>"
));
Then you can do: $("#curstatus").html(data.html);
I try to send an array of json objects from the javascript to a Php code. Unable to get a response from the php file.
function getData() {
var jsonObject = [];
var genderMenu = document.getElementById("gender");
var levelMenu = document.getElementById("level");
jsonObject[0] = {
psid: document.getElementById("psid").value,
fName: document.getElementById("fname").value,
lName: document.getElementById("lname").value,
gender: genderMenu.options[genderMenu.selectedIndex].value,
};
for(var i = 1; i <= varCount; i++) {
if(document.getElementById("fName"+(i))) {
jsonObject[i] = {fName : document.getElementById("fName"+(i)).value,
lName: document.getElementById("lName"+(i)).value,
};
}
}
var jsonObjectString = JSON.stringify(jsonObject);
var result = "";
$.ajax({
type: 'POST',
url: '/inviteProcessing.php',
data: {myData: jsonObject},
success: function(response) {
if(response.success)
alert(response.message);
else
alert(response.message);
}
});
alert(jsonObject);
}
Php File has the following code
<?php
$input = $_POST['myData'];
$input_string = json_decode($input, true);
echo json_encode( array('success' => true, 'message' => $input_string) );
?>
Do u see any problem?
Prior to echoing your output, try...
header('Content-type: application/json');
echo $encodedjsonstring;
exit;
Please try below points.
First check if path of the php file is correct.
Then add below line in ajax call.
type: 'POST',
dataType: "json", //add dataType
url: '/inviteProcessing.php',
data: {myData: jsonObject},
try to put exit or die() at the end of php file
i have an array , which has to be passed from backend to frontend using ajax, i am new to ajax i know the syntax but got stuck , below is my code
backend(PHP)
$s_q = "SELECT `ans` FROM `bec_log_response` WHERE session_id=1 AND paper_id=2";
$s_res = mysql_query($s_q, $db2);
while($row= mysql_fetch_array($s_res))
{
echo $row['ans'];
}
$result = array('ans' => $row['ans'] );
Javascript code
function get_solution()
{
$.ajax({
url: 'waiting.php',
dataType: 'json',
type: 'GET',
timeout: 30 * 1000,
data: {sol:row},
success: function(json){
$('#saved').html(json.ans);
},
error: function(){}
});
}
i am getting an error in this code data: {sol:row}.
The response data from php is not in json format..
$result = array('ans' => $row['ans'] );
echo json_encode($result);
add this in your php code
Create a JSON on the PHP Side and catch it with $.getJSON jquery
Server Side:
$row_1 = array();
$s_q = "SELECT `ans` FROM `bec_log_response` WHERE session_id=1 AND paper_id=2";
$result = mysql_query($s_q) or die (mysql_error());
while($r = mysql_fetch_assoc($result)) {
$row_1[] = $r;
}
$post_data = json_encode(array('ans' => $row_1));
echo $post_data;
Client Side:
$.getJSON("result.php", function(json) {
console.log(json)
$.each( json, function( key, data ) {
//loop through the json if necessary
});
});
I don't know why this double json response are not successful:
[{"first_content":"content",...}][{"second_content":"content",...}]
So i am getting the message Oops! Try Again.
if(isset($_GET['start'])) {
echo get_posts($db, $_GET['start'], $_GET['desiredPosts']);
echo get_posts1($db, $_GET['start'], $_GET['desiredPosts']);
$_SESSION['posts_start']+= $_GET['desiredPosts'];
die();
}
var start = <?php echo $_SESSION['posts_start']; ?>;
var desiredPosts = <?php echo $number_of_posts; ?>;
var loadMore = $('#load-more');
loadMore.click(function () {
loadMore.addClass('activate').text('Loading...');
$.ajax({
url: 'profile.php',
data: {
'start': start,
'desiredPosts': desiredPosts
},
type: 'get',
dataType: 'json',
cache: false,
success: function (responseJSON, responseJSON1) {
alert(responseJSON);
loadMore.text('Load More');
start += desiredPosts;
postHandler(responseJSON, responseJSON1);
},
error: function () {
loadMore.text('Oops! Try Again.');
},
complete: function () {
loadMore.removeClass('activate');
}
});
});
What is the solution to get a double json response ? With one there is no problem
"Double JSON response" as you call them is basically invalid JSON. You should have something like so:
{"first_content":"content", "second_content":"content",...}
Or as a couple of people mentioned:
[{"first_content":"content",...}, {"second_content":"content",...}]
You probably need to modify some server side code, your get_posts function could return a PHP array instead of a JSON array. Example:
function get_posts(){
$array = array('content' => 'foo', 'title' => 'bar');
return $array;
}
Then in your profile.php:
if(isset($_GET['start'])) {
$posts = get_posts($db, $_GET['start'], $_GET['desiredPosts']);
$posts1 = get_posts1($db, $_GET['start'], $_GET['desiredPosts']);
echo array($posts, $posts1);
$_SESSION['posts_start']+= $_GET['desiredPosts'];
die();
}