How will i process this Ajax in php.
What i want to do is send the data to process.php and if mode=loadlinks it will do a mysql query
function PresentLinks(div_id){
$("#loading-status").fadeIn(900,0);
$("#loading-status").html("<img src='img/bigLoader.gif' />");
$.ajax({
type: "POST",
url: "process.php",
data: "mode=loadlinks",
success: function(msg){
$("#loading-status").fadeOut(900,0);
$("#"+div_id).html(msg);
}
});}
What i want to process is
if($_POST['mode'] == loadlinks){ // this is what i want to ask
$query = "SELECT * FROM site ORDER BY link_id DESC";
$result = MYSQL_QUERY($query) or die (mysql_error());
while($data = mysql_fetch_row($result)){
echo ("$data[1]");
}}
else {
}
You need to quote strings in PHP. Otherwise they will be assumed to be constants. You should also be using PDO.
if($_POST['mode'] == 'loadlinks'){
$pdo = new PDO('mysql:host=HOST;dbname=DATABASE'), 'username', 'password');
$stmt = $pdo->execute('SELECT * FROM site ORDER BY link_id DESC');
$sites = $stmt->fetchAll();
foreach($sites as $site) {
echo "<div>" . $site['name'] . "</div>"; // Or whatever info you want to output
}
}
For performance you should be specifying table column names to retrieve instead of using *.
you need to quote the string value
if($_POST['mode'] == 'loadlinks'){.....
Related
Try to adopt JSON in database because i have data not fixed.
i can query well from terminal, and need to write same query to php script.
i have spent a lot of time before ask.
example:
sqlite> select json_extract(events.interni, '$') from events WHERE id='35';
output
[{"student_id":"12","student_name":"Lisa Ochoa"},{"student_id":"21","student_name":"Rafael Royal"}]
where id = 35 will become a variable of $ _POST ['id']
what I tried:
$result2 = $db->query("select json_extract(events.interni, '$') from events WHERE id='35'");
var_dump($result2->fetchAll(PDO::FETCH_ASSOC));
return [] <- empty array
i want instead = [{"student_id":"21","student_name":"Rafael Royal"}]
where did I go wrong?
I followed this answer on SO https://stackoverflow.com/a/33433552/1273715
but i need to move the query in php for an ajax call
possibile another help.
Can the result fron $ajax call can be usable as key value or remain string?
in other hands i can convert string to object like students = new Object()?
eaxaple of what i need in js environment
- count objects in array
- and loop key value
var data = [{"student_id":"12","student_name":"Lisa Ochoa"},{"student_id":"21","student_name":"Rafael Royal"}]
consolle.log(JSON.Stringify(data));
here I would like to avoid the backslash
consolle.log(JSON.Stringify(data.lenght));
in this phase the desired data is = 2
any possible help is largely appreciated
UPDATE
leave json_extract() function i have solved the second problem, so now i can work whit object property, and finally important to count objects in array:
<?php
try {
$db = new PDO('sqlite:eventi.sqlite3');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e) {
echo "I'm sorry, Dave. I'm afraid I can't do that.";
echo $e->getMessage();
}
$risultato = $db->query("SELECT * FROM events WHERE id = '35'", PDO::FETCH_ASSOC);
$result = array();
foreach ($risultato as $row) {
$result[] = $row;
}
// echo "Results: ", json_encode($result), "\n"; this produced backslash
echo $result[0]['interni'];
?>
js part
var num='';
$.ajax({
url: "sqlitedb/test-con.php",
type: 'POST',
dataType: 'json',
success:function(result){
console.log(result[0].student_id+ " - "+ result[0].student_name); // output here is good: 12 - Lisa Ochoa
counter(Object.keys(result).length);
}});
function counter (numero){
console.log("num2: =" + numero);
}
//out put here: 2
perfect!
odd behaviour:
console.log(result[0].student_id+ " - "+ result[0].student_name);
12 - Lisa Ochoa
outup is right but
console.log(result.lenght);
output is null
You can try something like this. and since you said in the comment about approaching it with ajax. I have included that also.
I also include php mysql backend workability for clarity. so Yo have now two options
1.) PHP WITH MYSQL
2.) PHP WITH SQLITE as you requested
index.html
<script src="jquery-3.1.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: 'get',
url: 'data.php',
dataType: 'JSON',
cache:false,
success: function(data){
var length = data.length;
for(var s=0; s<length; s++){
var student_id = data[s].student_id;
var student_name = data[s].student_name;
var res = "<div>" +
"<b>student_id:</b> " + student_id + "<br>" +
"<b>student_name:</b> " + student_name + "<br>" +
"</div><br>";
$("#Result").append(res);
}
}
});
});
</script>
<body>
<div id="Result" ></div>
</body>
In mysql database you can do it this way.
<?php
$host = "localhost";
$user = "ryour username";
$password = "your password";
$dbname = "your bd name";
$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
echo "cannot connect to db";
}
$return_arr = array();
$query = "SELECT id, student_id, student_name FROM events where id='35'";
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result)){
$student_id = $row['student_id'];
$student_name = $row['student_name'];
$return_arr[] = array("student_id" => $student_id,
"student_name" => $student_name);
}
// Encoding array in JSON format
echo json_encode($return_arr);
?>
So with sqlitedb something like this will work for you
$return_arr = array();
$result2 = $db->query("SELECT id, student_id, student_name FROM events where id='35'");
$result2->execute(array());
//$result2 = $db->query("SELECT * FROM events where id='35'");
//$result =$result2->fetchAll(PDO::FETCH_ASSOC));
while($row = $result2->fetch()){
$student_id = $row['student_id'];
$student_name = $row['student_name'];
$return_arr[] = array("student_id" => $student_id,
"student_name" => $student_name);
}
// Encoding array in JSON format
echo json_encode($return_arr);
You are surrounding you query with double quotes but inside the query there is an unescaped $.
Try escaping it:
$result2 = $db->query("SELECT json_extract(events.interni, '\$') FROM events WHERE id='35'");
var_export($result2->fetchAll(PDO::FETCH_ASSOC));
I want to check if a user has favourited an item but I'm unsure how to return the result of a database query to ajax.
I will show different html depending on the result.
Php
$query = "SELECT itemID from favourites WHERE userid = '" . $user. "'";
$result = mysql_query($query);
echo json_encode($result);
Jquery
$.ajax({
url: "inc/functions.php",
type: "POST",
data: {--result--},
success: function () {
// if result found in database
$('favourite').hide();
// if result not found
$('favourite').show();
}
});
I can't figure out how to display $result in the jquery code.
Any help much appreciated.
$result in this case is a PHP object representing a result.
You will have to use a fetch() method in order to extract the result before sending it back to your JS.
See this link. There's a list of all fetch-family method right above the comments.
Also, you will need to make a connection with you database beforehand using mysqli_connect (or mysql_connect in your case).
As stated in the comments, you should however use mysqli* functions family instead of mysql*.
Thanks to the comments for info regarding mysqli. I updated the code and solved the ajax part.
For anyone else stuck, I got it working like this:
PHP
require ("../../connection.php");
$sql = "SELECT * FROM favourites WHERE userID = ? AND itemID = ?";
$user = $_POST['userID'];
$item = $_POST['itemID'];
$statement = $db->prepare($sql);
if($statement === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $db->error, E_USER_ERROR);
}
$statement->bind_param('ii',$user,$item);
$statement->execute();
$statement->bind_result($user,$item);
while($statement->fetch()){
echo 1;
}
$statement->close();
Jquery
$.ajax({
url: "inc/userList.php",
data: userList,
type: "POST",
success: function (result) {
if (result == 1){
$('#addItem').css('display', 'none');
$('#removeItem').css('display', 'inline-block');
} else {
$('#addItem').css('display', 'inline-block');
$('#removeItem').css('display', 'none');
}
}
});
$.ajax({
type:"GET",
url: myurl, dataType:'json', data: 'username',
You should provide the accompanying HTML. It's possible your form is submitting POST variables (recommended) in which case $_GET['username'] being empty. Does it work with $_POST['username']?
I would suggest you to do some modifications, if it can work:
I. Take both $_GET and $_POST variables, if your form is using method="POST".
II. Using case insensitive match for "All" string as for all users.
<?php
include("dbconnect.php");
$username = isset($_GET['username']) ? $_GET['username']
: (isset($_POST['username']) ? $_POST['username'] : '');
if(preg_match("/^all$/i", $username))
{
$query = "select * from broons order by fname asc";
}
else
{
$query = "select * from broons where username = '$username' order by fname asc";
}
$link = mysql_query($query);
if (!$link) {
die($query);
}
$rows = array();
while($r = mysql_fetch_assoc($link)) {
$rows[] = $r;
}
$json = json_encode($rows);
echo $json;
echo $query;
?>
Good luck.
ADDED:
I might give a wrong way above.
At the calling side jQuery.ajax(), your username field seems not passed to the server, please try this:
$.ajax({
type:"GET",
url: myurl, dataType:'json', data: 'username=JohnDoe2'});
I have jquery pop form . It takes one input from the user ,mapping_key , Once the user enters the mapping key ,i make an ajax call to check if there is a user in the database with such a key.
This is my call .
Javascript:
$.ajax({
url : base_url+'ns/config/functions.php',
type: 'POST',
data : {"mapping_key":mapping_key} ,
success: function(response) {
alert(response)
}
});
PHP:
$sql = "select first_name,last_name,user_email,company_name from registered_users where mapping_key = '$mapping_key'";
$res = mysql_query($sql);
$num_rows = mysql_num_rows($res);
if($num_rows == 0)
{
echo $num_rows;
}
else{
while($result = mysql_fetch_assoc($res))
{
print_r($result);
}
}
Now i want to loop through the returned array and add those returned values for displaying in another popup form.
Would appreciate any advice or help.
In your php, echo a json_encoded array:
$result = array();
while($row = mysql_fetch_assoc($res)) {
$result[] = $row;
}
echo json_encode($result);
In your javascript, set the $.ajax dataType property to 'json', then you will be able to loop the returned array:
$.ajax({
url : base_url+'ns/config/functions.php',
type: 'POST',
data : {"mapping_key":mapping_key} ,
dataType : 'json',
success: function(response) {
var i;
for (i in response) {
alert(response[i].yourcolumn);
}
}
});
change
data : {"mapping_key":mapping_key} ,
to
data: "mapping_key=" + mapping_key,
You have to take the posted mapping_key:
$mapping_key = $_POST['mapping_key'];
$sql = "select first_name,last_name,user_email,company_name from registered_users
where mapping_key = '$mapping_key'";
or this:
$sql = "select first_name,last_name,user_email,company_name from registered_users
where mapping_key = $_POST['mapping_key']";
I have some ajax code that executes on mouseclick. It calls a file called update.php that does a bunch of stuff, including checking for user permissions, numerous database calls, etc. In the end, I also want to be able to return a few variables from PHP for the callback to use, but not sure how to reference them - or if there's a better way to return this info.
$.ajax({
type: "POST",
url: "update.php",
data: dataString,
success: callback
});
function callback(data, status)
{
// $("div").text(data);
$("div.numbert").text("[first variable here]");
$("div.numbert2").text("[second variable here]");
}
From my update.php file (some snippets):
if ($check_access > 0)
{
// Update database
$sql = "UPDATE db SET access = '1' WHERE user = '$user'";
$result = mysql_query($sql) or die(mysql_error());
// Give access - function returns data to variable
$value = GiveAccess($user);
// Email - function returns data to variable
$emaillist = emailAdmins($user);
} else {
$message = "Sorry you do not have access";
}
So I'd like to figure out how to use the variables $message, $value and $emaillist in my callback if possible.
I'm wondering if I just need to make multiple $.ajax POST calls, with each .php function that returns a variable having it's own call?
Thanks!
----UPDATE-------
Updated code trying to use the json methods - thanks for all the help - but seems I'm missing one last thing.
$.ajax({
type: "POST",
url: "update.php",
data: dataString,
dataType: 'json',
success: callback
});
function callback(data, status)
{
// $("div").text(data);
$("div.numbert").text(data.value);
$("div.numbert2").text(data.emaillist);
and update.php:
$storage = array();
// Update database
$sql = "UPDATE db SET access = '1' WHERE user = '$user'";
$result = mysql_query($sql) or die(mysql_error());
// Give access - function returns data to variable
$storage['value'] = "some user";
// Email - function returns data to variable
$storage['emaillist'] = "some stuff";
header('Content-type: application/json');
echo json_encode($storage);
exit(0);
Thanks again.
You can use a JSON wrapper:
$messages = array();
$messages['value'] = GiveAccess($user);
$messages['emaillist'] = emailAdmins($user);
$messages['message'] = "Sorry you do not have access";
echo json_encode($messages);
And then simply use:
data.value data.emaillist data.message
in your Javascript.
Easiest way would be to use JSON...
$.ajax({
type: "POST",
url: "update.php",
data: dataString,
dataType: 'json',
success: callback
});
function callback(data, status)
{
// $("div").text(data);
if(data.error){
alert(error.message||'Unknown Error');
} else {
$("div.numbert").text(data.access||'No value');
$("div.numbert2").text(data.emailList||'No value');
}
}
PHP:
if ($check_access > 0)
{
// Update database
$sql = "UPDATE db SET access = '1' WHERE user = '$user'";
$result = mysql_query($sql) or die(mysql_error());
$responseData = array();
// Give access - function returns data to variable
$responseData['access'] = GiveAccess($user);
// Email - function returns data to variable
$responseData['emailList'] = emailAdmins($user);
} else {
$responseData['error'] = array('code' => 403, 'message' => "Sorry you do not have access");
}
header('Content-type: application/json');
print json_encode($responseData);
exit(0);
No, just return a JSON object or a dataset that's delimited that you can parse.
You can return your values using json:
$storage = array();
if ($check_access > 0)
{
// Update database
$sql = "UPDATE db SET access = '1' WHERE user = '$user'";
$result = mysql_query($sql) or die(mysql_error());
// Give access - function returns data to variable
$value = GiveAccess($user);
$storage['value'] = $value;
// Email - function returns data to variable
$emaillist = emailAdmins($user);
$storage['emaillist'] = $emaillist;
} else {
$message = "Sorry you do not have access";
$storage['message'] = $message;
}
header("Content-Type: application/json; charset=utf8");
$return = json_encode($storage);
echo $return;
exit;
You can then iterate over the object and go
function callback(data, status)
{
// $("div").text(data);
$("div.numbert").text(data.value);
$("div.numbert2").text(data.emaillist);
}