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 :)
Related
I want to make dynamic select options based on database values.
I am getting id when user select an option, I get this id in ajax and then this id is passed in PHP. In PHP I run SQL query based on provided id. Now I want to send response back in AJAX and then I will append my next select option with the given response.
This is my AJAX, from this code I am passing selected_val in PHP.
`
$(document).ready(function() {
$(".sdpt").change(function(){
let deptid = $(this).val();
console.log(deptid);
$.ajax({
method: "POST",
url: "joins.php",
data: { selected_val: deptid },
success: function(response){
console.log(response);
}
});
});
});
`
In PHP, I am getting data (pro_name) from database and adding it in an array. I want to return this array in ajax and then I will use it there. Now it is return the whole PHP code in response. Please guide where I am doing mistake and what is the alternative.
`
if (isset($_POST['selected_val']) ) {
$value = $_POST['selected_val'];
$myq = new Database();
$result = $myq->sql("SELECT * FROM programs where dept_id=$value");
$arr = array();
while($row = mysqli_fetch_assoc($result)){
$arr[] = $row['pro_name'];
};
echo json_decode("Google");
}
`
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.
I try to use jQuery ajax call to retrive some data via php script.
Script take from mysql table all values of column 'rezhour' what also based on $_GET variable.
Then he print all finded values via json_encode() function
PHP:
<?php
header('Content-type: application/json');
$fromdate = $_GET['fromdate'];
$getrezhiredh = mysql_query("
SELECT rezhour FROM rezhiredhours
WHERE rezdate = '".$fromdate."' ORDER BY rezhour
");
$i=0;
$data = array();
while($row = mysql_fetch_array($getrezhiredh)){
$data['hours'][$i] = $row['rezhour'];
$i++;
}
$result = array(
$data
);
print json_encode($result);
?>
When script is called from browser adress bar all is fine and in we have correct result as below:
[{"hours":["2","9","13","14"]}]
Each digit in result above corresponds selected table row.
The problem is when i want to do the same via ajax.
jQuery:
<script>
var date = jQuery('input').val()
jQuery.ajax({
type: "GET",
dataType: "html",
data: "fromdate="+date,
url: "script.php",
success: function (data) {
console.log(data);
},
});
</script>
Now all is fine only when mysql query return result with one row and this looks in console like this:
[{"hours":["1"]}]
When mysql query return result with more than one row console show this:
[[]]
For me is really weird that jquery ajax call have problem to print correct result when we have more than one rows with selected data.
What i must do to have the same result in AJAX?
EDIT:
I found an important clue. The problem is WHERE clause in MYSQL query. When u remove from query this clause, php script return data from entire table and now ajax can print into console all selected values from specifed column.
The problem is i must use WHERE clause to load only data from before selected date at the website. Any idea how to do this?
If you want to return json data ,must use dataType:json. Valid data format is data :{key:value},...
var date = jQuery('input').val();
jQuery.ajax({
type: "GET",
dataType: "json",
data: {fromdate : date },
url: "script.php",
success: function (data) {
console.log(data);
},
});
Here's the values I am sending to the PHP script from the Javascript:
$('.verdi_knapp').click(function() {
$(this).siblings().removeClass("aktiv_verdi"); // ta vekk aktiv på de andre alternativene
$(this).addClass("aktiv_verdi"); // sett denne til aktiv
var min_id = $(this).attr('id').split("_")[1];
var aktuelle_verdier = []
$('.aktiv_verdi').each(function() {
aktuelle_verdier.push($(this).attr('id').split("_")[1]);
})
console.log("disse verdiene skal vi spørre etter", aktuelle_verdier)
$.ajax({
url: "oyvind_liste.php",
data: {aktuelle_verdier},
dataType: "json",
success: function(result){
console.log(result);
}});
This is the PHP script which queries a set of values from an SQL database and prints them to the console in the javascript:
$ids = $_GET['aktuelle_verdier'];
$value = implode(", ", $ids);
$antall = count($_GET);
$sql = "SELECT `art_id`
FROM `art_has_verdi`
WHERE `verdi_id` IN (".$value.")
GROUP BY `art_id` HAVING COUNT(*)=".$antall.";";
$result = mysqli_query($conn, $sql);
$arter_igjen = array();
while($row = mysqli_fetch_array($result)){
array_push($arter_igjen, $row['art_id']);
}
echo json_encode($arter_igjen);
What I am trying to find out next is how to send this array: $arter_igjen, which contains a set of IDs, to another page where I can run a query to the database for all the data containing these IDs and print them out in a list.
$.ajax({
url: "oyvind_liste.php",
data: {aktuelle_verdier: aktuelle_verdier},
dataType: "json",
success: function(result){
console.log(result);
}});
Please check data Paramter in ajax call. You forgot to pass key in JSON.
If I understand you right you like after ajax return you clone the window and in new one window you will make some new searches, but on the current one will be generate a log. In cas I'm understand you right, then why don't try to generate form on fly by with returned data end post it to the _blank window.
$.ajax({
url: "oyvind_liste.php",
data: {aktuelle_verdier},
dataType: "json",
success: function(result){
// Here you have to generate the form on fly
// Include hidden fields, containing your result data
// and finally send form with action some new.php on blank_ target
console.log(result);
}});
If the other page contains code like in this one (not in a class or function), you can just include it (include_once "..."), but it is not recommended that you just keep scripts like that.
Instead, encapsulate your code (put it within functions and classes). This will allow you to freely insert your scripts (include_once "...") and call these functions or create classes that will work.
Also, try to avoid too many http requests. If that list of ids won't be needed, do all of the work in the php scripts and return the needed result.
There are a few issues with your code. If you are just starting with PHP I would suggest you read:
PDO: Creating a connection
PDO with prepared statements (prevents SQL injections)
User-defined functions (I don't have enough reputation to put the link. Search: "w3schools php 5 functions")
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();