Passing value from JS to PHP - javascript

Passing a table cell value from javascript variable into php variable.
<script>
$(document).on('ready',function(){
$('#business_list_table').on('click','.view_btn',function (){
$.ajax({
url: "test.php",
method: "POST",
data:{business_id : "6510-1"},
success: function (data){
$('#business_permit_table').html(data);
}
});
});
});
<?php
$business_id = $_GET["business_id"];
echo $business_id;

You cannot use JS variable directly to PHP like that. use ajax instead:
JS
$("#business_list_table").on('click', '.view_btn', function post() {
// get the current row
var currentRow = $(this).closest("tr");
var Business_id_value= currentRow.find("td:eq(1)").text(); // get current row 2nd T;
$.post('', {Business_ID: Business_id_value}, function(result){
$('table tbody').html(result);
});
});
PHP
if (isset($_POST['Business_ID'])) {
$Business_ID = $_POST['Business_ID'];
$conn = mysqli_connect("localhost", "root", "", "bpsystem");
if ($conn->connect_error) {
die("Database connection failed:" . $conn->connect_error);
} else {
$sql = "SELECT * FROM business_tb WHERE Business_ID='$Business_ID';";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
echo "<tr >";
echo "<td>BUSINESS NAME</td>";
echo "<td>" . $row['Business_Name'] . "</td>";
echo "</tr>";
echo "<tr >";
echo "</tr>";
}
}
}
}

You can use the query string to pass the variable to PHP. Like this,
$("#business_list_table").on('click', '.view_btn', function post() {
// get the current row
var currentRow = $(this).closest("tr");
var Business_id_value= currentRow.find("td:eq(1)").text(); // get current row 2nd T;
window.location.href = 'http://your_url?b_id=' + Business_id_value;
});
Now you can access the Business_id_value varible in your PHP script using $_GET['Business_id_value']

Related

Ajax Success Returning Commented Html Tag

I am trying to set up a select box that would show up the cities depending on the prior selection of the state.
Basically, I am using ajax to run my php.file to populate my <option>. In the php file I successfully passed the pre-selected state to query the database. However, now, to populate the <option> I am using ajax success to call the php file, however, whenever I try to pass the variable containing the php code it shows up commented with !-- and --.
// hmtl
<select id="select-city" required >
<option disabled selected>Selecione sua Cidade</option>
</select>
// js code
function fillSelectCity () {
var getState = document.getElementById('selectState');
var stateID = getState.options[getState.selectedIndex].value;
$.ajax ({
type: "POST",
url: "fillcity.php",
data: { stateID : stateID },
success: function (){
var phpfile = "'fillcity.php'"
var tag = "<?php include_once " + phpfile + " ?>";
$('#select-city').html(tag);
/// here the output is "<!-- ?php include_once 'fillcity.php' ? -->"
}
})
}
//php file
<?php
$conn = mysqli_connect("host", "user", "pass", "db");
if(isset($_POST['stateID']))
{
$stateID = $_POST['stateID'];
}
$query = "SELECT * FROM states WHERE stateID = '$stateID'";
$result_one = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result_one); //my table has a specific ID for each state, so I am fetching the acronoym of the state according to the id;
$stateUf = $row['uf']; // passing the acronym to the $stateUf
mysqli_free_result($result_one);
$queryCity = "SELECT * FROM city WHERE Uf = '$stateUf'"; //query all cities with the acronym
if ($result = mysqli_query($conn, $queryCity)){
while ($row = mysqli_fetch_assoc($result)){
$id = $row['cityID'];
$name = $row['cityName'];
$name = utf8_encode($name);
echo <<< EOT
"<option value="$id">$name</option>"
EOT;
}
mysqli_free_result($result);}
else {echo "<option>Error</option>";}
?>
I expect to populate my select options by looping through the table city in the php file. The tag <?php include_once 'fillcity.php' ?> was used to populate the state select. Probably, there may be a more direct way to populate accordingly, but as I am new to programming, I am trying to figure things out on my own. But please, feel free to recommend other methods as I am not sure if what I am planning to do will gonna work. Thanks!
You can try this one. You can modify it later for improvement.
read.php
<?php
//include header
header('Content-Type: application/json');
$conn= mysqli_connect("localhost","my_user","my_password","my_db");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$type = $_GET["type"];
if($type == "GetState"){
//SAMPLE QUERY
$sql = "SELECT StateID,StateName from State";
$data = array();
$results = $db -> query($sql);
while($row = mysqli_fetch_assoc($results)){
$data[] = $row;
}
echo json_encode($data);
}
if($type == "GetCity"){
$StateID= $_POST["StateID"];
//SAMPLE QUERY
//LET'S ASSUME THAT YOU HAVE FOREIGN KEY
$sql = "SELECT CityID,CityName from City where StateID = '".$StateID."'";
$data = array();
$results = $db -> query($sql);
while($row = mysqli_fetch_assoc($results)){
$data[] = $row;
}
echo json_encode($data);
}
?>
index.html
<select id="state"></select>
<select id="city"></select>
<!--PLEASE INCLUDE JQUERY RIGHT HERE E.G. <script src='jquery.min.js'></script>-->
<!--DOWNLOAD JQUERY HERE https://jquery.com/-->
<script>
LoadState();
function LoadState(){
$.ajax({
url:"read.php?type=GetState",
type:"GET",
success:function(data){
var options = "<option selected disabled value="">Select
State</option>";
for(var i in data){
options += "<option value='"+data[i].StateID+"'>" + data[i].StateName+ "</option>";
}
$("#state").html(options);
}
});
}
function LoadCity(StateID){
$.ajax({
url:"read.php?type=GetCity",
type:"POST",
data:{
StateID: StateID
},
success:function(data){
var options = "<option selected disabled value="">Select City</option>";
for(var i in data){
options += "<option value='"+data[i].CityID+"'>" + data[i].CityName+ "</option>";
}
$("#city").html(options);
}
});
}
$("#city").change(function(){
LoadCity(this.value);
});
You don't need to include 'fillcity.php. The AJAX call runs that script, and the response is the output. It will be in the parameter of the success function.
function fillSelectCity () {
var getState = $("#selectState").val();
$.ajax ({
type: "POST",
url: "fillcity.php",
data: { stateID : stateID },
success: function (tag){
$('#select-city').html(tag);
}
});
}

