Unable to send javascript variable to php file using ajax - php

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

Related

Ajax call by button PHP form with id++, how to count max value?

There is some way to return value from PHP in to ajax? Or some other way?
simple jQuery call:
$(document).ready(function(){
var quizCount= 1;
$("button").click(function(){
quizCount = quizCount+1;
$("#quiz").load("load-quiz.php",{
quizNewCount : quizCount
});
});
});
PHP form:
$quizNewCount = $_POST['quizNewCount'];
$sql= "SELECT* FROM quiz WHERE quizid =$quizNewCount";
$result = $conn->query($sql);
mysqli_set_charset($conn,"utf8");
if ($result->num_rows > $quizNewCount)
{
return $quizNewCount=1;
}
I try that, but without effect. Anyone know how to do that? I don't wont number, but changing value because database will be increased every month.
Use ajax instead of load. Here is an example code. Use GET instead of POST. Explanation here.
$.ajax({
type: 'GET',
url: 'load-quiz.php',
data: {quizNewCount : quizCount},
success: function (result) {
console.log(result);
}
});
// Ajax calling
post_data = {quizNewCount : quizCount}
$.ajax({
method: 'post',
dataType: 'json',
data: post_data,
url: 'load-quiz.php',
success: function (data) {
result = data;
alert(result)
}
})
// action part or processing part
$quizNewCount = $_POST['quizNewCount'];
$sql= "SELECT* FROM quiz WHERE quizid =$quizNewCount";
$result = $conn->query($sql);
mysqli_set_charset($conn,"utf8");
if ($result->num_rows > $quizNewCount) {
$quizNewCount=1;
//as dataType is json so we need to enocde the data in the json format before sending it
echo json_encode($quizNewCount);
}

returning variables from AJAX / php file

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

.ajax() not responding after keyup event

This is a jquery/ajax problem. The jquery/ajax is responding to keyup event with the alert(loc) showing the result of the value inputted into the number textbox.
The essense of the program is to get data from the database which is in an array form after encoding with json via php and display the result inside the textbox.
However, reaching the .ajax function, it does not display anything inside the success section. At the end, there is no response or any error. Used JSONLINT to see if there is any error, it gave a code i dont understand.
Afte using mozilla firebug to step through jquery, it still did not show any message.
This are my html,php,jquery codes for verification.
JS:
$(document).ready(function() {
$('#number').keyup(function() { //keyup event responds
var loc = $('#number').val();
alert(loc); //display result from the number textbox
$.ajax({ //skips ajax function
dataType: "json"
url: "/php/barry.php",
data: ({loc : loc}),
async: false,
type: "GET",
contentType: "application/json; charset=utf-8
success: function(data) {
$.each(data.result, function()
{
$("#number").append(this['number']);// its suppose to display
$("#name").append(this['name']);
});
}
});
});
});
PHP:
<?php
include_once('/db.php');
if(isset($_GET['loc'])){
$foo = $_GET['loc'];
$sql = "SELECT * FROM freak where number='$foo'";
$res = mysql_query($sql);
$result = array();
while( $row = mysql_fetch_array($res) )
array_push($result, array('number' => $row[0],
'name'=> $row[1];
//print_r($result);
echo json_encode(array("result" => $result));
}
?>

JSON/PHP not parsing correctly

Firstly i'll point out the problem, basically inside my $.each(data, function (i, v) { code it's returning a bunch of variables which are echo'd from the PHP code which is using json_encode but when trying to place these variables or even alert() them it's showing undefined i've tried many ways to actually display the data, but it's always returning undefined and i don't know why since my code seems valid to my perspective.
The current javascript code i have is as follows
$.ajax({
url: "functions/ajax.php",
data: "func=auto",
type: "GET",
dataType: "json",
success: function(data){
$.each(data, function (i, v) {
var name = v['name'];
var player_id = v['id'];
alert(player_id);
});
},
error: function (jqXHR, textStatus, errorThrown){
console.log('Error ' + jqXHR);
}
});
The current PHP code i have is as follows
$res = $DB->Query("SELECT * FROM `inventory` WHERE `account_id` = '$_SESSION[ID]'");
$data = array();
while($player = $DB->fetch_assoc()) {
$data['name'] = $player['name'];
$data['id'] = $player['player_id'];
}
header('Content-type: application/json');
echo json_encode($data);
Just to sum the whole thing up, when using alert() on player_id it returns undefined in which obviously i want it to return the correct value
You're not sending back a multi-level array, you're sending an array with just two elements. e.g. your JS code should be
success: function(data){
var name = data['name'];
var player_id = data['id'];
}
If that DB query IS supposed to send back multiple records, then you're building it wrong:
while($player = $DB->fetch_assoc()) {
$data[] = array('name' => $player['name'], 'id' => $player['player_id']);
}
echo json_encode($data);
and then your $.each() code should start working, as you ARE sending back a multidimensional array/object.

jQuery success function not executing

the first success function works, the second doesnt... it works if I change datatype to text... but if i change datatype to text am not able to iterate through the array .. for example i require data[0].. which works with json....but with json success function is not working ...
var turl = "getForum.php";
var turl = "getForum.php";
var wurl = "getDiscussions.php";
$.ajax({
url:turl,
type:"POST",
dataType:"json",
success:function(data){
forumid = data[0]; // this works ...
dataString = 'forumid='+ forumid;
$.ajax({
url:wurl,
type:"POST",
dataType:"json",
data:dataString,
success:function(data){
alert(data); // this works if I change datatype to text... but if i type datatype to text am not able to iterate through the array .. for example i require data[0].. which works with json....but with json success function is not working ...
}
});
}
});
php file return json object
$query1 = " select * from discussforum where forumId= '$forumid'; ";
$result1 = mysql_query($query1);
while($info1 = mysql_fetch_array( $result1 )){
echo json_encode($info1);
}
Are you sure about your PHP is returning only one JSON object? If not:
$ret = array();
while($info1 = mysql_fetch_array( $result1 )){
$ret[] = $info1;
}
print json_encode($ret);
I think the solution is delineated in the comments, but here it goes in a bit more detail. First take a look at the fine documentation for jQuery.ajax(). You need to add an error callback to all your Ajax calls. with the following signature:
error(jqXHR, textStatus, errorThrown)
You can just add a parameter to .ajax() like this:
error: function(jqXHR, textStatus, errorThrown) {
console.error(textStatus);
},
This way you will see in the console every error that happens during the Ajax call and also during the processing of the message. You can define a generic ajaxError callback in some common .js file and use it everywhere.
In this case you are explaining very well the cause of the error: what getDiscussions.phpis returning is not a JSON, and thus the jQuery parser cannot understand it when you set dataType:"json": it would call the error callback if there was one. It works however when the dataType is set to text. So the POST request is probably failing.
To see what it is sending you can just extract it in the error callback, like this:
error: function(jqXHR, textStatus, errorThrown) {
console.error('Error in response: ' + jqXHR.responseText
},
so you can diagnose the problem in the server.

Categories