I have an AJAX Request, that essentially queries a database then posts the data back to the JS, however I can't print individual bits of data.
My code is as follows:
$.ajax({
type: 'POST',
url: '_process/offerrespres.php',
dataType: 'json',
data: {
msgid: msgid,
usrid: usrid
},
success: function(){
console.log(JSON.parse(data.pro_name));
console.log(data.accept_decline);
}
});
The PHP:
<?php
include_once 'connect.php';
if ($_POST) {
$msgid = mysql_escape_string($_POST['msgid']);
$usrid = mysql_escape_string($_POST['usrid']);
$getmsgq = mysql_query("SELECT * FROM booking_requests WHERE receiver_id = '$usrid' AND msg_id = '$msgid'");
$getmsg_info = mysql_fetch_array($getmsgq);
$data['success'] = true;
$data['date_sent'] = $getmsg_info['date_sent'];
$data['pro_name'] = $getmsg_info['pro_name'];
$data['accept_decline'] = $getmsg_info['accept_decline'];
}
header("Content-Type: application/json", true);
echo json_encode($data);
mysql_close();
?>
As you can see I've tried this:
console.log(JSON.parse(data.pro_name));
console.log(data.accept_decline);
the error in the console says "data not defined". The output from the PHP file is correct and how it should be, I just can't print one single piece of data.
Your callback function isn't accepting the return data as an argument
The line that reads success: function(){ should be success: function(data){
Also, the true isn't needed in your call to header("Content-Type: application/json", true);. The default action of this function is to replace headers, so true is already implied. That argument is only necessary if you don't want to replace the previous Content-Type. Makes no difference to your code, just a tip.
You didn't specify the data variable in the success function.
It should be:
success: function(data){
console.log(JSON.parse(data.pro_name));
console.log(data.accept_decline);
}
Related
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);
}
});
I have a PHP CODE:
if(isset($_POST['id'])){
$id = mysqli_real_escape_string($link,$_POST['id']);
$query = "SELECT * FROM `tb_cform` WHERE `ID`='$id'";
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_assoc($result)){
$message = '<div><h4>Subject: </h4><h5>'.$row['subj'].'<h5></div>';
$message .= '<hr><br>';
$message .= '<div><b>Message:<br>'.$row['message'].'</b></div>';
}
echo $message;
}
I need to pass the value from my AJAX code to the aforementioned code:
$('#messageModal').on('show', function(){
$.ajax({
type: "POST",
url: "viewmessage.php",
datatype: "html",
data:"data-id=" +id ,
success: function(r){
$('#messageBody').html( r );
}
});
});
The link that I am using is using a data-id="73" to pop open a model and populate the information.
My issue is, the value is not being passed and the body of the Modal is not being populated. Can anyone let me know why or what I did incorrect?
Check that your db returns something, so that $result is not null. Otherwise your $message will be empty.
If your query actually returns something and $message is still empty - try changing datatype to json:
JS
$.ajax({
type: 'POST',
url: 'php/server.php',
datatype: 'JSON',
data: {
dataId: someArbitraryId
},
success: function(data) {
var message = JSON.parse(data).message;
$('#message').html(message);
}
});
PHP
if (isset($_POST['dataId'])) {
$message = '';
// Some code
$result = array(
'message' => $message
);
echo json_encode($result);
}
Now even if the $message is empty or null - server should return array with empty string.
in js
data:{dataId : id}, // I'm sure this will work but data:"data-id=" +id, may work as well
in php
$_POST['dataId'] // instead of $_POST['id']
If this not work with you there are some steps you need to do
1- alert(r) on ajax success function and check for errors
2- I don't know what is id and where you get it from so try to alert(id) and see if it output an expected value or not
3- you may need to use shown.bs.modal instead of show take a look at here
4- in js try to get the a data-id by using $(a[data-target="#messageModal"]).data('id') instead of id
so your code should looks like
in js
$('#messageModal').on('shown.bs.modal', function(){
$.ajax({
type: "POST",
url: "viewmessage.php",
datatype: "html",
data:{ dataId : $(a[data-target="#messageModal"]).data('id')},
success: function(r){
$('#messageBody').html( r );
}
});
});
and also in php use $_POST['dataId'] instead of $_POST['id']
So i figured out the issue, it is now displaying the results, however, $(a[data-target="#messageModal"]).data('id'); will not pass the value, i had to use: var id = $("#messageID").attr("data-id");. This is working, but becuase there are multiple instances of #messageID listed, it is only showing the first result becuase you cannot have duplicate ID tags with the same information.
My question is how can i assign or get a value added after #messageID like an array using[ ] to assign a value and have it look for that then get the data-id value to pass?
I am using AJAX and trying to return variables that I got after querying the database in the modcomp.php file, I am then trying to input those values back into my main site to put into input boxes. Below is what I have tried but it is not working. Is this because I am getting variables in PHP and then bringing them back to use in JS / jQuery? Doing a few searches it looks like JSON might be the answer but looking at JSON I havent seen an example of how I could run code to query the database and then put that info in JSON format to pull back? My goal is to eventually pull back all 10 variables.
$.ajax({
method: "POST",
url: "modcomp.php",
data: {item: $(this).val()}
success: function(data) {
$('#itemnumber').val($itemnumber);
$('#cost').val($cost);
}
});
The modcomp.php file
<?php
if(array_key_exists("item", $_POST)) {
include("connection.php");
$query="SELECT * FROM components WHERE itemname = '".mysqli_real_escape_string($link,$_POST['item'])."' LIMIT 1";
if ($result=mysqli_query($link,$query)) {
$row=mysqli_fetch_array($result);
$id=$row[0];
$itemnumber=$row[1];
$itemname=$row[2];
$cost=$row[3];
$company=$row[4];
$contact=$row[5];
$address1=$row[6];
$address2=$row[7];
$phone=$row[8];
$part=$row[9];
//print_r ($id." ".$itemnumber." ".$itemname." ".$cost." ".$company." ".$contact." ".$address1." ".$address2." ".$phone." ".$part);
} else {
print_r("Issue with query");
}
}
?>
The easiest way to do that is just set your jquery.ajax to expect a json as return:
$.ajax({
method: "POST",
dataType: "JSON",
/** others attributes **/
After, convert your return to a json and print it (just it, nothing more) at php script:
//a better approach is return the column name (fetch_assoc)
echo json_encode($row);
Now, your return can be used as json:
success: function(data) {
data.column_name
}
json_encode is the answer
<?php
if(array_key_exists("item", $_POST)) {
include("connection.php");
$query="SELECT * FROM components WHERE itemname = '".mysqli_real_escape_string($link,$_POST['item'])."' LIMIT 1";
if ($result=mysqli_query($link,$query)) {
$row=mysqli_fetch_array($result);
$array = ();
$array['id']=$row[0];
$array['itemnumber']=$row[1];
$array['itemname']=$row[2];
.
.
$array['part']=$row[9];
$array['status'] = true;
echo json_encode($array);
} else {
echo json_encode(array(status => false , msg => "Issue with query");
}
}
Then in your js code use json as
$.ajax({
method: "POST",
url: "modcomp.php",
data: {item: $(this).val()}
success: function(data) {
data = JSON.parse(data); // to parse json string to object
if(data.status){
$('#itemnumber').val(data.itemnumber);
$('#cost').val(data.cost);
}
}
});
you should return your value from your php file as
<?php
if(array_key_exists("item", $_POST)) {
include("connection.php");
$query="SELECT * FROM components WHERE itemname = '".mysqli_real_escape_string($link,$_POST['item'])."' LIMIT 1";
if ($result=mysqli_query($link,$query)) {
$row=mysqli_fetch_array($result);
return json_encode($row,true);
} else {
return json_encode("Some error occured");
}
}
don't use print_r() function to return data from your php file
And set the datatype in ajax as JSON to parse the json data to be returned as
$.ajax({
method: "POST",
url: "modcomp.php",
datatype:'json',
data: {item: $(this).val()}
success: function(data) {
$('#itemnumber').val(data.itemnumber);
$('#cost').val(data.cost);
}
});
Now you are able to use your json data using the dot(.) operator like
$('#cost').val(data.cost);
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',
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");