AJAX cannot print elements onclick - javascript

I have got 2 files, one named index.php and one named api.php. I am trying to retrieve some data from my DB and I've done this simple example before trying to put the code into my project. In the api.php file I ve got the following:
$connessione=mysql_connect(DB_HOST,DB_USER,DB_PASS) or die(mysql_error());
$scelta_db=mysql_select_db(DB_NAME) or die(mysql_error());
$idM=67;
$result = mysql_query("SELECT * FROM map_comment WHERE idMap ='$idM'");
$array = array();
while ( $row = mysql_fetch_row($result) )
{
$array[] = $row;
}
echo json_encode($array);
While in the index.php:
<html>
<head>
<script language="javascript" type="text/javascript" src="jquery.js"></script>
</head>
<body>
<h3>Output: </h3>
<div id="output">Attacco qua sotto</div>
<button onclick ='show_comments'>Carica commenti </button>
<script id="source" language="javascript" type="text/javascript">
function show_comments()
{
$.ajax({
url: 'api.php',
data: "",
dataType: 'json',
success: function(rows)
{
for (var i in rows)
{
var row = rows[i];
var idU = row[1];
var text_map = row[3];
$('#output').append("<b> idU: </b>"+idU+"<b>text </b>"+text_map)
.append("<hr />");
}
}
});
};
</script>
</body>
</html>
The problem is that it does not seems to "append" nothing and I dunno what I am doing wrong. I KNOW I should use mysqli, I'll fix that. Plus: HOW can I "send" a $idM to the api.php from the index.php (for example an $id already defined in the index.php)?

Your function is not called when you click the button, in an onclick attribute you're not setting a function but rather writing code to execute. See example below
<button onclick ='show_comments()'>...
To send the id, you can use the data parameter
data: {id: 67},
Since this is a GET request you can use the php super global $_GET to retrieve the value $_GET['id'].

Related

get the data from database with ajax

i want to get the data from database through ajax but its gives me only one record not other but i want all the records from database i have search too much to understand the problem
but can't get that
that is database image
php code
//--------------------------------------------------------------------------
// Example php script for fetching data from mysql database
//--------------------------------------------------------------------------
$host = "localhost";
$user = "root";
$pass = "";
$databaseName = "search";
$tableName = "ajax01";
//--------------------------------------------------------------------------
// 1) Connect to mysql database
//--------------------------------------------------------------------------
include 'DB.php';
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
//--------------------------------------------------------------------------
// 2) Query database for data
//--------------------------------------------------------------------------
$result = mysql_query("SELECT * FROM $tableName"); //query
$array = mysql_fetch_row($result); //fetch result
//--------------------------------------------------------------------------
// 3) echo result as json
//--------------------------------------------------------------------------
echo json_encode($array);
?>
html
<!-------------------------------------------------------------------------
1) Create some html content that can be accessed by jquery
-------------------------------------------------------------------------->
<h2></h2>
<script id="source" language="javascript" type="text/javascript">
$(function ()
{
//-----------------------------------------------------------------------
// 2) Send a http request with AJAX http://api.jquery.com/jQuery.ajax/
//-----------------------------------------------------------------------
$.ajax({
url: 'api.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
// var id = data[0]; //get id
// var vname = data[1]; //get name
//--------------------------------------------------------------------
// 3) Update html content
//--------------------------------------------------------------------
$('#output').html("<b>id: </b>"+id+"<b> name: </b>"+name); //Set output element html
//recommend reading up on jquery selectors they are awesome
// http://api.jquery.com/category/selectors/
}
});
});
</script>
</body>
</html>
You only ever get one row.
$array = mysql_fetch_row($result);
You need to loop that line and keep going until you run out of rows (creating an array of row arrays as you go).
Then json_encode that final array.
THe best way to do this, use 3 different files;
php_page.php
script.js
php_handler.php
In the php_page.php you have have actually the HTML
In the script.js you make the request with ajax
In php_handler.php you give the response and there you can make the connection and take all the data from your database that you need!
php_page.php
<!doctype html>
<html>
<head>
<title></title>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<ul id="list">
<!-- In here comes the data! -->
</ul>
<button id="button">Get Data</button>
</body>
</html>
script.js
$(document).ready(function() {
$("#list").on("click", function() {
$.ajax({
url: "php_handler.php"
}).done(function(data){
$(this).empty().append("<li>"+ data +"</li>");
});
});
});
php_handler.php
<?php
$con = mysqli_connect($host, $user, $pass, $db);
$query = mysqli_query($con, "SELECT [FIELD_NAME] FROM [TABLE_NAME]");
foreach($query as $data)
{
echo '<li>' . $data . '</li>';
}
?>
The mysql_fetch_row takes only one record from result of query. You need to store each row of query result in an array, then finally convert the array to its JSON representation.
$records = [];
while( $row = mysql_fetch_row( $result ) ){
array_push( $records, $row );
}
echo json_encode( $records );
Substitute the mysql_fetch_row and json_encode lines of your code with this to achieve it.

