returning variables from AJAX / php file - php

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

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

Return php array to ajax not working

I am running a query to database which fetch a row and i want to return it as array which can accessed as array['min'], array['max'] etc. if i echo it with specific index, it shows the value correctly in ajax but i am unable to pass complete row through it to the ajax file.
PHP file:
<?php
// Database logic here
$calid = reset($_POST);
require '../incs/connect.php';
$sql=mysqli_query($con, "SELECT * FROM calcus_sets WHERE sets_id=$calid ");
WHILE($row=mysqli_fetch_array($sql))
{
echo $row['min']; break;
}
mysqli_close($con);
?>
JS file:
function DB_Fetecher(ops){
$.ajax({
type: "POST",
data: {ops},
url: "calcus_es1-fetcher.php",
success: function(res)
{
// alert( res );
alert(res);
}
});
}
This code get right value from mysql but i want to pass full row to ajax and then use each index in ajax itself to put into textboxes.
You can pass array by:
<?php
// Database logic here
$calid = reset($_POST);
require '../incs/connect.php';
$sql=mysqli_query($con, "SELECT * FROM calcus_sets WHERE sets_id=$calid ");
$result = array();
WHILE($row=mysqli_fetch_array($sql))
{
$result[] = array( "min" => $row['min'], "max" => $row['max'] );
}
mysqli_close($con);
echo json_encode( $result );
?>
On your js, make sure to specify dataType:"json",
function DB_Fetecher(ops){
$.ajax({
type: "POST",
data: {ops},
url: "calcus_es1-fetcher.php",
dataType:"json",
success: function(res)
{
// alert( res );
console.log(res);
}
});
}
Note: It is advisable to use console.log(res); instead of alert() on debugging.

How to understand and retrieve multiple values from a php script through jquery $.ajax function?

