I'm trying to get the following code to work that is supposed to display data from my database when the following link is clicked: (without refreshing the page)
<a id="bugatti_link" href="#" database_id="Bugatti">Bugatti</a>
Unfortunately it's not working, it's not displaying anything and not giving an error.
index.php =
<a id="bugatti_link" href="#" database_id="Bugatti">Bugatti</a>
<script>
$("#bugatti_link").click(load_ajax);
function load_ajax(e) {
var link = $(e.target);
var vehicle_database_id = link.attr("database_id");
var ajax_params = {"brand": vehicle_database_id};
$.getJSON("query2.php", ajax_params, success_handler)
}
function success_handler(data) {
//data variable contains whatever data the server returned from the database.
//Do some manipulation of the html document here. No page refresh will happen.
}
</script>
query2.php =
<?php
$host = "xx";
$user = "xx";
$db = "xx";
$pass = "xx";
$pdo = new PDO("mysql:host=" . $host . ";dbname=" . $db, $user, $pass);
$rows = array();
if(isset($_GET['brand'])) {
$stmt = $pdo->prepare("SELECT brand FROM cars WHERE brand = ? ");
$stmt->execute(array($_GET['brand']));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
echo json_encode($rows);
?>
you pass your json data to 'success_handler', but the data is not processed within that function
Note the addition of .error to your $.getJSON code. Should the request fail, this will tell you why. A response was received, but it might have an issue and this will tell you. See the note below as to why it might be failing silently.
Also, adding a $(document).ready wrapper around your code is best as it ensures the page has fully loaded before running the javascript inside. Depending on the browser and how nested the element is, it may or may not be ready for attaching events. In any regard, it's best to put it in the document ready to always be sure.
$(document).ready( function(){
$("#bugatti_link").click(function(e){
e.preventDefault();
var vehicle_database_id = $(this).attr("database_id");
var ajax_params = {"brand": vehicle_database_id};
$.getJSON("query2.php", ajax_params, function(data){
//data variable contains whatever data the server returned from the database.
//Do some manipulation of the html document here. No page refresh will happen.
})
.error(function(data,msg,error){
alert( msg );
});
});
})
Important: As of jQuery 1.4, if the JSON file contains a syntax error,
the request will usually fail silently. Avoid frequent hand-editing of
JSON data for this reason. JSON is a data-interchange format with
syntax rules that are stricter than those of JavaScript's object
literal notation. For example, all strings represented in JSON,
whether they are properties or values, must be enclosed in
double-quotes. For details on the JSON format, see http://json.org/.
Related
So, I imagine this is pretty simple but I can't really wrap my head around it, I am pretty new to AJAX so bear with me, I have created simple REST API for my little project with native php which gets characters info from MySQL database and I want to insert that data for each character on each click of a link,idea is this
simple page with links and the right side of the page is the div which I created to insert that data in,
This is my code for ajax currently which doesn't work
var title = document.getElementById('charactertitle');
var desc = document.getElementById('characterdesc');
var buttonClick = document.getElementsByClassName('content-button');
buttonClick.addEventListener('click', loadCharacterInfo);
function loadCharacterInfo(e){
e.preventDefault();
var xhr = new XMLHttpRequest();
xhr.open('GET','/api/characters/read.php',true);
xhr.onload = function(){
var characters = JSON.parse(this.responseText);
output = '';
for(var i in characters){
output += characters[i].title;
}
title.innerHTML = output;
}
}
xhr.send();
and this is the code for the right side of the page with simple div with 2 p tags
<div class="flex-shrink-1">
<div class="card bg-dark text-white">
<img class="card-img" src="img/charactersbg.jpg" alt="no image">
<div class="card-img-overlay">
<p class="card-title display-4" id="charactertitle"></p>
<p class="card-text" id="characterdesc"></p>
</div>
</div>
</div>
This is the read function which basically gets data from Database end encodes it to JSON `
include '../../config/Database.php';
include '../../models/Characters.php';
// Instantiate DB & Connect
$database = new Database();
$db = $database->connect();
// Instantiate blog post object
$chars = new Characters($db);
//Blog Post Query
$result = $chars->read();
// Check if any characters
$num = $result->rowCount();
// Check if any characters
if ($num > 0) {
// Post array
$chars_arr = [];
$chars_arr['data'] = array();
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
extract($row);
$chars_item = [
'id' => $id,
'title' => $title,
'description' => html_entity_decode($description)
];
// Push to data
array_push($chars_arr['data'], $chars_item);
}
// Turn to JSON & output
echo json_encode($chars_arr);
} else {
// No posts
echo json_encode(
['message' => 'No posts found']
);
}
I tested the read function on Postman so it works, I also was wondering if I needed to create read_single type of function which only gets one character info, but I still can't really display it on div so figuring out that is main worry
Anyway thanks in advance for answers, I would love some help :)
`
console.log() is handy for debugging AJAX methods.
In browsers like Chrome and Firefox you can open the console with Ctrl-shift-i
xhr.onload = function() {
var characters = JSON.parse(this.responseText);
console.log(characters);
Then you can read the console to see if the characters variable looks the way you expect it to and if you are parsing it correctly.
Now, from a quick read it looks like the PHP side is creating a multi-dimensional array (turned into a JSON object), while the client-side loadCharacterInfo function is expecting a one-dimensional array.
It appears that if all goes well in the PHP script, the only property of the Javascript object characters is data, which contains the characters array. If no characters are found it looks like the only property is message, which contains the error message.
i.e. On the PHP side, the top level of $chars_array only has one item, data. There is no title etc. in the top level. It is the second level, $chars_array['data'], that holds the array of characters, each with properties like title, etc.
var resp = JSON.parse(xhr.responseText);
if (resp.data) {
// resp.data should correspond to the PHP $chars_array['data']
var characters = res.data;
for (var i in characters) {
// display as you wish
}
} else if (resp.message) {
// e.g. This could be the 'No posts found' message.
var msg = resp.message; // display as you wish
}
I'm pulling deals from Groupon's api, and I have no clue how to take the data and put it into a database with php, i know how to show it on in html, but not in the database, I need to pull it into the database so I have more control over the info, if anybody knows how to do this or knows a better way, i'm all eye's, lol, thanks
<script type='text/javascript'>
$(function () {
$.getJSON("https://api.groupon.com/v2/deals.json?callback=?",
{
client_id: "b252ad3634a4ab2985b79d230ccc4e49a3ea9d19",
show: "all",
division_id: "los-angeles"
})
.done(function (data) {
console.log(data);
// do whatever processing you need to do to the data
// right here, then drop it in the div
$.each(data.deals, function (i, v) {
$title = $("<h2/>", {
html: v.title,
class: "heading"
});
$img = $("<img/>", {
src: v.mediumImageUrl
});
$deal = $("<div/>", {
html: v.highlightsHtml + v.pitchHtml
});
$("#main").append($deal);
$deal.prepend($title, $img);
});
});
});
</script>
Theory
Well I'm just gonna start running through the process...
First, know which driver you are dealing with and research how PHP interacts with them. Look at this list and start reading...
http://www.php.net/manual/en/refs.database.php
Sending the data to a PHP script to handle the rest, depends on how you got the data. Here are some basic flows...
Pull it using jQuery, and use AJAX to send it as soon as you get it to the php script to save it. (Requires an additional HTTP request)
Pull it using PHP, save it to the DB, then format and output it on the same page. (Slows down initial page load time)
Pull it with jQuery, format it, and allow the user to press a button that will then ajax that entry to the PHP save script (More flexible, but greatly increases requests)
After you can get a connection to your database you just need to save it to a table using a SQL query (most likely using INSERT or UPDATE). With JSON data, I prefer to save it to a column that has the data type of TEXT. The only real risk here is that you have to be sure that you can validate the data. ESPECIALLY IF THE DATA IS BEING GIVEN TO PHP FROM A JAVASCRIPT /AJAX SOURCE!
Pulling the data from that point is just using a "SELECT" sql statement. PHP's database modules will pull this data and put it into a lovely array for you, making manipulation easy.
Examples
Now thats the theory, heres some actions. I'm going to be choosing the 1st flow idea. Now this one will just save it to the database. I'm not doing any fancy checking or really pulling. But this will show you the idea of how ajaxing and saving to php would work.
view-deals.html
<script type='text/javascript'>
$(function () {
$.getJSON("https://api.groupon.com/v2/deals.json?callback=?",
{
client_id: "b252ad3634a4ab2985b79d230ccc4e49a3ea9d19",
show: "all",
division_id: "los-angeles"
}).done(function (data) {
console.log(data);
// do whatever processing you need to do to the data
$.post('save-deals.php',{dealData: data}, function(finishData) {
//This is an optional function for when it has finished saving
});
// Your formatting comes next
....
});
</script>
Now that will send all the data that you got (intact) from groupon to a seperate php script using an AJAX Post call. I use post, well, because that's what it's for.
save-deals.php
ob_start(); //I like output-buffering because if we need to change headers mid script nothing dies
$DealData = isset( $_POST['dealData'] )?$_POST['dealData']:die("Malformed form data!");
if($DealData!='') {
$DB = new mysqli("example.com", "user", "password", "database");
if ($DB->connect_errno) {
echo "Failed to connect to MySQL: " . $DB->connect_error;
}
$DealData = $DB->real_escape_string($DealData); //Sanitize it for MySQL
if (!$DB->query("INSERT INTO deals(data) VALUES ($DealData)") {
echo "Insert failed: (" . $DB->errno . ") " . $DB->error;
} else {
//AT THIS POINT IT SHOULD HAVE BEEN INSERTED!
//You could return a success string, or whatever you want now.
}
} else {
http_response_code("400");
die("Bad Request, please check your entry and try again");
}
ob_end_flush(); //Close up the output-buffer
Some important things to note about that script is that the ob_* functions are completely optional. The way DealData is set is a VERY shorthand way of checking that the post data contains that value, and setting it properly; if not, then to give an error.
This next script is to show you how to pull the data from the database now, and manipulate it if you want. It will also return the data as JSON information so it can be used with a javascript $.getJSON() call. This is mostly a snippet for reference
manipulate-deals.php
//First connect to the database!
$DB = new mysqli("example.com", "user", "password", "database");
if ($DB->connect_errno) die("Failed to connect to MySQL: " . $DB->connect_error);
//Get ALL the entries!
if(!$results = $DB->query("SELECT * FROM data")) die("Failed to retrieve data! ".$DB->error);
//Decode the datas!
$returnResults = [];
while($entry = $results->fetch_assoc()) {
$JSON = json_decode($entry['data']);
//Manipulate however you wish!
$JSON->whatever->tags[1]->you->want = "whatever value";
//Add it to the results!
$returnResults[] = $JSON;
}
echo json_encode($returnResults);
That very last section is just for fun. It would export a json string containing an array of results. And each of that array's entries would be a valid object just as groupon had given you. Hope that helps!
How can I use the clicked element's inner HTML in PHP as described below?
$(function () {
$(".topic-list-items").click(function () {
// document.getElementById("content-of-the-topic").innerHTML= $(this).context.innerHTML;
<?php
$dbhost = '127.0.0.1';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$conn) {
die('Could not connect: '.mysql_error());
}
// here I want to table name dynamically, that is, "SELECT id FROM table". $variable
$sql = "SELECT id FROM ";
//$ variable is the clicked element's innerHTML
mysql_select_db('entries_database');
$retval = mysql_query($sql, $conn);
if (!$retval) {
die('Could not get data: '.mysql_error());
}
?>
});
});
You need to make an AJAX call to your PHP script and have the contents of your element as a data parameter.
data: {my_data: $(".topic-list-items").html()}
Or, if you have more of them, you can grab the contents from the click function using $(this):
$(".topic-list-items").click(function () {
data: {my_data: $(this).html()}
...
})
Then you can access it from the PHP using something like $_POST['my_data'].
Here's an example:
$.ajax({
type: "POST",
url: "my_php_script.php",
data: {my_data: $(".topic-list-items").html()}
}).done(function( msg ) {
alert( "PHP says: " + msg ); // you can do whatever you want here
});
EDIT
And please stop using mysql_* functions as they are deprecated. See here: http://www.php.net/manual/en/function.mysql-query.php
Also, pay attention to SQL injection by filtering any inputs (although the input comes from the DOM element, it's easily converted into a database attack).
Your php is running server side, javascript is running client side. If you want to get those values to you php, you will need to submit them back to the server.
Check out ajax for that.
You can't just put server side php code into your client side JScript code and expect it to be executed. It can be done, though this is usually not the way it is implemented.
If you're already using JQuery, please start with using AJAX functions like jQuery.get(). It might be easier to begin with shorthand functions like jQuery.load() in order to get a first impression how these functions works. They have some good examples in the manual, too.
You could use the jquery ajax functions
//the get method
$.get('file.php', function(data) {
$('.result').html(data);
alert('Load was performed.');
});
http://api.jquery.com/jQuery.get/
//the load function
$('#result').load('file.php');
http://api.jquery.com/load/
Add a hidden form element with #hiddenElementId in your HTML then assign the value to whatever you like, and submit the form. This will post the parameter to your php target.
var myInnerHTML;
$(".topic-list-items").click(function() {
myInnerHTML= $(this).context.innerHTML;
$("#hiddenElementId").val(myInnerHTML);
$("#formId").submit();
}
I have an app that sends latitude, longitude values to my postgresql database. And i want to plot the updated points accordingly on my OpenLayers map using jquery,ajax. But here is where i am stuck at: When I click the button, the php file with database connection and saving the last entry of the table in an array is happening.
But when i try using the outputs in markers, nothing is happening.
How to use the output values of the php in my function?
Here is the code that i am trying to use.
php file:
<?php
$conn = pg_connect("host=xxx port=xxx dbname=xx user=postgres password=xxx");
$result = pg_exec($conn,"Query goes here");
$numrows = pg_numrows($result);
for($ri = 0; $ri < $numrows; $ri++)
{
$row = pg_fetch_array($result, $ri);
$data = array(); // create a variable to hold the information
$lat_latest[] = $row["latitude"];
$long_latest[] = $row["longitude"]; // add the row in to the results (data) array
}
pg_close($conn);
$js_lat = json_encode($lat_latest);
echo "var javascript_lat1 = ". $js_lat . ";\n";
$js_long = json_encode($long_latest);
echo "var javascript_long1 = ". $js_long . ";\n";
?>
My page code is :
function init(){
//openlayers map code is here.
$("button").click(function(){
$.get("dataconn.php",function(data,status){
alert("Data:"+data+"Status:" +status);
var extra_point = new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.Point(parseFloat(javascript_long1[0]),parseFloat(javascript_lat1[0])),
{some:'data'},
{externalGraphic: 'images1/marker-gold.png', graphicHeight: 16, graphicWidth: 16});
vectorLayer1.addFeatures([extra_point]);
});
});
}
</script>
</head>
<body onload='init();'>
<div id="map" style = 'width: 1075px; height: 485px'>
<button> Update </button>
</div>
and the alert i am getting when clicking update button is
Data:
var javascript_lat1 = ["output of the query"];
var javascript_long1 = ["output of the query"];
Status : success
Is the way i am trying to access the values of query output correct? Please help.
Sorry if this is a dumb question. I am new to jquery.
When your php script sends a string like:
'var javascript_lat1 = ["output of the query"];'
back to your code, that does not mean that your code has a variable called javascript_lat1 in it.
Your php script is sending strings back to your javascript code from which you must extract the information that you want to use in your code. It is up to your javascript code to know what format the strings are in. But since you wrote the php script you can send the strings back in any format you want. Then your javascript code can dissect the strings with regexes, split(), etc. to extract the parts of the strings that you want to use in your code. A very simple format that your php code could use is:
"output of query 1, output of query 2"
Then you can split() on the comma to separate the two pieces of data e.g.:
var pieces = data.split(', ');
Then you can use pieces[0] and pieces[1] in your javascript code.
Another option is to send a request to your php script using the $.getJSON() function. If you do that, your php script should send back a json formatted string, e.g.:
"{lat1: 'blah blah blah', long1: 'foo bar foo bar'}"
Then the $.getJSON() function will automatically convert the string into a javascript object and pass the js object to your callback function. Inside the callback function you can access the data using:
some_func(data.lat1, data.long1);
I've been reading and watching a lot of tutorials about javascript, jquery and AJAX but I can't seem to understand how to make a 'filter' like these guys from unlim500 have.
Their script allows you to just click on a brand and then the table gets filtered and refreshed (without reloading the page).
Live example on this page, click on Все марки:
http://www.unlim500.ru/results/
Can anyone lead me into the right direction?
How can I make such a filter?
index.php =
<a id="bugatti_link" href="#" database_id="Bugatti">Bugatti</a>
<script>
$("#bugatti_link").click(load_ajax);
function load_ajax(e) {
var link = $(e.target);
var vehicle_database_id = link.attr("database_id");
var ajax_params = {"brand": vehicle_database_id};
$.getJSON("query2.php", ajax_params, success_handler)
}
function success_handler(data) {
//data variable contains whatever data the server returned from the database.
//Do some manipulation of the html document here. No page refresh will happen.
}
</script>
query2.php =
<?php
$host = "xx";
$user = "xx";
$db = "xx";
$pass = "xx";
$pdo = new PDO("mysql:host=" . $host . ";dbname=" . $db, $user, $pass);
$rows = array();
if(isset($_GET['brand'])) {
$stmt = $pdo->prepare("SELECT brand FROM cars WHERE brand = ? ");
$stmt->execute(array($_GET['brand']));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
echo json_encode($rows);
?>
The actual page you linked uses an anchor to create a link to some javascript. The way I have done this in the past (and imo a simpler way) is to make a link without href pointing to the same page (to avoid reload), and attach a click event to the link which will trigger your ajax call.
eg - HTML - the link to click
<a id="bugatti_link" href="#" database_id="2">Bugatti</a>
then in jquery
$("#bugatti_link").click(load_ajax);
function load_ajax(e) {
var link = $(e.target);
var vehicle_database_id = link.attr("database_id");
var ajax_params = {"id": vehicle_database_id};
$.getJSON("the/url/to/the/database/view", ajax_params, success_handler)
}
function success_handler(data) {
//data variable contains whatever data the server returned from the database.
//Do some manipulation of the html document here. No page refresh will happen.
}
On the server you'll receive a GET request to the/url/to/the/database/view which will have a parameter called "id" with the value of "2" so you can fetch vehicle at row 2 and return whatever data you wanted from that vehicle.
Hopefully that gives some insight into how to turn a regular link into an ajax loader, which can be used to update the page without reloading it.
Some useful links about this sort of thing:
jQuery ajax calls
and more useful for this sort of usage, jQuery getJSON
You can use a jquery plugin for the sorting functionality. One of which is the tablesorter plugin
All you have to do is to download jquery and tablesorter.js then include them in your page. The code below assumes that you have jquery and tablesorter on the same folder where you have the file that you're running:
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="tablesorter.js"></script>
Add an id to your table:
<table id="myTable">
Then use the tablesorter on document load:
<script>
$(function(){
$("#myTable").tablesorter();
});
</script>