echo json_encode() not working via ajax call - php

I really don't know what i'm missing here. I have this script:
<script type="text/javascript">
function ServiceOffer(){
var service_name = $('#service_name').val(),
dataString = "service=" + service_name;
$.ajax({
type: "POST",
url: "posted.php",
data:dataString,
success:function(data){
console.log(data);
}
});
}
$(document).ready(function(){
ServiceOffer();
$(document).on('change','#service_name',function(){
ServiceOffer();
});
});
</script>
And here is my code for posted.php
<?php
$connect = mysql_connect('localhost','root','') or die('Unable to connect'.mysql_error());
$select = mysql_select_db('hcs',$connect) or die('Unable to select database'.mysql_error());
$service = $_POST['service'];
$query = mysql_query("SELECT * FROM serviceoffer WHERE servicename = '$service'");
$num = mysql_num_rows($query);
while($rows = mysql_fetch_array($query)){
$data[] = $rows;
}
echo json_encode($data);
So what i'm missing? I don't think there is a string that is being attached in my code and it gives me string in my console and not json encoded data. Please Help! Thanks!
Edit: Here is the data that is being returned in my console.

You have three options:
Add dataType: 'json' to the options in $.ajax.
Add header("Content-type: application/json"); to the PHP code.
Use console.log($.parseJSON(data)) in the success function.
Note that you shouldn't use option 3 if you've also used options 1 or 2. jQuery automatically parses the JSON in the first two cases, and you'll try to parse the result of that, which won't work.

