Need to pass value of php in jquery script - php

I need to pass the PHP retrieved value from database to Ajax function for further querying in database my code is given below.
The PHP Script:
$query = mysql_query("SELECT * FROM employee") or die(mysql_error());
while($res=mysql_fetch_assoc($query)){
echo $res['emp_id'];
$emp_id=$res['emp_id']
and submit button with id name-submit
The Javascript
$('input#name-submit').on('click',function(){
var empid = $('php echo $emp_id; ');
alert(empid);
the script is running just below the php script.

Exactly as you are doing, but by putting the full opening tag in there. Change the second JS line to:
var empid = $('<?php echo $emp_id; ?>');

Related

filter Query data with from html value input

I have an HTML page with a filter that basically lists car names. When the user selects a value in the filter, I want to show the data associated to that value which comes from my PostgreSQL database. I have attached the code below. At the moment when the user is presented with the page and selects a value from the filter nothing is currently appearing not sure why. Any help welcome thank you
<html>
<select id="filter">
<option>All</option>
<option>BMW</option>
<option>Mercedes</option>
</select>
<?php
$db_connection = pg_connect("host=localhost dbname=postgres user=postgres password=postgres");
$feild_value = $_POST["filter"];
// you can use this $feild_value variable in query;
$result = pg_query($db_connection, "SELECT * from cars where car_name= $feild_value;");
//echo query result here
while($row = pg_fetch_array($result))
echo $result;
die;
?>
<script>
$(document).ready(function()
{
var value = $("#filter").val();
$.ajax({
type:"POST",
data:{"filter":value},
success:function(result){alert(result);}
})
});
</script>
</html>
I'm not sure about your code but your ajax function will not work on the filter change if you didn't call it in on change even, and make sure to put a submit URL to the ajax call and I hope your PHP script is in a separate file if not your script will not run after the die()
$('#filter').on('change',function(e){
//put your ajax submit here
});
There are couples of things with your code that you should be aware of.
Firstly, the die() function will stop the PHP code before the rest of the code is executed and outputted.
Secondly, $result = pg_query($db_connection, "SELECT * from cars where car_name=$feild_value;"); should be
$result = pg_query($db_connection, "SELECT * from cars where car_name='$feild_value;'");
Note the single quote around the $field_value in the SQL statement.

Inserting non-form data into database using jQuery

I have a function in JavaScript with the following parameters below:
insertdata(micheal, newyork)
I want to be able to insert thus:
name = micheal
location = newyork
into my MySQL database using PHP and jQuery.
Both items of data are not coming from a form. I'm only passing them from JavaScript.
Since I cannot comment due to reputation, I suggest you a solution that through jQuery you can append this to your current form as hidden fields and these get submitted at the PHP backend and you can save it in your DB.
Let me know if you need help on how to append it to the form.
var name = $("<input type='hidden' name='whatever' value='micheal' />");
$("#myform").append(name);
Also have a look at this
Add elements using jQuery dynamically
To process this in PHP see this,
$variable_name_1 = $_POST['name_of_form_field_1'];
$variable_name_2 = $_POST['name_of_form_field_2'];
//Read how to sanitize variables
$query = "INSERT INTO table_name (field1, field2) VALUES ('$variable_name_1', '$variable_name_2')";
$result = mysqli_query($query);
if(!$result) {
echo "Error" . mysqli_error();
}
else {
echo "Done!";
}
You can have a snapshot of your form submitted by doing this var_dump($_POST)

php variable through jquery ajax to external php

i found a php/jquery/ajax script that has a textfield that is sent after the user clicks the input to an external php script to be written into a mysql database.
http://gazpo.com/2011/09/contenteditable/
whats missing is the userid passed into the external php file:
$sql = "UPDATE customer SET comment = '$content' WHERE userid = 12345 ";
here is what i do:
i am catching the user id in the main file with:
$s = $_GET['contact'];
from the url parameter.
then i put it in to my db select in the main php:
$sql = "select customer from user where userid = $s";
then there are some div
<div id="content">
<div id="editable" contentEditable="true">
followed by the ajax script:
$(document).ready(function() {
$("#save").click(function (e) {
var content = $('#editable').html();
var content_two = $('#editable_two').html();
$.ajax({
url: 'save2.php',
type: 'POST',
data: {
content: content
},
in the save.php there is this:
$content = $_POST['content']; //get posted data
$sql = "UPDATE customer SET comment = '$content' WHERE userid = "XXXX" ";
So: how do i get the $s variable from my url parameter into the "XXXX"
As others pointed out in comments that seem to be quitly ignored , you really need to check this out, since the way you build your query is very insecure. Please read about SQL injection.
Add userid to the data you pass from your ajax call back to save.php.
data: {
content: content,
userid: <?= $s ?>
}
This is a guess without seeing the rest of your code and how the code actually renders the page.
Thanx alot for the hint.I changed theses lines:
In Ajax/Jquery section of the main php file:
$("#save").click(function (e) {
var content = $('#editable').html()
var nr = <?php echo $s; ?>;
$.ajax({
url: 'save.php',
type: 'POST',
data: {
content: content,
nr: nr
}
And in the external save.php i added this:
$s = $_POST['nr'];
and also included the variable into $s into my sql update section:
$sql = "UPDATE ADRESSEN SET BEMERKUNG = '$content' WHERE NR = $s ";
This is for a telefonsoftware, when somebody calles me up the software is opening a webpage with the main.php and this variable is using the sql select to show the customer informations, then i write a commend into the editable field and it gets written back into my sql databbase.
So! If somebody is looking for a way to path a url command variable via $_get into a php and then into ajax bach into an external file, i hope he google finds this keywords and is showing this page to help him :)
here its in short:
www.url.com/?contact=12345
php catch url parameter:
$s = $_GET['contact'];
sql select:
$sql = "select user, userid from customer where userid = $s";
in AJAX/jquery ad:
var nr = <?php echo $s; ?>;
and later on
nr: nr
in external save php:
$content = $_POST['content']; //get posted data
and
$sql = "UPDATE customer SET comment = '$content' WHERE userid = $s ";

MySQL database populated dropdown box and PHP search

I have question regarding search on webpage with textbox and dropdown box.
I have table with fields:
ID
First name
Last name
Company name
Occupation
Description
Now i need to make search form which will be populated from database (field Occupation) and textbox where I can put whatever I want, and then get results from database based on those on web page.
I am really sorry but i am totally begginer and only need some examples of such kind of code and much help :)
Thank you
You're going to want to use AJAX to call a php script from your page and then use the php script to query your database and to echo the results back to the page.
I'm going to use jQuery for this example because it saves a lot of lines, you should check it out if you haven't already.
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type="text/javascript">
function searchOccupation () {
$.ajax({
url: "searchOccupation.php?search=" + $('#searchTxt').attr('value'),
success: function (data) {
alert(data);
}
});
}
</script>
</head>
<body>
<input type="text" id="searchTxt">
<input type="button" value="Search" id="searchBtn" onclick="searchOccupation()">
</body>
Then your php script (whose name should match that in the "url" field of the ajax call (in this case it should be named "searchOccupation.php") will look like this:
<?php
$searchTxt = $_GET['search'];
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$con = new mysqli('server', 'user', 'password', 'database');
$sql = "SELECT * FROM tableName WHERE occupation = ?";
$stmt = $con->prepare($sql);
$stmt->bind_param('s', $searchTxt);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {
echo $row['firstName']; //This sends data back to the page
}
?>
The echo part of the php script is what sends data back into the "success: function (data)" of the javascript, so echo whichever field you want on the page as above.
Edit: Slightly misunderstood what you meant, ajon's above is probably what you need.

Updating HTML Element Every Second With Content From MySQL Database

I'd like to have a div on my web page that is based off of the data in my MySQL database. When the data in the database changes, the content in the div should change as well.
Example: Let's say I have a field in the first row of a table called "server_statistics" in my MySQL database which keeps track of a server being online or offline. When the server goes offline, the MySQL field changes from 1 to 0. When it goes online, it goes from 0 to 1.
So I want to use Javascript to display the server status on my webpage and update it without refreshing the page.
I thought I'd be able to do it like this:
<script type="text/javascript">
var int = self.setInterval("update()", 1000);
function update() {
var statusElement = document.getElementById("status");
var status = "<?php
$con = mysql_connect("localhost", "root", "");
mysql_select_db("database_name", $con);
$row = mysql_fetch_array(mysql_query("SELECT * FROM server_statistics LIMIT 1"));
mysql_close($con);
echo $row[0]; ?>";
if (status == 0) {
statusElement.style.color = "red";
statusElement.innerHTML = "offline";
}
else {
statusElement.style.color = "green";
statusElement.innerHTML = "online";
}
}
</script>
But this doesn't work. The page needs to be refreshed for it to update and I don't know why...
I've read I can use JQuery but I have no knowledge of this language at all.
I tried this:
<script type="text/javascript">
var int = self.setInterval("update()", 1000);
function update() {
$('#status').load('load.php');
}
</script>
and then in load.php I had this:
<?php
echo "test";
?>
But nothing happened after 1 second passed. I'm probably doing it wrong because as I said, I don't know anything about this JQuery/AJAX stuff.
So how can I accomplish retrieving a field from a MySQL database at every specified interval and then automatically update an HTML element accordingly? It would be ideal to only update the HTML when a change occurred in the database but for now, I just want it to change every few seconds or minutes...
Thanks in advance.
What you need to do is utilize AJAX. Your page will need to make a request to the server each time it wants to check the status. There are two ways to do it: manually refresh the page yourself, or use an AJAX call.
AJAX really isn't all that difficult, you start by creating a separate PHP page check_status.php with the following in it:
<?php
$con = mysql_connect("localhost", "root", "");
mysql_select_db("database_name", $con);
$row = mysql_fetch_array(mysql_query("SELECT * FROM server_statistics LIMIT 1"));
mysql_close($con);
echo $row[0]; ?>
Then, in your HTML page, the easiest way to do this would be to use jQuery:
var statusIntervalId = window.setInterval(update, 1000);
function update() {
$.ajax({
url: 'check_status.php',
dataType: 'text',
success: function(data) {
if (parseInt(data) == 0) {
$("#status").css({ color: "red" }).text("offline");
} else {
$("#status").css({ color: "green" }).text("online");
}
}
}
}
That's it really. Every second, it will call the update() method which makes an AJAX call and inserts the result back into your HTML.
instead of var int = self.setInterval("update()", 1000); try using self.setInterval(update, 1000); and place it after the update function.

Categories