fetch rows from mysql using Ajax - javascript

I am trying to retrieve a row from mysql db using ajax, code bellow:
jQuery.ajax({
type: 'POST',
url: 'Connection.php',
dataType: 'text',
data: {'query_id' : query_id},
success: function(response){
data = response;
alert(data['username']); //print undefined!!!
},
error: function(xhr, ajaxOptions, thrownError){
alert("thrownError");
}
});
Here is my mysql php code:
<?php
$con = mysql_connect('****','****','****');
mysql_select_db("eBay",$con);
$username = $_SESSION['username'];
$query_id = $_POST['query_id'];
$myquery = "SELECT * FROM `Output` WHERE `username` =" '$username';
$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
}
$data = mysql_fetch_array($query);
echo ($data);
mysql_close($server);
?>
In the response I get, I have undefined array cell. Any idea?

to return just the username from php:
$data = mysql_fetch_assoc($query)['username'];
in your javascript you should be able to do alert(data) instead of searching for the username tuple in an array.
Ideally you should return your data back in json instead of text that way it can remain structured and easier to access in javascript. You will need to change your ajax option to dataType: 'json'
and the PHP code to :
$data = json_encode(mysql_fetch_assoc($query));

You are getting array in $data variable so you should use json_encode function to get all values from resulting row like this-
$myquery = "SELECT * FROM `Output` WHERE `username` ='".$username."'";
foreach ($myquery as $test)
{
$field1_value =$test->name_of_field1_in_db;
$field2_value =$test->name_of_field2_in_db;
$field3_value =$test->name_of_field3_in_db;
}
$all_values_in_array=array('field1'=>$field1_value,'field2'=>$field2_value,'field3'=>$field3_value,);
echo json_encode(echo json_encode($arr_provider);
and get all value on ajax suucess function like this--
success: function(response){
var pro = jQuery.parseJSON(response);
var field1_val=pro.field1; //var field1 contain value of field1 in db
var field2_val=pro.field2;
var field3_val=pro.field3;
},
hope it will help you.
Best of Luck

Related

Ajax call to php, get mysql data as array and use in JS function

I'm looking to make an ajax call to a PHP script to get data from MySQL, create a json array and pass it back to the success function of the ajax call, where i will then use it as parameters for a JavaScript function.
This is my ajax call,
$('button[name="message"]').click(function() {
var $row = $(this).closest("tr"); // Find the row
var $tenant_id = $row.find(".col-md-1 id").text(); // Find the tenants ID
var $landlord_id = "<?php echo $id; ?>"
$.ajax({
url : "./message.php",
type : "POST",
async : false,
data: {
landlord_id: $landlord_id,
tenant_id : $tenant_id
},
success: function(data){
console.log(data);
var messages = data;
insertChat(messages.sender_id, messages.body, messages.timestamp);
}
})
});
And this is my PHP file,
<?php
session_start();
require_once('../dbconnect.php');
// update tenants table to show deposit returned
if(isset($_POST['tenant_id'])){
$tenant_id = $_POST['tenant_id'];
$landlord_id = $_POST['landlord_id'];
$sql = "SELECT * from messages WHERE messages.sender_id OR messages.receiver_id = '$tenant_id' AND messages.sender_id OR messages.receiver_id = '$landlord_id'";
$result = mysqli_query($conn, $sql) or die("Error in Selecting " . mysqli_error($conn));
//create an array
$messages = array();
while($row =mysqli_fetch_assoc($result))
{
$messages[] = $row;
}
echo json_encode($messages);
}
?>
If anybody has a link to a tutorial or the individual parts that would be fantastic. I don't even know if the process i have outlined above is correct.
If anybody could tell me the correct way to go about this that would be of great help!
Thanks
Just a few things to adjust your javascript side (I won't explain the php sql injection issue you have... but please research prepare, bind_param and execute):
Since you are returning an ARRAY of $messages from php (json_encoded), you need to loop on those in your success handler.
Add dataType: 'JSON' to your options, so it explicitly expects json returned from php.
And you were missing a couple semicolons ;)
Adjustments added to your code:
$('button[name="message"]').click(function() {
var $row = $(this).closest("tr");
var tenant_id = $row.find(".col-md-1 id").text();
var landlord_id = "<?php echo $id; ?>";
$.ajax({
url : "./message.php",
type : "POST",
data: {
landlord_id: landlord_id,
tenant_id : tenant_id
},
dataType: 'JSON',
success: function(data){
console.log(data);
if (typeof data !== undefined) {
for(var i = 0; i < data.length; i++) {
insertChat(data[i].sender_id, data[i].body, data[i].timestamp);
}
}
}
});
});

How to split the row from mysql db passed through json_encode to display in separate textboxes

I trying to split the result from a mysql statement output from one php page to another page containing javascript.
I tried below method but something is missing in my code :-(
The result I am looking forward is to get the values in each column from the selected row in mySQL table to populate into #eventTitle, #eventDescription and so on....
Please find my code below
lookup_event.php
<?php
$eid = $_POST['eid']
include '/include/db_connect.php';
$sql="SELECT title, description, start, end FROM evenement where id=".$eid;
$result = $mysqli->query($sql);
while ($row = mysqli_fetch_assoc($result)) {
$sessions[] = $row;
}
echo json_encode($sessions);
die();
?>
script in cal.php
eid = event.id;
$.ajax({
type: 'POST',
url: 'lookup_event.php',
data: eid,
success: function (sessions) {
$('#eventTitle').val(sessions["title"]);
$('#eventDescription').val(sessions["description"]);
}
});
Its coming as a string because its json. You first need to parse it.
script in cal.php
eid = event.id;
$.ajax({
type: 'POST',
url: 'lookup_event.php',
data: eid,
success: function (sessions) {
var sessions = JSON.parse(sessions);
$('#eventTitle').val(sessions["title"];
$('#eventDescription').val(sessions["description"];
}
});
I recommend you to start using PDO: http://php.net/pdo
And statement+binds to automatically escape SQL injections.
<?php
// ... include PDO connection ($conn)
$eid = (int) $_POST['eid'];
$sql = "SELECT title, description, start, end FROM evenement WHERE id = :id";
$stmt = $conn->prepare($sql);
$stmt->bindParam('id', $eid);
$stmt->execute();
$result = $stmt->fetchAll();
echo json_encode($result);
Javascript:
$.ajax({
type: 'POST',
url: 'lookup_event.php',
data: { eid: eid },
dataType: 'json',
success: function (event) {
// with dataType specified dont need parse
}
});
Finally fixed the issue. Thanks everyone for your support.
This is how now my files look like. However your comments for any modifications on below code are most welcome. Thanks once again.
lookup_event.php
<?php
include '/include/db_connect.php';
$eid = $_POST['eid'];
$sql = "SELECT title, description, start, end FROM evenement where id=" . intval($eid);
$result = $mysqli->query($sql);
if ($result) {
$array = mysqli_fetch_array($result);
}
echo json_encode($array);
die();
?>
cal.php
eid = event.id;
$.ajax({
type: 'POST',
url: 'lookup_event.php',
data: {eid:eid},
success: function (event) {
var event = JSON.parse(event);
$('#eventTitle').val(event.title);
$('#eventStart').val(moment(event.start).format('YYYY-MM-DD, HH:mm:ss'));
$('#eventEnd').val(moment(event.end).format('YYYY-MM-DD, HH:mm:ss'));
$('#eventDescription').val(event.description);
$('#myModal').modal();
}
});

Pass a variabile from php to js via JSON

At the lessons i learn how to pass result from a sql request to js via JSON/AJAX. I need the value of the row from this request in my js but it doesnt work. Via console i have an error: Uncaught SyntaxError: Unexpected token <
part of PHP:
<?php
//get all the course from db and reply using json structure
//connection to db
$mysqli = new mysqli("localhost", "root", "", "my_hyp");
$id = $_POST['id'];
if (mysqli_connect_errno()) { //verify connection
exit(); //do nothing else
}
else {
# extract results mysqli_result::fetch_array
$query = " SELECT * FROM course WHERE course_category='$id'";
//query execution
$result = $mysqli->query($query);
//if there are data available
if($result->num_rows >0)
{
$myArray = array();//create an array
while($row = $result->fetch_array(MYSQL_ASSOC)) {
$myArray[] = array_map('utf8_encode', $row);
}
$response = array();
$response['rows'] = $row;
$response['query'] = $myArray;
echo json_encode($response);
}
//free result
$a=num_rows;
$result,$a->close();
//close connection
$mysqli->close();
}
?>
first part of Script:
$.ajax({
method: "POST",
//dataType: "json", //type of data
crossDomain: true, //localhost purposes
url: "./query/cate_has_courses.php", //Relative or absolute path to file.php file
data: {id: i},
success: function(response) {
console.log(JSON.parse(response));
var course=JSON.parse(response.query);
var row=JSON.parse(response.rows);
Seem you use JSON.parse in wrong way.
The JSON.parse must be done one time only. The result of JSON.parse is store in course the the access to the data is due by response.query or respons.row .. and so on and not by JSON.parse(respose.query)

How to get the "data" fromphp array in ajax

My code in ajax.
$.ajax({
type: 'post',
url: 'url.php',
dataType: 'JSON',
success: function(data)
{
id = // I want to get the ID data
}
});
In my (data) there's already a different data in it one of that data is the ID. What I want to do is get the ID data and save it to a variable.
Here's my PHP :
$comments = array();
$get = "Some query";
$result = $connection->query($get);
while($row = mysqli_fetch_array($result))
{
$comments[] = $row;
}
echo json_encode($comments);
The parameter "data" will be the response printed by url.php script. It depends on how you are printing the information from PHP script.
If you print it as a json like {'id': 'some_id'}, then the "id" var can be fetched using data.id on your script.
But if you are just printing text, then "data" parameter will be the printed characters from url.php.
To help you more, you can post what you have inside url.php script.
Well, you're expecting the response to be a json object, since you set dataType to 'JSON'. So for example if your php script returns something like that:
<?php $result['data'] = $yourdata; $result['id'] =$id; echo json_encode($result); ?>
Then you can use the result on the client side like this:
success: function(result)
{
id = result.id;
data = result.data;
}

get return value from php for ajax call

I am trying to get the auto increment id from a database insert in php back to my javascript ajax call:
My ajax call looks like this:
//get values
var note = $('#note1').val();
alert(userID);
alert(beerID);
var ajaxSettings = {
type: "POST",
url: "atn.php",
data: {u:userID , b:beerID ,n:note},
success: function(data){
alert(data);
} ,
error: function(xhr, status, error) { alert("error: " + error); }
};
$.ajax(ajaxSettings);
return false;
and my php script looks like this:
<?php
error_log("starting code");
require_once('myConnectDB.inc.php');
$u = $_POST['u'];
$b = $_POST['b'];
$n = $_POST['n'];
//do some checks etc
$db = new myConnectDB();
$u = $db->real_escape_string($u);
$n = $db->real_escape_string($n);
$b = $db->real_escape_string($b);
$query3 = "INSERT INTO tn (userID,beerID,note) VALUES ($u, '$b', '$n')";
$result = $db->query($query3);
$dbID = mysql_insert_id();
echo $dbID;
?>
the $dbID that I am trying to send back is not getting alerted after the php script runs. I am getting this error in my alert:
<br />
<b>Warning</b>: mysql_insert_id() [<a href='function.mysql-insert-id'>function.mysql-insert-id</a>]: A link to the server could not be established in <b>/home4/m133414/public_html/atn.php</b> on line <b>23</b><br />
Replace your following line:
$dbID = mysql_insert_id();
for this one:
$dbID = $db->insert_id;
As you were incorrectly using the procedural version of mysql_insert_id() while you were otherwise using the object oriented version, so to be consistent we use the OOP version here too.

Categories