How to display values in JS from a PHP array that was posted from jQuery

I have a button called rename that when pushed, executes in jQuery a rename.php file. Inside that php file the program selects data from a mysql, creates an array with that data, and processes an array in to json_encode($array);. How can I then get that json encoded array and echo it out into javascript?
I'm trying to echo the array out so that javascript displays my images src's.
This is my second line of ajax so I just wrote the javascript out as if it were php because I'm not sure of the commands or structure in js.
$.ajax
(
{
url:"test4.php",
type: "GET",
data: $('form').serialize(),
success:function(result)
{
/*alert(result);*/
document.getElementById("images_to_rename").innerHTML = foreach(jArray as array_values)
{
"<img src=\""array_values['original_path']"/"array_values['media']"/>";
}
}
}
);
and my jQuery php file:
<?php
include 'db/mysqli_connect.php';
$username = "slick";
if(empty($_GET['image_name']))
{
echo '<div class="refto" id="refto">image_name is empty</div>';
}
else
{
echo '<div class="refto" id="refto">image_name is not empty</div>';
foreach($_GET['image_name'] as $rowid_rename)
{
//echo '<br><p class="colourful">rowid_refto: '.$rowid_refto.'</p><br>';
$active = 1;
$command = "Rename";
$stmt = $mysqli->prepare("UPDATE ".$username." SET active=?, command=? WHERE rowid=?");
$stmt->bind_param("isi", $active, $command, $rowid_rename);
$stmt->execute();
$stmt->close();
}
//go to database, get parameters of sort
$command = "Rename";
$active = 1;
$stmt = $mysqli->prepare("SELECT original_path, media FROM " . $username . " WHERE active=? and command=?");
$stmt->bind_param("is", $active, $command);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc())
{
$arri[] = $row;
}
foreach($arri as $rows) //put them into workable variables
{
$rowt = $rows['original_path'];
$rowy = $rows['media'];
//echo 'rows[\'original_path\'] = '.$rows['original_path'].''.$rows['media'].'';
}
$stmt->close();
echo json_encode($arri);
?>
<script type="text/javascript">
var jArray= <?php echo json_encode($arri); ?>;
</script>
<?php
}
echo "something2";
?>
My PHP file is a jQuery url:"test4.php", type: "GET", and is not the main file. The main file is called main.php and the test4.php is something that's called in jQuery when the user clicks on rename.
Somebody suggested console log so here's what chrome says:
<div class="refto" id="refto">image_name is not empty</div>[{"original_path":"Downloads","media":"shorter.jpg"},{"original_path":"Album 2","media":"balls.jpg"}] <script type="text/javascript">
var jArray= [{"original_path":"Downloads","media":"shorter.jpg"},{"original_path":"Album 2","media":"balls.jpg"}];
</script>
something2
Your ajax php file isn't render in browser, then the variable jArray is undefined. With your case, let return php file to json and you can get it as variable in result.
<?php
include 'db/mysqli_connect.php';
$username = "slick";
if (empty($_GET['image_name'])) {
//echo '<div class="refto" id="refto">image_name is empty</div>';
} else {
//echo '<div class="refto" id="refto">image_name is not empty</div>';
foreach ($_GET['image_name'] as $rowid_rename) {
//echo '<br><p class="colourful">rowid_refto: '.$rowid_refto.'</p><br>';
$active = 1;
$command = "Rename";
$stmt = $mysqli->prepare("UPDATE " . $username . " SET active=?, command=? WHERE rowid=?");
$stmt->bind_param("isi", $active, $command, $rowid_rename);
$stmt->execute();
$stmt->close();
}
//go to database, get parameters of sort
$command = "Rename";
$active = 1;
$stmt = $mysqli->prepare("SELECT original_path, media FROM " . $username . " WHERE active=? and command=?");
$stmt->bind_param("is", $active, $command);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$arri[] = $row;
}
foreach ($arri as $rows) { //put them into workable variables
$rowt = $rows['original_path'];
$rowy = $rows['media'];
//echo 'rows[\'original_path\'] = '.$rows['original_path'].''.$rows['media'].'';
}
$stmt->close();
echo json_encode($arri);
//stop render here
die();
}
?>
php file need return only json string. Then we'll get result as json variable in javascript.
And Js:
$.ajax
(
{
url:"test4.php",
type: "GET",
data: $('form').serialize(),
success:function(result)
{
var jArray = JSON.parse(result);
/*alert(result);*/
var txt = "";
jArray.forEach(function(array_values){
txt += `<img src=\""array_values.original_path."/"array_values.media"/>`;
})
document.getElementById("images_to_rename").innerHTML = txt;
}
}
);