At a minimum, you should send the appropriate header in PHP, eg
header('Content-type: application/json');
echo json_encode($data);
exit;
You can also set the dataType in jQuery's $.ajax method to specify the expected response type. I also find it easier to send request parameters as object literals (saves having to build URL encoded strings), eg
$.ajax({
type: 'POST',
dataType: 'json',
data: { service: service_name },
//etc
Update
As shirejedi mentioned, you should initialise $data as an array
$data = array();
while($rows = mysql_fetch_array($query)){
$data[] = $rows;
}

Related

Unable to send javascript variable to php file using ajax

I want to send a javascript variable to php file which shows the comments on a webpage.
I was able to send this js variable to some other php file, but I can't do it with this comment-list.php file. I guess there is some problem with JSON.
function listComment() {
$.ajax({
url: "Komentarji/comment-list.php",
data : {page_num: page_num},
type : 'post',
success : function(response) {
}
});
$.post("Komentarji/comment-list.php", function(data) {
var data = JSON.parse(data);
.
.
.
The function is called here:
$(document).ready(function() {
listComment();
});
Inside comment-list.php I try to get the variable that was sent with ajax. However it doesn't work and comment's aren't displayed on page. If I delete this line, the comments work again (but of course, I don't get the sent variable).
$num = $_POST['page_num'];
$sql = "SELECT * FROM tbl_comment ORDER BY parent_comment_id asc, comment_id asc";
$result = mysqli_query($conn, $sql);
$record_set = array();
while ($row = mysqli_fetch_assoc($result)) {
array_push($record_set, $row);
}
mysqli_free_result($result);
mysqli_close($conn);
echo json_encode($record_set);
Here is the javascript variable and included php file.
<script>
var page_num = 1;
</script>
<?php
include($_SERVER["DOCUMENT_ROOT"]."/index.php");
?>
I get this error in console: Uncaught SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse ()
As said eariler if I remove the line where I get the variable with post, this error disappears.
You shouldn't use $.ajax and $.post to do the same thing, pick one, I'd say remove the $.post one and dont forget to put an exit; statement after you echo the response to avoid PHP to process further code if existing, also worth mentionning but not necessary, you can put the dataType to json so dataType: 'json' in the $.ajax call, dataType is used to tell jQuery what to expect as a response type from the server, as you are echoing the response by encoding it in JSON, you won't need to parse the response on your JS side if you speficied the dataType beforehand.
$.ajax({
url: "Komentarji/comment-list.php",
data : {page_num: page_num},
type : 'post',
dataType: 'json',
success : function(response) {
console.log(response); //will show the result of echo json_encode($record_set); from your PHP
}
});
$num = $_POST['page_num'];
$sql = "SELECT * FROM tbl_comment ORDER BY parent_comment_id asc, comment_id asc";
$result = mysqli_query($conn, $sql);
$record_set = array();
while ($row = mysqli_fetch_assoc($result)) {
array_push($record_set, $row);
}
mysqli_free_result($result);
mysqli_close($conn);
echo json_encode($record_set);
exit; //exit statement here
Following discussion with OP who wanted to use the $.post method, this is how it is done, pass the data as an object to the second attribute (more infos here):
$.post("Komentarji/comment-list.php", {page_num: page_num});
Just make your format JSON in your JS script
$.ajax({
url : 'Komentarji/comment-list.php',
type: "POST",
data: page_num:page_num,
dataType: "JSON",
success: function(data)
{
console.log(data);
},
error: function (jqXHR, textStatus, errorThrown){
console.log(errorThrown);
}
});

Getting data from php using ajax not working

I am trying to make an Ajax request and get the data from a PHP file; that is, a single row based on a where condition. I don't know how to extract the PHP array in JavaScript.
My Ajax code:
function loadData(Sno)
{
$.ajax({ //create an ajax request to
type: "GET",
url: "php/getgreetings.php?loadsno=" + Sno,
dataType: "json", //expect html to be returned
success: function(data){
response = jQuery.parseJSON(data);
alert (response.Greet_Name);
}
});
}
My PHP code:
require('db.php');
$loadsno = $_GET['loadsno'];
$query = "SELECT * from Greetings where greetsno=".$loadsno ;
$result = sqlsrv_query($conn,$query);
$data = array();
while ($row = sqlsrv_fetch_array($result))
{
$data[] = $row;
}
echo (json_encode($data));

JSON Padding With PHP

Please can anyone assist I'm trying to get my JSON data displayed on my html5 localhost page,
I'm still new to JSON
I get the following returned but no data is loading on the page.
http://www.hostname/getCheck.php?callback?&callback=jQuery110205560797746881064_1392215061343&_=1392215061344
Please if anyone can assist.
Below is my php script
`mysql_select_db($database_xxx, $xxx);
$rsfet = "SELECT * FROM cs_tracking ";
$fet = mysql_query($rsfet, $xxx) or die(mysql_error());
$json = array();
while($r=mysql_fetch_array($fet)){
$json[] = $r;
}
header('Access-Control-Allow-Origin: *');
echo $callback ='('.json_encode($json).')';`
and my javascript to display the table data
`
$(document).ready(function(){
$.ajax({
url: 'http://xxxxxxxxxxx.com/getCheck.php?callback=?',
type: 'GET',
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
jsonp: true,
success: function(data){
$.each(data,function(i,photo){
var tblRow =""
+""+data.CS_Track_Child+""
+""+data.CS_Track_Date+""
+""+data.Tracking_Status+""
+""+data.CS_Tracking_ID+""
+"" ;
$(tblRow).appendTo("#userdata tbody");
});
},
});
});`
The $callback variable is not magically declared in your script (at least, it shouldn't be); you can access the value via $_GET['callback'] but make sure to sanitize its value:
if (isset($_GET['callback']) && preg_match('/[A-Z]\w*/i', $_GET['callback']) {
header('Content-Type: application/javascript');
header('Access-Control-Allow-Origin: *');
printf('%s(%s);', $_GET['callback'], json_encode($json));
}
You have two GET parameter of callback one is valid but empty and second is invalid.
http://www.hostname/getCheck.php?callback?&callback=jQuery110205560797746881064_1392215061343&_=1392215061344
url: 'http://xxxxxxxxxxx.com/getCheck.php?callback=?',
So remove your parameter and try with this:
url: 'http://xxxxxxxxxxx.com/getCheck.php',

How to convert stringified data to an object?

My php has header('Content-type: application/json') and a json_encode.
The ajax code I use to send the data to the php file has dataType: 'json' and I am sending the data as a string (json.stringify).
The problem is, I can't make $_POST['data'] work on a string.
Any way to convert it to an object?
edit: What I am trying to achieve is, sending data from ajax to php where a query looks up the information from the database and the php file sends an array using JSON to the ajax and the ajax displays it.
Ajax:
function op_prof(obj) {
var xval = obj.id;
$.ajax({
type: "POST",
url: '../script/profile.php',
dataType: 'json',
data: JSON.stringify({'u_search':'xval'}),
cache: false,
success: function(data) {
console.log(data);
alert(data);
alert({u_search:xval}['u_search']);
$("#co_profile").html(data).show();
}
});
};
PHP:
<?php include(dirname(__FILE__). '/../script/config.php');
session_start();
$id = $_POST['u_search'];
foreach($pdo->query("SELECT * FROM Users WHERE ID='$id'") as $row) {
$fullname = $row['FullName'];
$data = array("u_data"=> true,"inpt"=>"<p>My name is " . $fullname . "</p>");
header('Content-type: application/json');
echo json_encode($data);
?>
<?php $pdo = null; ?>
I'd also like to know any other way of achieving this (even without using JSON)
Try json_decode("php://input");

Struggling to decode JSON in jquery ajax success callback from PHP script

I've been trying to find an answer for this for hours but really struggling.
I have a simple jquery Ajax function which sends data to a PHP script. The data is then used to conduct a MySQL query and the results are included as an array. I'm sending the array back using json_encode but can't work out how to display the array at the other end. I've posted the code below. The console.log is displaying Object {modules: Array[0]}
. There should be 3 entries in the array.
The PHP
<?php
include_once('../../dbconnect.php');
$name = $_POST['uploadname'];
$query = "SELECT * FROM marking_assignments WHERE name = '$name'";
$details = $conn->query($query);
$modules = array();
while ($row = $details->fetch_assoc()){
$modules[] = $row['unit'];
}
$dataarray = array("modules"=>$modules);
echo json_encode($dataarray);
?>
The jQuery
var uploadname;
$("#uploadname").blur(function(){
uploadname = $(this).val();
$.ajax({
url: "uploadnames.php",
type: "POST",
data: {uploadname: uploadname},
dataType: 'json',
success: function(data){
console.log(data);
}
});
});
you should use:
var parsedData = jQuery.parseJSON(data);
and then:
console.log(parsedData)

Categories