How to write this query with this id? - php

How can I add this data-id in query line
<li><a data-id="<?php echo $random_id;?>">Show</a></li>
In my case I can not add $random_id here. I have to use the data-id.
simply I need to select from posts where id is equal to data-id.
How can I write it down ?
$query = "select * from posts where id='???' ";

You cannot get this data-id attribute value in your php code directly. You have to use Jquery, Ajax to use this like:
var dataId = $('a').attr('data-id');
or
var dataId = $('a').data('id');
Now make an ajax() call and pass this value as an parameter in that call.

In order for you to make this happen - I believe - you have to use AJAX.
The code will look like this:
$.ajax({
url: 'your_script.php',
type: 'POST',
data: {var1: javascript_var_1, var2: javascript_var_2},
success: function(data) {
console.log("success");
}
});
Your PHP will look similar to this (without keeping in mind the JSON encode:
<?php
$var1 = $_POST['var1'];
$var2 = $_POST['var2'];
$getvalue="SELECT id,name from table1 WHERE column1='$var1' and column2='$var2'";
$result=mysql_query($getvalue) or die(mysql_error());
while($row=mysql_fetch_array($result)){
extract($row);
echo $name;
}
?>
Then you can JSON encode the results and pretty much output them on the success. Your php script - however - must live on another php file.
Also, escape your data. Use prepared statements.

Related

How to declare the value of id as a variable in phpMysql

From the below code I need to display the values of data1. I have declared it by using id as "id="data1". Suggest me how to pass this "data1" as a variable in phpMysql.
<div class="col-lg-12">
<p id="data1"></p>
<?php
// Make a MySQL Connection
mysql_connect("localhost", "projects", "pwd", "projects") or die(mysql_error());
mysql_select_db("projects") or die(mysql_error());
$var='data1';
// Get all the data from the "Race" table and create table
$result2 = mysql_query("SELECT
A.service_center_name,
A.status,
C.branch_name
FROM
customers A
INNER JOIN
ascs B ON A.serv_cent_mob_no = B.contact_number
Inner Join
branches C on B.branch_id=C.id
where C.branch_name='". $var. "'
GROUP BY A.service_center_name ,A.status,C.branch_name;")
or die(mysql_error());
echo "<table border='1'>";
echo "<tr> <th>Service Center Name</th> <th>City</th> <th>Branches</th> </tr>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result2 )) {
// Print out the contents of each row into a table
echo "<tr><td>";
echo $row['service_center_name'];
echo "</td><td>";
echo $row['branch_name'];
echo "</td><td>";
echo $row['status'];
echo "</td></tr>";
}
echo "</table>";
?>
</div>
How to pass the data1 using variable in the below code "$var='data1';".
Solution:
You can use the jQuery AJAX function to parse the data to the desired file of your choosing. More about jQuery AJAX here.
Your AJAX function could look like so:
function postData() {
var data = $('#data1').html();
$.ajax({
type : "POST",
url: "/some/path/some_page.php",
data: { dataVariableName : data },
success: function (html) {
//Success handling
}
})
}
You could then fire the function from a button. For instance:
<button onclick="postData();">Submit data!</button>
In your some_page.php, you will then need to access your POST variable, like so:
<?php
$var=$_POST['dataVariableName'];
//Continue with SQL logic etc.
?>
Explanation:
What we basically did here, is that we encapsulated the AJAX function into another function named, postData, which we can use to call onclick, or however we desire. We could also simply add an onclick event to the ajax function directly, but I thought this would make for an easy understanding.
We then go on to define a variable that contains the data we wish to parse.
Then in our AJAX function, we first define our data type. As you can see in this example, we're using the data type POST. There are other data types that you can define here, and each for a different purpose. Another well-known data type would be GET for instance. I suggest you look up the data types to find out what they mean, and what influence they have. For instance, GET types will show as parameters in the URL.
Next we define what page we are sending our data to, which will be some_page.php in our example.
We then go on to define our POST variable, which is going to contain the data we're supposed to parse. You can parse more than one variable at a time in your AJAX function, by doing so:
data: {
dataVariableName : data,
dataVariableName2 : otherData,
//more variables [...]
},
Note that I also defined a success function in our AJAX function. We can use this to do a lot of things upon success, if we so desire. I.e. redirect to another page, alert(); a success message etc. etc. A lot of things.
If you run into trouble with the SQL, let me know, and I can take a look at that as well.
Important note:
You should really consider switching to mysqli_* or PDO, instead of using the deprecated mysql_* notation. You won't be able to use the mysql_* notation in the newer version of PHP, i.e. PHP 7.0 and forward. You should also look into prepared statements and sanitizing your inputs in general, in case you continue with the mysql_* notation.
using Jquery you can get the data in p tag like below
var pdata = $('#data1').html();
you can post this data to php using jquery Ajax as below
request = $.ajax({
url: "/form.php",
type: "post",
data: pdata
});
In your php, you can make it as
$var = $_POST['data'];

How can i pass two values from select box using AJAX

Hi i have the following code but i am not able to access the values in my request.php file from this.
$(document).ready(function(){
$("select.location").change(function(){
var Did = $("input[name='district']").val();
var selectedLocation = $(".location option:selected").val();
$.ajax({
type: "GET",
url: "request.php",
data: {location : selectedLocation, Did:Did},
}).done(function(data){
$("#response").html(data);
});
});
});
and my request.php is calling the data like this
if(isset($_GET["location"]))
{
$i=0;
$bfrom = $_GET["location"];
$did= $_GET["Did"];
$sql = "SELECT distinct stopname FROM `route` WHERE `rfrom` LIKE '$bfrom' and did=$did";
$result = $conn->query($sql);
first off, and most importantly, for security you need to parameterize your query. See PHP: Prepared statements and stored procedures
Secondly, your LIKE argument needs to be preceded and followed by % - eg '%$bfrom%' - this enables "wildcard" data search MySQL Wildcards
Lastly, you need to echo a response in the AJAX call, in order for the receiving javascript to pick it up :)

How can you pass a sql query through ajax?

I have sql query I need pass through to an ajax file.
$qry = mysqli_query($this->con,"SELECT * FROM products");
I have contained the variable in html such as:
<input type="button" data-qry="'.$qry.'" id="button" value="click">
I use the ajax jquery code below to pass it through:
$('#button').click(function(){
array = $(this).attr('data-qry');
$.ajax({
type : 'POST',
dataType : 'json',
url : 'ajax.php',
data : 'qry='+qry,
success : function(data) {
$('#result').html(data);
}
});
});
I want to be able to open ajax.php and perform
$qry = $_POST['qry'];
$row = mysqli_fetch_assoc($qry);
Of course this is not working. How can I pass the query through, does it need to be done through JSON some how?
At the start of your button you assign the value to the variable array
array = $(this).attr('data-qry');
But you send qry with the ajax
data : 'qry='+qry,
The way you fix this is by sending the variable you assign the value to

variable in jquery function is null

I am having a problem with seeing one of my variables on a webpage. Here is what I have so far.
$(document).ready(function() {
$(function() {
$("#CheckID").click(function() {
// submit ajax job and display the result
var id = '$("#ID").val()'
$.ajax({
type: "POST",
url: "test_wID.php",
data: "id",
success: function(data) {
$('#rightselection').html(data)
}
});
});
});
});
This is the jquery function I am using to take an ID entered into a form and use that ID with a bash script.
Here is the php.
<?php
//Get the ID from the HTML form and use it with the check chunk script.
$id = $_POST['ID'];
if (is_null($id)){
echo "$id is null";
}
echo "Selected test Game ID: ".$id;
//print shell_exec('/opt/bin/tester $id');
?>
I commented out the script because the variable is returning null, at this point I am just trying to make sure that I get the ID.
For completeness here is the form I'm using.
print "<p><h3>ID: <input type=\"text\" id=\"ID\" /></h3></p>";
#print "<br>";
print "<p><button id=\"CheckID\">Check ID</button></p>";
When i click the button I get the message in my div that the variable is null. So my question is am I missing something in the declaration? How is it that the var id is null?
Thanks for any help provided.
You should consider changing your jQuery code to:
$.ajax({
type: "POST",
url: "test_wID.php",
data: {id: $("#ID").val()},
success: function(data) {
$('#rightselection').html(data)
}
});
You mixed up strings and variable references at two points.
First, the statement var id = '$("#ID").val()' assigns just a string to your if variable and not the return value of the jQuery call. So just remove the ' here.
Second, the data parameter you're giving to the ajax() call again consists just of a string "id" and not the respective value. Here you need to change to {'id': id}.
So after correcting everything, your code should look like this:
$(document).ready(function() {
$("#CheckID").click(function() {
// submit ajax job and display the result
var id = $("#ID").val();
$.ajax({
type: "POST",
url: "test_wID.php",
data: {'id': id},
success: function(data) {
$('#rightselection').html(data);
}
});
});
});
Sidenote: Try to put all ;, where they belong. This prevents some errors, which can be hard to track!
EDIT
As pointed out in the comment by #FlorianMargaine you only need one wrapper not two around your code.
Firstly, the two following snippets are equivalent:
$(document).ready(function() {
});
// Is equivalent to:
$(function() {
});
So your code does the same as:
$(document).ready(function() {
$(document).ready(function() {
});
});
Plain useless, right?
Secondly, this line is plain wrong:
var id = '$("#ID").val()';
You're passing a string to the id variable. $('#ID').val() is not evaluated. This is the equivalent of doing this in PHP:
$id = '$_POST["id"]';
Which is just wrong, right?
You want this:
var id = $('#ID').val();
By the way, this variable naming could be improved, the same goes for the HTML ID.
Thirdly, you're doing the same mistake in the data option of $.ajax:
data: 'id'
You're just passing a string to the data option. You want the value of the id variable.
Then, if you absolutely want a string, I don't recommend it. jQuery expects a special kind of string. You better pass an object. Like this:
data: {
id: id
}
Do you see why the variable naming is wrong? You can't differentiate the property from the value. If you had done the following:
var idValue = $('#ID').val();
You could use this:
data: {
id: idValue
}
Which is way more readable.
In your $.ajax call you need to do:
data : { id: id }
If you want to pass parameters in an AJAX call you need to pass a string similar to the GET string you see in urls. So something like: d=123&name=test
Change the line
var id = '$("#ID").val()'
To
var id = 'id=' + $("#ID").val();

Better approach for displaying two PHP variable switch jQuery Ajax

I'm getting two random values from a table. The values are in the same row.
<?php
$result = mysql_query("SELECT * FROM people ORDER BY RAND() LIMIT 1", $connection);
$row = mysql_fetch_array($result);
echo $row["name"];
echo $row["surname"];
?>
And I want to display these two values at different div's on my HTML page by using jQuery Ajax functions.
$(function()
{
$("#sentence-form").submit(function()
{
$.ajax(
{
type: "GET",
url: "newperson.php",
success: function(response)
{
$("#top-container").append(response); /* Both name and surname */
}
});
});
});
The problem is separating two values to display different in div's. I tried to use two Ajax calls and I send boolean data to PHP to use with an if statement. So one of the Ajax calls displays name and the other one displays surname. But because of randomization, it's a bit complicated to find surname of a name.
What is a better approach?
Yes: send the data in a data structure – probably JSON – so your client-side code knows which bit is which.
First, send the data with PHP's json_encode function:
echo json_encode(array(
'name' => $row['name'],
'surname' => $row['surname']
));
Then use your browser's ability to parse JSON:
$.ajax({
type: "GET",
url: "newperson.php",
dataType: 'json',
success: function (response) {
$("#name-container").append(response.name);
$("#surname-container").append(response.surname);
}
});
response is now a Javascript object (something like {name: 'John', surname: 'Smith'}), so you can access the two parts as normal object members.
Send the variables as a JSON array
<?php
$result = mysql_query("SELECT * FROM people ORDER BY RAND() LIMIT 1", $connection);
$row = mysql_fetch_array($result);
$output['name'] = $row["name"];
$output['surname'] = $row["surname"];
echo json_encode($output);
?>
And on the JavaScript code, access it as:
data.name and data.surname
Although I like lonesomeday's answer, and I think that that is the way to go, I will post the alternative:
Relevant PHP:
echo $row["name"].'||'.$row["surname"];
Relevant JavaScript code:
success: function (response) {
var parts = response.split('||');
$("#name-container").append(parts[0]); //name
$("#surname-container").append(parts[1]); //surname
}
Use this:
<?php
$result = mysql_query("SELECT * FROM people ORDER BY RAND() LIMIT 1", $connection);
$row = mysql_fetch_array($result);
echo $row["name"]."&".$row["surname"];
?>
$(function(){
$("#sentence-form").submit(function(){
$.ajax({
type : "GET",
url : "newperson.php",
success : function(response){
items=response.split('&')
$("#top-container").append(items[0]); /* name */
$('#bottom-container").append(items[1]); / /*s(u should be i)rname */
}
});
});
});

Categories