How do I transfer data from JavaScript to PHP? - php

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();
}

Related

How can i change a SELECT query using AJAX call

I'm very new to php and SQL so i'm really sorry if this is very trivial.
My site has multiple divs with table names inside it. The HTML is of the form:<p class="listname">(table name)</p>
I am trying to write a function so that when a user clicks on a div, the function gets the text using innerHTML and the contents of that particular table are shown.
The jquery function i wrote is:
$(document).ready(function(){
$(".listname").click(function(){
var x=($(this).html()).toLowerCase(); //this assigns the text in the class listname to the variable x
console.log(x);
$.ajax({
url: 'http://localhost/fullcalendar/events.php',
data: {name:x},
type: "GET",
success: function(json) {
}
});
});
});
And my PHP code is:
<?php
include 'ChromePhp.php';
ChromePhp::log('php running');
$json = array();
if($_POST['name']!=null)//check if any value is passed else use default value
{
$table=$_GET['name'];
ChromePhp::log($table);
}
else
{
$table= 'event';
ChromePhp::log($table);
}
$requete = "SELECT * FROM `$table` ORDER BY id";
try {
$bdd = new PDO('mysql:host=localhost;dbname=fullcalendar', 'root', 'root');
} catch(Exception $e) {
exit('Unable to connect to database.');
}
// Execute the query
$resultat = $bdd->query($requete) or die(print_r($bdd->errorInfo()));
// sending the encoded result to success page
echo json_encode($resultat->fetchAll(PDO::FETCH_ASSOC));
?>
When i first load the website, the default value for $table is used in the query, and data is retrieved. However, when i try clicking on a div, the correct value is passed to php and assigned to $table (i checked in the console) but the data displayed is of the default table i.e 'event' table.
How can i fix this?
PS: all my tables are in the same database.
You're checking the POST data:
if($_POST['name']!=null)
But using GET data:
type: "GET"
So the $_POST array will always be empty and your if condition will always be false. You probably meant to check the GET data:
if($_GET['name']!=null)
Also of note are a couple of other problems in this code:
Your success callback is empty, so this AJAX call isn't going to actually do anything client-side. Whatever you want to do with the returned data needs to be done in that success function.
This code is wide open to SQL injection. It's... very unorthodox to dynamically use table names like that. And this is probably an indication that the design is wrong. But if you must get schema object names from user input then you should at least be taking a white-list approach to validate that the user input is exactly one of the expected values. Never blindly execute user input as code.

delete checked table rows with ajax