$.ajax post loads html code from current page instead of requested php

im new to javascript, but have to use it for an ajax load of a .php
This is my ajax.js
$(document).ready(function(){
var url = $(location).attr('href');
var uA = navigator.userAgent;
$.ajax({
type: "POST",
url: "neo4j.php",
data: {"url": url, "userAgent": uA}
});
alert(url);
});
It should post the datas to neo4j.php.
My Start.php looks like
<head><title>Start</title></head>
<?php
include("db.php");
$sql = "SELECT * FROM category_paths LIMIT 10";
$pattern = mysql_query($sql);
while($row = mysql_fetch_object($pattern)){
if ($row->descendant_id == 1) {
echo "<a href='http://localhost/2play/Start.php'>$row->descendant_id</a><br>";
}else {
echo "<a href='http://localhost/2play/Section.php/?sec=$row->descendant_id'>$row->descendant_id</a><br>";
}
}
?>
<footer><script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="ajax.js"></script></footer>
Here my code works.
But if I click on a link to section.php
<head><title>Section</title></head>
<?php
include("db.php");
echo "<a href='http://localhost/2play/Start.php'>1</a><br>";
if(isset($_GET["sec"])) {
$sec = $_GET["sec"];
}
$sql = "SELECT * FROM category_paths WHERE ancestor_id = $sec AND length = 1";
$pattern = mysql_query($sql);
while($row = mysql_fetch_object($pattern)){
echo "<a href='http://localhost/2play/Game.php/?game=$row->descendant_id'>$row->descendant_id</a><br>";
}
?>
<div id="js">test</div>
<footer><script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="ajax.js"></script>
</footer>
My ajax.js dont load the js code, instead it load the html-code of the current page. Copy from loaded section.php with firebug:
<html>
<head>
<title>Section</title>
</head>
<body>
1
<br>
123
<br>
124
<br>
125
<br>
156
<br>
197
<br>
<footer>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="ajax.js" type="text/javascript">
<--Here the script should be loaded, but it relaods the raw non-php code from section.php-->
<head><title>Section</title></head>
<a href='http://localhost/2play/Start.php'>1</a><br>
<footer><script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="ajax.js"></script>
</footer>
<--End-->
</script>
</footer>
</body>
</html>
What I already found out:
If I manually add some get-vars to the Start.php url like
http://localhost/Start.php?foo=bar
the script wont work and do some failure as above.
SOLVED
Ok I found my mistake, and cant believe it.
It is because i had an slash in the link before I set the get-vars http://localhost/2play/Section.php**/**?sec=$row->descendant_id'> . After deleting it, the problem disappeared.
You should nod declare variable inside $.ajax. Try something like this
$(document).ready(function(){
var data1 = "foo",
data2 = "bar";
$.ajax({
type: "POST",
url: "foobar.php",
data: {"data1": data1, "data2": data2}
});
alert(data1);
});
More about AJAX can follow the link
Ok I found my mistake, and cant believe it. It is because i had a slash in the link before I set the get-vars
http://localhost/2play/Section.php**/**?sec=$row->descendant_id'>
After deleting it, the problems disappeared.

Share config in php with javascript + ajax (json) in usage

