I have an AJAX request and if get id succeeds I would like to alert the data.
If I print_r my PHP function I get the correct result.
My ajax:
$.ajax({
type: "GET",
url: "getQuestions.php",
datatype: "json",
data:{
compid: id[4].innerHTML
},
success: function(response){
alert(response);
}
});
My getQuestions.php:
<?php
include "functions.php";
getQuestions($_GET['compid']);
My function getQuestions($compid) in functions.php:
function getQuestions($compid){
$int=intval($compid);
$vastus=array();
$conn = dbconnect();
$sql="SELECT * FROM bet_question WHERE compid = $int";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
array_push($vastus,$row);
}
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
return json_encode($vastus);
}
If I do print_r(getQuestions("some valid id")) in getQuestion.php I get valid result and if I do var_dump($_GET['compid']) in getQuestion I'll get the correct id from ajax request.
If I check if the request is sent using inspect elements I get that request is sent with correct params, but the response is empty.
Instead of return you need to use echo and it should be updated as
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
array_push($vastus,$row);
}
echo json_encode($vastus);
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
exit;
You don't have to return the data, use echo instead, and set content type:
function getQuestions( $compid ) {
$int=intval($compid);
$vastus=array();
$conn = dbconnect();
$sql="SELECT * FROM bet_question WHERE compid = $int";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
array_push($vastus,$row);
}
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
#header( 'Content-Type: application/json' );
echo json_encode( $vastus );
exit;
}
Hope it helps
Related
I have the following php code (in a file returndata.php) to retrieve messages for a user:
$sql = 'SELECT * FROM usertimes WHERE receiver ="'. $messagesforaccount. '"';
$result = $conn->query($sql);
$response = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$response['message'] = $row["message"];
$response['date'] = $row["date"];
$response['sender'] = $row["sender"];
$response['receiver'] = $row["receiver"];
}
echo json_encode($response);
} else {
echo " 0 results";
}
Then the javascript is as follows (displays the message and some information on it such as the sender, date etc. on the webpage):
$.post(
"returndata.php",
{ messagesforaccount: userAccount },
function(response) {
var sender = response.sender;
var receiver = response.receiver;
var message = response.message;
var date = response.date;
console.log('Retreived data: ', sender, receiver, message, date);
p = document.createElement('p')
p.innerHTML = message + '<br>' + 'sent by ' + sender + ' at ' + date
listmessages.appendChild(p)
}, 'json'
);
This only adds one message to the page (the last one in the database). What should the php be so it loops through all results, and for each result it adds the message to the webpage?
You did a little bit mistake there. If you want associative array for multiple data then you should have a two dimensional array and you must have an index for second dimensional array as well
<?php
$sql = 'SELECT * FROM usertimes WHERE receiver ="'. $messagesforaccount. '"';
$result = $conn->query($sql);
$response = array();
$index = 0;
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$response[$index]['message'] = $row["message"];
$response[$index]['date'] = $row["date"];
$response[$index]['sender'] = $row["sender"];
$response[$index]['receiver'] = $row["receiver"];
$index++;//incrementing index variable
}
echo json_encode($response);
} else {
echo " 0 results";
}
?>
In return you can iterate that array in this way
for ($i=0;$i<count($response);$i++)
{
echo $response[$i]['message'] . "<br>" ;
echo $response[$i]['date'] . "<br>" ;
echo $response[$i]['sender'] . "<br>" ;
echo $response[$i]['receiver'] . "<br>" ;
}
You need to respond with all of them in an array like this:
$sql = 'SELECT `message`, `date`, `sender`, `receiver` FROM `usertimes` WHERE `receiver` ="'. $messagesforaccount. '"';
You should only request the fields you need. This improves performances and reduces overhead. Later, you can just push the whole row to the response.
$result = $conn->query($sql);
$response = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$response[] = $row;
}
echo json_encode($response);
} else {
echo " 0 results";
}
I have 2 files, A .js and a .php. The .php connects to the MySQL DB and the .js is the front end of the system.
I'm in the middle of trying to set it up so it sends a hash key to the ajax which returns the correct data for the related person from the database.
So far it does work as it send the hash from the URL to the PHP file and returns back the data in the console log.
//AJAX Function
//Grabs Varibles from PHP
var hash = window.location.hash.substr(1);
$(function() {
$('.hashfield').text(hash)
});
$.ajax({
type: "POST",
async: false,
cache: false,
url: "SelectFromSQL.php",
//Sending URL password
data:{ hash: hash, WorkingHash : "yes" },
success: function(data){
//Return of AJAX Data
console.log(data);
},
error:function() {
console.log("FAIL");
}
})
This is within the .js file which sends the hash
<?php
if(isset($_REQUEST['WorkingHash'])){
$hash = $_POST['hash'];
function IDHASH($hash){
echo $hash;
}
IDHASH($hash);
}
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT ID, CustomerName, ContactName, Address, City, PostalCode, Country FROM customers WHERE ID=$hash";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["ID"] . "<br>";
echo $row["CustomerName"] . "<br>";
echo $row["ContactName"] . "<br>";
echo $row["Address"] . "<br>";
echo $row["City"] . "<br>";
echo $row["PostalCode"] . "<br>";
echo $row["Country"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
This is the .php file. I need to return the data from the database related to the correct customer ID.
All the data being echoed from the while loop will need it's own variably within a js format
My Goal is to retrieve each entry from the database
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["ID"] . "<br>";
echo $row["CustomerName"] . "<br>";
echo $row["ContactName"] . "<br>";
echo $row["Address"] . "<br>";
echo $row["City"] . "<br>";
echo $row["PostalCode"] . "<br>";
echo $row["Country"] . "<br>";
}
}
instead use
if ($result->num_rows > 0) {
// output data of each row
$row = $result->fetch_assoc();
print_r(json_encode($row));
}
and in js
javacript
$.ajax({
type: "POST",
async: false,
cache: false,
url: "SelectFromSQL.php",
//Sending URL password
data:{ hash: hash, WorkingHash : "yes" },
success: function(data){
//Return of AJAX Data
data = JSON.parse(data);
console.log(data);
//YOU CAN USE data.ID , data.CustomerName and so on
},
error:function() {
console.log("FAIL");
}
})
How about something like this:
Edit
instead of return data echo it like this:
if ($result->num_rows > 0) {
// echo the data instead of return
echo json_encode($result->fetch_assoc());
}
To access the properties of the object you can in your success function do that :
success: function(data){
// parse your data first
data = JSON.parse(data);
//Return of AJAX Data
console.log(data.CustomerName);
console.log(data.ContactName);
// you can assign them to a variables if you want
var customerName = data.CustomerName;
var ccontactName = data.CustomerName;
}
On my website, I'm using ajax to send data to an external php script, which queries a database and returns the result to the website. I ran into the problem, that I can only return strings with php, but I want to return an array of objects (which is valid json). My code looks like this at the moment:
php
$connection = mysqli_connect($adrs, $usr, $pw, $db);
if(mysqli_connect_errno()) {
die(mysqli_connect_error());
}
if($_GET["feed"] == "hausaufgaben") {
$query = "SELECT fach, aufgabe, datum FROM hausaufgaben WHERE fachgruppe != '";
if($_GET["fremdsprache"] == "latein") {
$query .= "französisch";
}
else {
$query .= "latein";
}
$query .= "' AND fachgruppe != '";
if($_GET["englisch"] == "koch") {
$query .= "schopper";
}
else {
$query .= "koch";
}
$query .= "' AND datum > '" . date("Y-m-d") . "' ORDER BY datum ASC;";
$result = mysqli_query($connection, $query);
$data = [];
while($row = mysqli_fetch_row($result)) {
$object = '{"fach": "' . $row[0] . '", "datum": "' . $row[2] . '", "aufgabe": "' . $row[1] . '"}';
array_push($data, json_decode($object));
}
echo $data;
}
ajax
$.ajax({
type: "GET",
url: "php/getFeed.php",
cache: false,
dataType: "json",
data: {feed: "hausaufgaben", fremdsprache: this.fremdsprache, englisch: this.englisch}
})
.done(function(data, textStatus, jqXHR) {
alert(typeof(data));
this.hausaufgaben = data;
})
.fail(function(jqXHR, textStatus, error) {
alert("error: " + error);
});
It always throws the error "Unexpected token A". I got it to return each single line in the array as string, but I can't use a string in my website. My problem is, that I can't echo an array of objects with php and get the array with ajax.
Instead of trying to build a json string yourself you can do it all much easier by building the $data array using PHP data structures and then using json_encode() to convert it all to a JSON string for sending to your javascript.
Reference json_encode and json_decode
Like this :-
$data = [];
while($row = mysqli_fetch_object($result)) {
$data[] = $row;
}
echo json_encode($data);
You will also have to change you javascript to process an array of objects rather than a string, but that should be easy
I have searched stackoverflow for similar questions but nothing helped. This is my ajax call to adding.php file. I called this on jquery keyup event. When I inspect in browser I see php file returning response. However, the data in response never reaches success function of ajax.
$.ajax({
url: "anding.php",
type: "POST",
dataType: 'json',
data: JSON.stringify({mycol:mycol,mycolval:mycolval,string:string}),
contentType: 'application/json',
success: function(data){
alert(data);
var output = data.substring(0, data.indexOf('arventures'));
last = data.substring(data.indexOf('arventures') + 10);
last--;
$('.remove').remove();
$('.main_tr').after(output);
if (output == '' || output == null) {
$('.message').html('No results found.');
}
else {
$('#row1').addClass('highlight');
}//highlight row1 by default
}
});
This is my php file which returns the response. I have pasted the entire code because I dont know which part is causing the issue.
adding.php
<?php
include 'connection.php';
$postdata = json_decode(file_get_contents("php://input"), true);
//var_dump($postdata);exit;
//var_dump($postdata);
$query = "SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = '".$table_name."'
AND table_schema = '".$mysql_database."'";
$result = mysqli_query($con,$query);
$results = array();
while ($line = mysqli_fetch_assoc($result)) {
$results[] = $line;
}
$query = null;
foreach ($results as $r) {//search in order.1st search in column 1 then column 2...so on
$append = " SELECT * from " . $table_name . " WHERE " . $r['COLUMN_NAME'] . " like '" . $postdata['string'] . "%'";
$query = $query . $append;
for($i=1;$i<=(count($postdata['mycol']))-1;$i++)
{
$append1=" AND " .$postdata['mycol'][$i]. " like '" . $postdata['mycolval'][$i] . "%'";
$query = $query . $append1;
}
$query=$query." UNION";
}
$query = substr($query, 0, -6);
$result2 = mysqli_query($con, $query);
$pos = strrpos($postdata['string'], '%');
$str_count = substr_count($postdata['string'], '%');
$results2 = array();
$results3 =array();
while ($line = mysqli_fetch_assoc($result2)) {
if (strpos($postdata['string'], '%') !== false || strpos($postdata['string'], '_') !== false) {// highlight in star search
$str = preg_replace('/[^a-zA-Z0-9-]/', '', $postdata['string']);
$line = preg_replace("|^($str)|Ui", "<span class='highlights'>$1</span>", $line);
} else {
$string=$postdata['string'];
$line = preg_replace("|^($string)|Ui", "<span class='highlights'>$1</span>", $line); //highlight in normal search
}
$results2[] = $line;
}
$result2 -> data_seek(0);
while ($line1 = mysqli_fetch_assoc($result2)) {
$results3[] = $line1;
}
for ($i=1;$i<=count($results2);$i++) {
echo "<tr id='row".$i."' class='remove table_row'>";
$j=0;
foreach($results as $r1){
if($j==0){
echo "<td class='index_field' dB_id='".$results3[$i-1][$r1['COLUMN_NAME']]."'>".$results2[$i-1][$r1['COLUMN_NAME']]."</td>";
} else {
echo "<td>".$results2[$i-1][$r1['COLUMN_NAME']]."</td>";
}
$j++;
}
echo "</tr>";
}
echo 'arventures' . $i;
mysqli_close($con);
Your ajax call never reaches the success function because you have specified dataType as JSON. Either remove dataType or return JSON instead of normal HTML.
actually i want to send a comment to the each image and it should display just after clicking the button . I am able to do insert and retrieve the comment but it require refresh the page and i don't want to refresh....just like orkut.plz help me i m new in php...
thans to all............
insertimg.php
//________________________________________FOR INSERT COMMENT_____________________________________________________
if (isset($_POST['Submit']))
{
$sql = "INSERT INTO comment(imid, comm) values ('".mysql_real_escape_string(stripslashes($_REQUEST['imgId']))."', '".mysql_real_escape_string(stripslashes($_REQUEST['Comment']))."')";
//$sql = "INSERT INTO comment (com) VALUES ($_POST['Comment'])";
//$sql="UPDATE upload SET comm='$_REQUEST['Comment']'WHERE id='$_REQUEST['imgId']'";
if($result = mysql_query($sql ,$conn))
{
echo "submited:";
}
else
{
echo "<h1>problem </h1> ".mysql_error();
}
}
For display comment..
$page=$_GET["page"];
$sql = "select comm from comment where imid = '".$page."'";
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
echo"Comments:";
echo "<br>";
echo "<br>";
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
//echo $row['comm'];
echo "<textarea name=\"Comment\" style=\"background-color:#81F7BE;\">"; echo $row['comm']; echo "</textarea>";
//echo "<font>";
echo "<br>";
echo "<br>";
}
mysql_close($conn);
?>
You can solve it with AJAX.
You can use something like jQuery Ajax library.
$.ajax({
type: "POST",
url: "inserting.php",
data: "imid=1&comm=Hi",
success: function(msg){
alert( "Ajax Response: " + msg );
}
});