I have checked through numerous questions to find the solution. I know I'm close, but I'm still not getting anything happening with my deleteData.php after confirming to delete.
Status:
Testing the array provides successful result.
Example: I checked rows 1, 2 & 31...then press #btn_del.
First, I get the confirm "Are you sure...?"
Next, I see the correct alert(array) 1,2,31
The next step...ajax is supposed to be sending this array data to deleteData.php for processing.
script
$('a#btn_del').click(function(e) {
e.preventDefault();
page = $(this).attr("href");
ids = new Array()
a = 0;
$(".chk:checked").each(function(){
ids[a] = $(this).val();
a++;
})
// alert(ids);
if (confirm("Are you sure you want to delete these courses?")) {
$.ajax({
url : 'deleteData.php',
data : ids,
type : "POST",
//dataType : 'json',
success : function(res) {
if ( res == 1 ) {
$(".chk:checked").each(function() {
$(this).parent().parent().remove();
}) // end if then remove table row
} // end success response function
} // end ajax
}) // end confirmed
}
return false;
}); // end button click function
}); // end doc ready
deleteData.php
<?php
require_once('config.php'); // Connect to the database
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
or die ('Error connecting to MySQL server.'.$dbc);
foreach ($_POST['ids']
as $id) {
$sql = "DELETE FROM unit_genData
WHERE unit_id='" . $id . "'";
$result = mysqli_query($sql)
or die(mysqli_error($dbc));
} // end echo result count
mysqli_close($dbc); // close MySQL
echo json_encode(1);
?>
Edited:
Updated GET to POST.
Updated data: 'ids' to data: ids
Tested:
a) In php...echo $_POST['ids'];
NO RESULT
b) In js...commented out the if(confirm...
NO RESULT
Status:
Looks like the AJAX isn't firing (so to speak)
First of all, I would use POST instead of GET for a delete.
Then you need to send the correct data to your php script. What you have now is just a string, no key-value pairs which is what you expect at the backend.
The easiest way to send your data would be to use something like (assuming you have a form):
data: $('form').serialize(),
but you can also send an array like the one you are building:
data: ids,
The advantage of the first method is that values automatically get escaped / encoded (wouldn't make a difference with just integers obviously...).
At the backend you would need to prevent the sql injection problem you have now. You can do that using a prepared statement with bound parameters or in the case of numeric ID's you can cast them to integers.
Edit: As noted in the comments by #Fred-ii-, additional spaces in a string will cause your condition to fail. I would recommend a prepared statement but if you decide to cast to int and use that, just remove the quotes.
Also note that the procedural mysqli_* functions take the database link as the first parameter, that applies both to the query and to the error handling.

$.ajax query not posting to PHP

I've spent the better part of today trying to send a jQuery variable to my PHP file and use it in a SQL search. My first issue is that can't even get the variable into PHP properly. I am also getting an error about some of my SQL code which I've included as well.
What I want: the variable in jQuery called name sent to the PHP file where it is used in an SQL Query to find the real name of musicians. the real name would then be sent back to the HTML file where it is displayed on the webpage. MyPHPAdmin and my database has already been setup.
jQuery:
$('li').click(function () {
var name = $(this).text();
$('#prf').attr("class",name);
$('#pic').attr("class",name);
$('#info').attr("class",name);
JSON.stringify (name);
$.ajax({
type: "POST",
url: "ajax-name.php",
data: {name: name}
})
PHP:
$rname = $_POST['name'];
var_dump($rname);
try {
$db = new PDO('mysql:dbname=dbname;host=myhost;charset=utf8', 'user', 'pass');
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query="SELECT realname FROM artistmaster WHERE stagename = :name";
$stmt = $db->prepare($query);
$stmt->execute(array("name"=>$rname));
var_dump($rname);
echo 'Success';
$result=$stmt->fetchAll();
print "<pre>";
print_r($result);
print "</pre>";
}
catch(PDOExeception $e)
{
echo $e->getMessage();
}
OUTPUT:
NULL NULL
I've read the documentation on $.ajax() and still can't figure out what I'm doing wrong. I appreciate any help on this, it's been giving one hell of time.
To evaluate the output of the PHP script from the AJAX request add a return handler to your request:
$.ajax({
type: "POST",
url: "ajax-name.php",
data: {name: name}
}).always(function( html ) {
console.log(html); // this will show the content of the php script in the developer console of your browser
});
The function defined in .always() is called every time an AJAX request finishes. When you made sure that your code works you can change it to .done(), which is only called when the AJAX call is successfull. You can also add a .failure() function to handle errors gracefully.
Also note this from the documentation:
The $.ajax() function underlies all Ajax requests sent by jQuery. It is often unnecessary to directly call this function, as several higher-level alternatives like $.get() and .load() are available and are easier to use.
I'd suggest to use the $.post function instead:
$.post("ajax-name.php", {name: name}, function( html ) {
$('#outputdiv').html(html);
// this will replace the content of a <div id="outputdiv"></div> with the output of the AJAX request
});
Try this:
$.ajax({
type: "POST",
url: "ajax-name.php",
data: {name: name},
success : function(html) {
// html code, do something with it here
}
});
then
$rname = $_POST['name'];
$query="SELECT realname FROM artistmaster WHERE stagename = :name";
$stmt = $db->prepare($query);
$stmt->execute(array("name"=>$rname));
You get your result with
$stmt->fetchAll();
You don't retrieve PDO driver results with mysqli
alert variable name in javascript and make sure it is not null.you may use exit;
echo $_POST['name'] in the php file.receive the processed data in javascript with the success:function(result) and alert it.
store every data in a single variable in the php file. and finally echo them.

trying to put api data in database with php?

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!

Display data from database without refreshing (Javascript)

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/.

Categories