I am trying to share a config.inc.php in php with javascript. It works, but not with ajax... there is always the "error-function" called. Is there any way to share the config file with an working ajax?
I am using it in an apache cordova project, with bootstrap and jQuery.
Here is a part of my index.html file:
<html>
<head>
<title></title>
<link rel="stylesheet" href="lib/bootstrap/3.3.1/css/bootstrap.min.css">
<link rel="stylesheet" href="lib/bootstrap/3.3.1/css/bootstrap-theme.min.css">
<script type="text/javascript" src="js/jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="lib/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<script type="text/javascript" src="config.inc.php"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
console.log(config_url);
jQuery.ajax({
url: config_url,
type: "POST",
dataType: "json",
data: "param=no",
success: function(html){
doSomething();
});
}, error: function(e){
alert(e); //always an alert :/
}
});
});
</script>
</head>
<body></body>
</html>
Here is my config.inc.php:
<?php
global $config;
$config["url"] = "http://192.168.1.Y/fetchdata.php";
$config["db"]["host"] = "localhost";
$config["db"]["database"] = "myDatabase";
$config["db"]["username"] = "root";
$config["db"]["password"] = "";
$config["db"]["port"] = null;
$config["db"]["socket"] = null;
?>
var config_url = <?php echo json_encode($config["url"]); ?>; //if i remove this line, ajax will work and call the "success part".
And finally the last file "fetchdata.php" for database connection:
<?php
// Allow access via php
header('Access-Control-Allow-Origin: *');
// Load configuration
require 'config.inc.php';
global $config;
$sqlconn = mysqli_connect($config["db"]["host"], $config["db"]["username"],
$config["db"]["password"], $config["db"]["database"], $config["db"]["port"],
$config["db"]["socket"]) or die(mysqli_error());
$dataquery = mysqli_query($sqlconn, "SELECT * FROM table_profil");
$arr = array();
while($row = mysqli_fetch_object($dataquery)) {
array_push($arr, array("key" => $row->key, "value" => $row->value));
}
print_r(json_encode($arr));
?>
I used XAMPP for testing. The output is
var config_url =
"http://192.168.1.Y/fetchdata.php";[{"key":"size","value":"150"},{"key":"color","value":"green"}]
Without the ''var [...] .php";'' output, it will work... But I liked to share the config.
you used javascript var in php without <script> tag? How come? use
<script>
var config_url = '<?php echo json_encode($config["url"]); ?>';
</script>
instead of
var config_url = <?php echo json_encode($config["url"]); ?>;
with that way you can pass config_url with javascript but your ajax will not work .. cause ajax not work through servers so you can't use "http://192.168.1.Y/fetchdata.php" in your ajax url .. in your ajax url just use url:'fetchdata.php', and check you link to its path
Thanks mohamed-yousef and Michael, I solved it with a part of your answers. You shown me the error and gave me hints for the solution :).
Ted wrotes the solution in Shared JSON data for php and Javascript/Ajax . I use a "GET"-Param for supporting javascript. Because my "fetchdata.php" won't have any javascript, I use it without the param => no javascript output if not needed.
My index.php includes the config with a "js" parameter; looks like ...
<script type="text/javascript" src="config.inc.php?js"></script>
... and my "config.inc.php" looks like
<?php
global $config;
$config["url"] = "http://192.168.1.Y/fetchdata.php";
....
if (isset($_GET["js"])) {
echo
'
var config = [];
config["url"] = "' . $config["url"] . '";
';
}
?>
No changes in "fetchdata.php".
This solution is working for me. Thanks everybody!

PHP - Call PHP file in a DIV