Creating jQuery array variable and Transferring array to another page PHP

I currently have this function exactly how I want it except for the jQuery at the bottom in which I am only alerting and not creating a real variable. It all works but I am stuck on how I can take all of the data from the jQuery script and then make it into a variable so that I can bring it to another page? Any ideas, NEED HELP!
function getGrade($id, $grades_array) {
$counter = 0;
$sql = "Select grade FROM grades";
$result = mysql_query($sql) or die (mysql_error());
echo '<select name="grades_selected" multiple="multiple" id="grades_selected">';
while ($row = mysql_fetch_array($result)) {
if ($row['grade'] != $grades_array[$counter]) {
echo "<option>" . $row['grade'] . "</option>";
} else {
echo "<option selected=" . $row['grade'] . ">" . $row['grade'] . "</option>";
$counter = $counter + 1;
}
}
mysql_free_result($result);
echo '</select>';
$_SESSION['test'] = $grades_array;
?>
<script>
$(document).ready(function() {
$('#grades_selected').change(function() {
alert($(this).val());
});
});
</script>
<?
}
You need to use ajax within on change function:
$(document).ready(function() {
$('#grades_selected').change(function() {
var variable = $(this).val();
$.ajax({
type: 'post',
url: 'target_page.php',
data: {variable : variable},
success: function (res) {
alert(res);
}
});
});
});
On target_page.php:
echo $_POST['variable'];

How to delete record using ajax?