While using jquery $.ajax or $.post, to submit a value (say uid {user id}) how can I define a callback function to retrieve multiple values from the php script and retrieve values from my mysql table say(user details, corresponding to the uid) and store them in vars, using the default datatype:datatype???
Can anyone please show me both the jquery and php scripts please. And yes the database is runninga mySQL 5.5.24 and PHP version is 5.3
instead of using $.ajax you can also use this...
var id=$("#id").val();
$.getJSON('script.php', {id:id}, function(json) {
var id=json.id;
var name=json.name;
var email=json.email;
});
}
in your php scrip..
<?php
mysql_connect($host,$dbuser,$dbpass);
mysql_select_db($db_name);
$id=$_GET['id'];
$query="select * from tbl_name where id='$id'";
$rs=mysql_query($query);
$row=mysql_fetch_assoc($rs);
$id=$row['id'];
$name=$row['name'];
$email=$row['email'];
$data=array("id"=>$id,"name"=>$name,"email"=>$email);
echo json_encode($data);
?>
The best way to do this would be to send it back to javascript as a json object.... so for your user example
// assuming post containing a username, using pseudo code for db access
$row = $db->fetchAssoc("select * from users where username = '".dbEscape($_POST["username"]."'");
header("Content Type: application/json");
echo json_encode($row);
ajax code will be like follows
$.ajax({
type: "POST",
url: "your_page.php",
data: { param1: "val1", param2: "val2" }
}).done(function( data) {
// do your callback operation
});
get values from your_page.php like below
$_POST["param1"] , $_POST["param2"]
if you want to know more then click here
I think this will solve your problem.
<script type="text/javascript">
$.ajax({ // ajax call starts
url: 'serverside.php', // JQuery loads serverside.php
data: 'button=' + $(this).val(), // Send value of the clicked button
dataType: 'json', // Choosing a JSON datatype
success: function(data) // Variable data contains the data we get from serverside
{
}
});
</script>
dataType: json..so jason will return multiple values. from you php script
echo json_encode($array_of_val);
$.ajax({
type: "POST",
dataType:"html",
url: "ajax_page.php",
data:"params1="$params1"&params2="+$params2,
}).done(function(value) {
// write your callback operation
});
you can get your data on ajax_page.php using an post method like
$_POST['params1'];
and
$_POST['params2'];
$query= select statement
$items=array();
while ($row = mysql_fetch_object($rs)) {
array_push($items, $row);
}
$result["rows"] = $items;
echo json_encode($result);

How to correctly select and show (or insert) data from (in) MySQL database with AJAX call to PHP function?

So far I have something like this:
//HTML
<body onload=getRoomTemp();>
//JS
function getRoomTemp() {
$.ajax({
type: "POST",
url: "getRoomTemp.php",
datatype: "text";
data: {
temp: temp
}
}).done(function () { $('#getRoomTemp').append(text); });
}
//PHP
<?php
if (isset($_POST['temp'])) {
require('database.php');
$query = ("SELECT temp FROM tempWHERE tempID=1");
$res = mysql_query($query) or die("ERROR ".__LINE__.": ".mysql_error());
while ($ar = mysql_fetch_array($res)) {
$temperatureIn = $ar['temp'];
echo $temperatureIn;
}
}
?>
So, when my HTML body loads, I would like to make query and show query result in div called "getRoomTemp" with AJAX. Later, I will need the same technique to insert data in MySQL (single number value) on button click.
I can't find the problem with my current code, tried different dataType for ajax but no success. Please help..
You have 2 undefined identifiers temp and text, try
function getRoomTemp() {
$.ajax({
type: "POST",
url: "getRoomTemp.php",
dataType: "text",
data: {
temp: 'temp'
}
}).done(function (text) { $('#getRoomTemp').append(text); });
}

Retrieve JSON Data with AJAX

Im trying to retrieve some data from JSON object which holds location information such as streetname, postcode etc. But nothing is being retrieved when i try and put it in my div. Can anybody see where im going wrong with this?
This is my ajax code to request and retrieve the data
var criterion = document.getElementById("address").value;
$.ajax({
url: 'process.php',
type: 'GET',
data: 'address='+ criterion,
success: function(data)
{
$('#txtHint').html(data);
$.each(data, function(i,value)
{
var str = "Postcode: ";
str += value.postcode;
$('#txtHint').html(str);
});
//alert("Postcode: " + data.postcode);
},
error: function(e)
{
//called when there is an error
console.log(e.message);
alert("error");
}
});
When this is run in the broswer is just says "Postcode: undefined".
This is the php code to select the data from the database.
$sql="SELECT * FROM carparktest WHERE postcode LIKE '".$search."%'";
$result = mysql_query($sql);
while($r = mysql_fetch_assoc($result)) $rows[] = $r;
echo json_encode($rows), "\n"; //Puts each row onto a new line in the json data
You are missing the data type:
$.ajax({
dataType: 'json'
})
You can use also the $.getJSON
EDIT: example of JSON
$.getJSON('process.php', { address: criterion } function(data) {
//do what you need with the data
alert(data);
}).error(function() { alert("error"); });
Just look at what your code is doing.
First, put the data directly into the #txtHint box.
Then, for each data element, create the string "Postcode: "+value.postcode (without even checking if value.postcode exists - it probably doesn't) and overwrite the html in #txtHint with it.
End result: the script is doing exactly what you told it to do.
Remove that loop thing, and see what you get.
Does your JSON data represent multiple rows containing the same object structure? Please alert the data object in your success function and post it so we can help you debug it.
Use the
dataType: 'json'
param in your ajax call
or use $.getJSON() Which will automatically convert JSON data into a JS object.
You can also convert the JSON response into JS object yourself using $.parseJSON() inside success callback like this
data = $.parseJSON(data);
This works for me on your site:
function showCarPark(){
var criterion = $('#address').val();
// Assuming this does something, it's yours ;)
codeAddress(criterion);
$.ajax({
url: 'process.php',
type: 'GET',
dataType: 'json',
data: {
address: criterion
},
success: function(data)
{
$("#txtHint").html("");
$.each(data, function(k,v)
{
$("#txtHint").append("Postcode: " + v.postcode + "<br/>");
});
},
error: function(e)
{
alert(e.message);
}
});
}

Categories