I'm having an issue with a AJAX code, I've near to none experirence with this language, the issue is, I'm trying to call a PHP file "prepare_game.php":
prepare_game.php
<?php
session_start();
include "config.php";
if(isset($_SESSION["user_name"]))
{
$selectcategoria = "SELECT DISTINCT id_partida, id_categoria FROM partida WHERE user_name =".$_SESSION["user_name"];
$querycategoria = mysqli_query($con, $selectcategoria);
$rowcategoria = mysqli_fetch_array($querycategoria);
$personajenum = rand(0,23);
$selectpersonaje = "SELECT nombre_personaje, foto_personaje FROM Categoria WHERE id_personaje =".$personajenum;
$querypersonaje = mysqli_query($selectpersonaje);
$rowpersonaje = mysqli_fetch_array($querypersonaje);
$selectturno = "SELECT user_name_retador, user_name_oponente FROM WHERE user_name =".$_SESSION["user_name"];
$queryturno = mysqli_query($con, $selectcategoria);
$rowturno = mysqli_fetch_array($query);
if($_SESSION["user_name"]=$rowturno["user_name_oponente"]){
$insertestado = "INSERT INTO estadojugador(id_partida, user_name, turno_activo, personaje_secreto) VALUES(".$row['id_partida'].", ".$_SESSION["user_name"].", "."false".", ".$rowpersonaje["nombre_personaje"].")";
$queryestado = mysqli_query($insertestado);
}
else
{
$insertestado = "INSERT INTO estadojugador(id_partida, user_name, turno_activo, personaje_secreto) VALUES(".$row['id_partida'].", ".$_SESSION["user_name"].", "."true".", ".$rowpersonaje["nombre_personaje"].")";
$queryestado = mysqli_query($insertestado);
}
echo "<img src=\"categorias/".$rowpersonaje["foto_personaje"]."\" width=\"240\" height=\"360\" style=\"display:block; margin: 0 auto;\"></img>";
}
?>
As you may see, there's no need for any POST/GET array variables, then I created a JS function that calls this PHP file using an AJAX call.
prepareGame()
prepareGame = function() {
$.ajax({
url: "prepare_game.php"
}).done(function(data) {
console.log(data);
});
}
Then I call the JS function through:
JS script:
<script type="text/javascript">
prepareGame();
</script>
However, nothing happens.
Problem:
How to call a PHP file, without using form tags, nor use any DATA attributes in the AJAX call?
Notes:
prepare_game.php fills two tables in a DB, then it prints an IMG tag through an echo.
prepare_game.php loading method must be inside a DIV tag.
Thanks in advance.
Try something like this:
<div id="whatever"></div>
<script>
$(document).ready(function() {
$('#whatever').load('prepare_game.php');
});
</script>
This should just take the results from prepare_game.php and put them in the #whatever div.

.load page with form variables

I want to load a page with variables from a form and it seems it doesn't get my select value. I'm new to JavaScript and I need this instead doing a serialize to get values and then use .load().
Here is my code:
<?php
include('dbconfig.php');
$id=$_GET['id'];
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function filtreaza_tip () {
var tip = document.getElementById("tip").value;
var id_local= document.getElementById("id_local").value;
$( "#tipuri_rezervare" ).load("select_tip_rezervare.php?id="+id_local+"&tip="+tip);
}
</script>
</head>
<body>
<form id="tip" method="post">
<input type="hidden" name="id_local" id="id_local" value="<?php echo $id;?>">
<select name="tip" id="tip" onchange="filtreaza_tip();">
<option value="0">Selectati Tipul</option>
<?php
$stmt = $dbh->prepare("SELECT *
FROM Tip_Rezervare
INNER JOIN Local ON Local.ID_Local=:id_local
INNER JOIN Leg_Tip_Local ON Tip_Rezervare.ID_Tip=Leg_Tip_Local.ID_Tip and Leg_Tip_Local.ID_Local=:id_local");
$stmt->bindParam(':id_local', $id, PDO::PARAM_INT);
$stmt->execute() ;
while ($row = $stmt->fetch()) {
$local=$row['Denumire_Local'];
echo '<option value="'.$row['ID_Tip'].'">'.$row['Nume'].'</option>';
}
echo'</select>';
?>
<div id="tipuri_rezervare">
</div>
</body>
</html>
I have a working one with serialize but I don't want that. Here is the working code:
function filtreaza_tip ()
{
var datastring = $("#tip").serialize();
$.ajax({
type: "POST",
url: "tip_rezervare.php",
data: datastring,
success: function(data) {
$( "#tipuri_rezervare" ).load('select_tip_rezervare.php?',data);
}
});
}
Your form id and dropdown id are same.
Thats the reason you are getting the issue.
Change the ids it will work fine.
Load uses POST method so you can just do this:
var tip = document.getElementById("tip").value;
var id_local= document.getElementById("id_local").value;
$( "#tipuri_rezervare" ).load("select_tip_rezervare.php, {tip: tip, id: id_local});
Then you can get your values on your select_tip_rezervare.php page with $_POST['tip'] and $_POST['id'].
Use the jquery method $.val() like that :
$("#tip").val(); // Return the input / select value of the selector
Check the jQuery Api : http://api.jquery.com/val/

Categories