I am trying to delete record from database using AJAX. The confirmation window does not appear so that the record can be deleted. here is the code..
<?php
$q = $_GET['q'];
$p = $_GET['p'];
$sql="SELECT * FROM course_details WHERE sem='" . $q . "' AND branch='" . $p . "' ORDER BY course_codes ASC";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)){
echo '<tr class="record">';
echo "<td>" . $row['course_codes'] . "</td>";
echo "<td>" . $row['course_names'] . "</td>";
echo "<td>" . $row['course_instructors'] . "</td>";
echo "<td>" . $row['course_credits'] . "</td>";
echo '<td><div align="center">delete</div></td>';
echo '</tr>';
}
echo "</table>";
mysql_close($bd);
?>
Here $p and $q are send by an AJAX script from another page. It is working fine. The records are displayed as expected. Deletion works using AJAX if i do not use AJAX to display records.The script I am using to delete is:
<script src="jquery.js"></script>
<script type="text/javascript">
$(function() {
$(".delbutton").click(function(){
var element = $(this);
var del_id = element.attr("id");
var info = 'id=' + del_id;
if(confirm("Are you sure you want to delete this Record?")){
$.ajax({
type: "GET",
url: "deleteCourse.php",
data: info,
success: function(){
}
});
$(this).parents(".record").animate({ backgroundColor: "#fbc7c7" }, "fast")
.animate({ opacity: "hide" }, "slow");
}
return false;
});
});
</script>
deleteCourse.php
if($_GET['id']){
$id=$_GET['id'];
$id = mysql_escape_string($id);
}
$del = "DELETE from course_details where course_id = '$id'";
$result = mysql_query($del);
The problem is because you are creating dynamic elements so you have to use a delagate $(document).on() inorder to bind the click event to the elements.
Here is the corrected code
<script type="text/javascript">
$(function() {
$(document).on('click','.delbutton',function(){
var element = $(this);
var del_id = element.attr("id");
var info = 'id=' + del_id;
if(confirm("Are you sure you want to delete this Record?")){
$.ajax({
type: "GET",
url: "deleteCourse.php",
data: info,
success: function(){ }
});
}
return false;
});
});
</script>
and your deletCourse.php
if($_GET['id']){
$id=$_GET['id'];
$id = mysql_escape_string($id);
}
$del = "DELETE from course_details where course_id = ".$id."";
$result = mysql_query($del);
Hope this helps, Thank you
try this one
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
delete
delete
delete
delete
delete
javascript
function del(id)
{
var info = 'id=' + id;
if(confirm("Are you sure you want to delete this Record?")){
var html = $.ajax({
type: "POST",
url: "delete.php",
data: info,
async: false
}).responseText;
if(html == "success")
{
$("#delete").html("delete success.");
return true;
}
else
{
$("#captchaStatus").html("incorrect. Please try again");
return false;
}
}
}
ajax file
if($_GET['id']){
$id=$_GET['id'];
$id = mysql_escape_string($id);
}
$del = "DELETE from course_details where course_id = '$id'";
$result = mysql_query($del);
if($result)
{
echo "success";
}
Try this:
<script type="text/javascript" src="jquery.js"></script>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
function del(id)
{
var info = 'id=' + id;
if(confirm("Are you sure you want to delete this Record?")){
var html = $.ajax({
type: "GET",
url: "deletCourse.php",
data: info,
async: false ,
success: function() {
window.location.reload(true);}
}).responseText;
}
}
</script>
<?php
$link=mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("cart");
$sql=mysql_query("SELECT * FROM `details`");
echo "<table>";
echo "<tr><th>Name</th><th>NO of Items</th></tr>";
while($row = mysql_fetch_assoc($sql)){
echo '<tr class="record">';
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['num'] . "</td>";
echo '<td><div align="center">delete</div></td>';
echo '</tr>';
}
echo "</table>";
mysql_close($link);
?>

calling a php function in javascript

I dont know how to use ajax in my problem:
I have a function in php (assign) that update a temporary table in database, I want to when user user click on a button (feedback function that is defined in javascript) this function (assign) run, what should I do?
<script>
function feedback(){
var boxes = document.getElementsByClassName('box');
for(var j = 0; j < boxes.length; j++){
if(boxes[j].checked) {
assign(1);
}
else{
assign(0);
}
}
}
</script>
<?php
$con = mysql_connect("localhost", "root", "")
or die(mysql_error());
if (!$con) {
die('Could not connect to MySQL: ' . mysql_error());
}
mysql_select_db("project", $con)
or die(mysql_error());
$result = mysql_query("select * from words");
echo "<table border='1'>
<tr>
<th>word</th>
<th>meaning</th>
<th>checking</th>
</tr>";
while($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['word'] . "</td>";
$idd= $row['id'] ;
echo "<td>". "<div class='hiding' style='display:none'>".$row['meaning']."</div>"."</td>";
echo "<td>";
echo "<input class=\"box\" name=\"$idd\" type=\"checkbox\" value=\"\"> ";
echo "</td>";
echo "</tr>";
}
echo "</table>";
function assign($checkparm){
//mysql_query("update words set checking=$checkparm ");
mysql_query("create TEMPORARY TABLE words1user1 as (SELECT * FROM words) ");
mysql_query("update words1user1 set checking=$checkparm ");
}
mysql_close($con);
?>
<button onclick="ShowMeanings()">ShowMeanings</button>
<button onclick="feedback()">sendfeedback</button>
There is only one way to call a php function after the page is loaded:
1.ajax:
function callPHP() {
$.ajax ({
url: "yourPageName.php",
data: { action : assign }, //optional
success: function( result ) {
//do something after you receive the result
}
}
in your PHP, write
if ($_POST["action"] == "assign")
{
assign(your parameters); //You need to put the parameters you want to pass in
//the data field of the ajax call, and use $_POST[]
//to get them
}
There are many great guides on the internet. I will however suggest you get too know JQuery. It will help you on your learning curve.
function ajaxCall(){
$.ajax({
type: "GET",
url: "scripts/on/serverside.php"
});
};

Categories