I have a simple PHP code that retrieves data from the table including image and stores it in a JSON object.
<?php
$con = mysql_connect("localhost","root","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$selected = mysql_select_db("req2",$con)
or die("Could not select req2");
$table_first = 'locationtab';
$query=mysql_query("SELECT Id,City,Image FROM $table_first");
while ($row=mysql_fetch_assoc($query)) {
$array=$row;
$array['Image']=base64_encode($row['Image']);
$output[]=$array;
}
echo json_encode($output);
mysql_close($con);
?>
This works perfectly fine and I'm able to view the JSON object using print.
on the client side, I wrote a Javascript+Ajax code to call this PHP file and on success display the data in the JSON object. I dont know what is missing in the below code but I don't seem to get the AJAX part to work at all. PLease so help
<html>
<head>
<script src="file://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$.ajax({
url:"table.php",
dataType:'json',
type:'POST',
success:function(output) {
alert( output.Id );
}
});
});
</script>
</head>
<body>
<p>test</p>
</body>
</html>
output is an array of objects with ids.
You are treating it as a single object with an id.
You need either a for loop, or to grab a specific index.
alert( output[0].Id );
Related
I'm trying to show MySQL data using Ajax. Unfortunately, I am unable to find the correct way. I was trying to show MySQL data on a select box. When I click on "select category" option then all category will show as dropdown.
here is my HTML code.
<!DOCTYPE html>
<html>
<head>
<title>PHP MySQL Insert Tutorial</title>
<script src='https://code.jquery.com/jquery-2.1.3.min.js'></script>
</head>
<body>
<select id='category'>
</select>
<script src='fetch.js'></script>
</body>
</html>
I have used this JS code to send request. Here is my JS code.
$('#category').onclick(function(){
$.getJSON(
'fetch.php',
function(result){
$('#category').empty();
$.each(result.result, function(){
$('#category').append('<option>'+this['category']+'</option>');
});
}
);
});
I have used this php code to complete ajax request and database connection. Here is my PHP code.
<?php
define('HOST','localhost');
define('USERNAME', 'root');
define('PASSWORD','');
define('DB','ajax');
$con = mysqli_connect(HOST,USERNAME,PASSWORD,DB);
$category = $_GET['category'];
$sql = "select category from ajaxx where category='$category'";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array('category'=>$row[0]));
}
echo json_encode(array('result'=>$result));
enter code here
mysqli_close($con);
?>
When you make the AJAX request, it's to this URL:
fetch.php
But then in the server-side code, you try to get a query string value:
$category = $_GET['category'];
You can't get a query string value that you never provided. So when you build your SQL query (which is wide open to SQL injection by the way), there's nothing to get from the database.
If you want to use a query string value, you have to provide one:
$.getJSON(
'fetch.php?category=someValue',
function(result){
//...
}
);
What value you provide or where you get that value is up to you. (Perhaps from $('#category').val()?) But it has to exist before you can use it.
You may have confused two things: (a) initially fetching the HTML code to populate the options of your <select> control, and (b) Catching the selected option and using it to perform another DB query, returning new data.
Please review this modified (untested) code sample:
<!DOCTYPE html>
<html>
<head>
<title>PHP MySQL Insert Tutorial</title>
<script src='https://code.jquery.com/jquery-2.1.3.min.js'></script>
</head>
<body>
<select id='category'>
</select>
<div id="resultDIV"></div>
<script src='fetch.js'></script>
</body>
</html>
javascript/jQuery:
//Run on document ready to populate the dropdown box
$(document).ready(function(){
$.getJSON(function(){
'fetch.php',
function(result){
$('#category').empty();
$.each(result.result, function(){
$('#category').append('<option>'+this['category']+'</option>');
});
}
});
$(document).on('click', '#category', function(){
//run on click to take dropdown value and perform lookup
myCat = $(this).val();
$.ajax({
type: 'post',
url: 'getcategory.php',
data: 'category=' +myCat,
success: function(d){
//if (d.length) alert(d);
$('#resultDIV').html(d);
}
});
});
}); //END document.ready
I have used this php code to complete ajax request and database connection. Here is my PHP code.
<?php
/*** getcategory.php ***/
define('HOST','localhost');
define('USERNAME', 'root');
define('PASSWORD','');
define('DB','ajax');
$con = mysqli_connect(HOST,USERNAME,PASSWORD,DB);
$category = $_GET['category'];
$sql = "select category from ajaxx where category='$category'";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array('category'=>$row[0]));
}
echo json_encode(array('result'=>$result));
enter code here
mysqli_close($con);
?>
Here are some basic, simple AJAX examples to study (the three links at the bottom, but also note the information from the first link). Copy them to your server and make them work - play around with them:
AJAX request callback using jQuery
Your ajax code needs some changes :
<!DOCTYPE html>
<html>
<head>
<title>PHP MySQL Insert Tutorial</title>
<script src='https://code.jquery.com/jquery-2.1.3.min.js'></script>
<script type="text/javascript">
function myAjax ()
{ $.ajax( { type : 'POST',
data : { 'category' : $('#txt_cat').val() }, // SEND CATEGORY.
url : 'fetch.php',
success : function ( result )
{ $( '#category' ).empty();
var arr = JSON.parse( result );
var sel = document.getElementById("category");
for ( i = 0; i < arr.length; i++ )
{ var option = document.createElement( "option" );
option.text = arr[ i ];
sel.add( option );
}
},
error : function ( xhr )
{ alert( "error" );
}
}
);
}
</script>
</head>
<body>
Enter category <input type="text" id="txt_cat"/>
<button onclick="myAjax()">Click here to fill select</button>
<select id='category'>
<option> - empty - </option>
</select>
</body>
</html>
fetch.php
<?php
$category = $_POST[ "category" ]; // CATEGORY FROM HTML FILE.
// CONNECT TO DATABASE AND QUERY HERE.
$result = Array( "111","222","333","444" ); // SAMPLE DATA.
echo json_encode( $result );
?>
I can't seem to get the 123.php return information to use in the html document where I use jQuery-AJAX-thing (to change the content of div named div1).
Im pretty new to JavaScript, PHP and html; but tried some tutorials now and can't seem to make em fit my needs so would really appriciate some help.
Here is my 123.html that should use AJAX-jQuery thing to call my 123.php
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.ajax({
type: "POST",
url: "/123.php",
data:{id:"3", name:"John Doe"},
success:function(response){
alert('ok-'+data+'-'+respText+'-'+xhr);
$("#div1").html(respText);
},
error: function (request, status, error) {
alert(request.responseText);
}
});
});
</script>
</head>
<body>
along with the 123.php
<?php
$my_id = trim($_REQUEST['id']);
$my_name = trim($_REQUEST['name']);
$file = '123.txt';
// Open the file to get existing content
$current = file_get_contents($file);
// Append to the file
$current .= 'time:' . time() . ',id:' . $my_id . ',name:' . $my_name . "\n";
// Write the contents back to the file
file_put_contents($file, $current);
echo 'received following: id: ' . $my_id . ' and name: ' . $my_name;
?>
The 123.txt was just to see if the php file responded, and it does, but only when I pass
/123.php?id=7&name=Jane%20Doe
Elsewhere using the 'post' method, no response (gets errors from the JavaScript)
So I guess it's the structure of AJAX/jQuery;
for the attempt listed above, I get the error in JavaScript-console "Uncaught error: reference not defined"
and when I use the following 123.html instead (replacing the other 123.html)
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").post("/123.php",{id:"3",name:"John Doe"},function(data,status){alert("Data: " + data + "\nStatus: " + status);});
});
});
</script>
</head>
<body>
<div id="div1">Text that should be changed</div>
<button>Press me, I'm a button</button>
</body>
</html>
I get "Uncaught TypeError: Undefined is not a function", I tried to look it up and some people wrote that it could be solved inserting
(function ($) {
$(document);
}(jQuery));
However it did not (inserted it in the very top, just below the script-start-tag )
I can't seem to figure what I'm doing wrong, and I really appriciate any help and directions as for where to look.
Thanks in advance
Your php is not returning JSON or XML therefore you cannot get data. Replace this
success:function(response){
alert('ok-'+data+'-'+respText+'-'+xhr);
$("#div1").html(respText);
},
with this
success:function(response){
alert('ok-'+response);
$("#div1").html(response);
},
I'm doing GeoRef application. This is my index.php:
<!doctype html>
<html lang="es">
<head>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"> </script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript" src="http://www.ign.gob.ar/argenmap/argenmap.jquery.min.js"></script>
<script>
$(document).ready(function () {
$.ajax({
url: 'getcoord.php',
dataType: 'json',
error: function(){
alert("ERROR");
},
success: function(res) {
var ico;
ico='Icon.png';
var marcador;
$('#mapa').argenmap();
$('#mapa').centro(-34.597907,-58.385557)
$('#mapa').zoom(4);
$('#mapa').capaBase('satellite');
for(var i=0;i<res.length;i++)
{
marcador=[{lat: res[i].latitud, lng:res[i].longitud,icono:ico}];
$('#mapa').argenmap().agregarMarcadores(marcador);
}
} });});
</script>
</head>
</html>
And this is my getcoord.php file:
<?php
include("config.php");
require("db.inc");
$sql = "SELECT * FROM datos_mapa";
$res = buscar($sql);
$arry=array();
foreach ($res as $r)
{
$arr = array('longitud' => $r['longitud'],'latitud' => $r['latitud']);
array_push($arry,$arr);
}
echo json_encode($arry);
?>
My problem is that, when I run getcoord.php using json_encode($arry), I see the information I want but, it doesn´t return to index.php. I´ve tried:
Using json in dataType. Gives me a Json Object but with Object in each field instead of latitude and longitude.
Using jsonp in dataType. Results an error.
Using text in dataType. I get the information I want, but as a string not as an Object.
Replacing echo json_encode($arry) with:
a) json_encode($arry);
b) print_r(json_encode($arry));
c) echo $_GET['receive'].'('.json_encode($arry).');';
But getting the same error.
Why I´m not getting the information in the format I want?
I was trying this code at work where apache is configured and didn´t work (keeps getting error when using dataType: 'json'). In my personal computer, using xampp, it works. So I think the code is right. Is there anything else I should configure?
I am trying to create a feature on my website that automatically updates the database onchange of the textarea below (which is going to be act as a 'post-it note for reminders'). I am new to ajax, and I was wondering if someone can show me a basic example of how I would make an AJAX call to update my database onChange of the textarea below?
<?php
//Create mysql connect variable
$conn = mysql_connect('samplesource.com', 'example', 'pass');
//kill connection if error occurs
if(!$conn){
die('Error: Unable to connect.' . '<br>' . mysql_error());
}
//connect to mysql database
mysql_select_db("mydb", $conn);
session_start();
$userid = $_SESSION['id'];
$results = ("SELECT * FROM notes WHERE userid='$userid'");
?>
<html>
<head>
<title>practice</title>
<script src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".sometext").change(function(){
//make ajax call to update database onChange
});
});
</script>
</head>
<body>
<textarea class="note" style="resize:none; width:300px; height:200px;"> </textarea>
</body>
</html>
First, you'd need to move your database save script into a new file e.g save.php
On your <textarea> i'd add
<textarea onchange="saveChanges(this);"></textarea>
For the javascript save function that's called when a change is made:
function saveChanges(object){
$.ajax({
url: 'save.php',
data: 'content=' + object.value,
cache: false,
error: function(e){
alert(e);
},
success: function(response){
// A response to say if it's updated or not
alert(response);
}
});
}
This is a very quick and dirty way of doing it.
I can send a query to mysql database with following code:
$sql = mysql_query("INSERT INTO wall VALUES('', '$message', '$replyno')");
My questions is, Is there any way to send a query with just a click on some text.
Let's example: there are a text name Reply. I want if i click this Reply text then mysql database field value (field name: Reply, type: int) will be increase by 1.
Sorry I DON'T KNOW ABOUT JAVASCRIPT/AJAX:(
FINAL UPDATER CODE TO #DEVELOPER:
<html>
<head>
<title>Untitled Document</title>
</head>
<script language="javascript">
$("#mylink").click(function() {
$.ajax({
url: "test.php"
}).done(function() {
$(this).addClass("done");
});
});
</script>
<body>
echo "<a href='#' id='mylink'>Reply</a>";
</body>
</html>
Php page:
<?php
include("database/db.php");
$sql = mysql_query("INSERT INTO wall VALUES('','','','','','','','1');");
?>
You should have this link or button to be clicked wired to an ajax call using jQuery
http://api.jquery.com/jQuery.ajax/
It should call a php page, which contains the query you're looking to run. You can pass in arguments with the ajax call as well, so that your $message and $replyno are set properly before executing.
<script>
$("#mylink").click(function() {
$data = $("#myform").serialize();
$.ajax({
url: "postquery.php",
data: $data
}).done(function() {
$(this).addClass("done");
});
});
</script>
then your php page would look something like this:
<?php
...
$message = mysql_real_escape_string($_REQUEST['message']);
$replyno = mysql_real_escape_string($_REQUEST['replyno']);
$sql = mysql_query("INSERT INTO wall VALUES('', '$message', '$replyno')");
....
?>
Excaping your incoming strings using "mysql_real_escape_string" is always important to prevent SQL Injection attacks on your database.
Your HTML should look something like this:
<html>
...
<input type="textarea"></input>
Reply
...
</html>
This will cause the previously stated jquery statement to trigger when "Reply" is clicked.
Here is with your updated code. I corrected the link ID and also removed the form serialization data since your test code does not appear to need it. I also added the reference to the jQuery library:
<html>
<head>
<title>Untitled Document</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script language="javascript">
$("#mylink").click(function() {
$.ajax({
url: "test.php"
}).done(function() {
$(this).addClass("done");
});
});
</script>
</head>
<body>
<a href='#' id='mylink'>Reply</a>
</body>
</html>
The problems you're likely seeing are because of your query, not the front end code. Try adding some debug code like this:
<?php
include("database/db.php");
$sql = mysql_query("INSERT INTO wall VALUES('','','','','','','','1');");
if(!$sql)
{
echo mysql_error();
}
?>
Or try checking your servers error logs.
$sql = mysql_query("INSERT INTO wall VALUES('', '$message', '$replyno')");
You have to use jquery and ajax like this:-
<script type="text/javascript">
$j(document).ready(function() {
$j('#reply').click(function(){
jQuery.ajax({
url: "test.php", //Your url detail
type: 'POST' ,
data: ,
success: function(response){
}
});
});
});
</script>
In the file "updat_post.php" write:
If(isset($_GET['visit_post']))
$pdo->query('update posts set counter = counter+1');
In your js/jquery file on document ready write:
$('#mybutton').click(function() {
$.post('update_post.php', {visit_post: true});
});