getting error while doing post request to another php page - javascript

So its a little bit complicated i will try to make it simple.
i have a table with 3 columns and i made function that if u press on the column its give u the id of the post.
after this i need the id so i can show the post over new page - post.php.
i made this request
$(".click_title").click(function() {
var $item = $(this).closest("tr").find(".post_id_c").text();// for sure work
$.post("post.php",{"post_id_to_show":$item},function(){
location.href = "post.php";
});
});
on the php i starting with this:
if (isset ($_POST["post_id_to_show"]) ){
$post_id_to_show = $_POST["post_id_to_show"];
}else{
echo "errror";
}
and now i getting an error from the echo thing.
and then i want to show the post from the sql table:
<table class="table">
<caption><h3 style="text-align:right">h1</h3></caption>
<tr class="success">
<th style="text-align:center"> h2
<th style="text-align:center"> h3
<th style="text-align:center"> h4
</tr>
<?php
$cursor = $MySQLdb->prepare("SELECT * FROM comments WHERE post_id=:post_id");
$cursor->execute( array(":post_id"=>$post_id_to_show) );
foreach ($cursor->fetchAll() as $obj): ?>
<tr>
<td style="text-align:center"> <? echo $obj['comment_data']?></td>
<td style="text-align:center"><? echo $obj['full_name']?></td>
<td style="text-align:center"><? echo $obj['date_time']?></td>
</tr>
<? endforeach; ?>
</table>
and i getting this error from the web page Notice: Undefined variable: post_id_to_show in /opt/lampp/htdocs/big_project/post.php on line 96
btw the line is this line
$cursor->execute( array(":post_id"=>$post_id_to_show) );
something wrong?

first i deliver the info by ajax like this.
$(".click_title").click(function(){
var $item = $(this).closest("tr").find(".post_id_c").text();//עובד בטוח
if($item){
$.ajax({
url: 'post.php',
type: 'POST',
data: {post_id_to_show:$item},
success: function(data) {
location.href = "post.php";
console.log(data); // Inspect this in your console
}
});
};
});
and than in the first call of post_id_to_show i switch it to session var.
in the second call i used the session var and it worked.

Related

Displaying data from a certain database field that a user enters into a search bar

I have some code where the intended purpose is a user typing into a search bar. Upon searching, a table should display with records closely related to the search phrase. In my case, I have all the code set up, but I am not getting any table being shown upon searching.
I have many lines commented out and those are some of the fixes and things I have messed around with that I thought would fix this.
The Search function code - search.php
$name = $_POST['name'];
$sql = "SELECT * FROM ProfessorsOrStaff where Name LIKE '%".$name."%'";
//echo $sql;
$data = array();
$result = $conn->query($sql);
//echo json_encode($result);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row['Name'];
array_push($data, $row);
}
} else {
//array_push($data);
echo "no data";
exit;
}
//array_push($data, {"msg":'success'});
echo json_encode($data);
$conn->close();
?>
Partial code of file that displays the search bar and javascript
<div id="message" style="text-align: center">
<p>There are no results.</p>
</div>
<table class="table" id="result_table" hidden="hidden">
<thead class="thead-dark">
<th>Name</th>
<th>Phone Number</th>
</thead>
<tbody id="body">
<tr>
<!--<td>1</td>
<td>1</td>
<td>1</td>
<td>1</td>
<td>1</td>
<td>1</td>-->
</tr>
</tbody>
</table>
</div>
<script type="text/javascript">
$("#search").click(function(){
var text = $("#name").val();
$.post('search.php', {name: text}, function(data){
console.log(data);
//$name = $_POST['name'];
if(data != "no data" ){
console.log("here");
var obj = JSON.parse(data);
//$("#result_table").setAttr('hidden');
$('#result_table').removeAttr('hidden');
$("#message").hide();
var html = '';
for(var i = 0 ; i < obj.length; i ++ ){
console.log(obj[i]);
html += '</td><td>'+obj[i].Name+'</td><td>'+obj[i].PhoneNumber+'</td></tr>';
}
$('#body').html(html);
}
else{
$('#result_table').attr("hidden","hidden");
$("#message").show();
}
});
})
The code is a bit messy. To clarify,
The search.php can be found here-https://codeshare.io/a3wdmD
Other file with javascript- https://codeshare.io/G8838A
Table layout -https://imgur.com/a/14SsvLS
EDIT1- After finding out the request was not being made, I switched some stuff around and was able to make it not correctly call the search.php file. Now I am getting the wrong results from this. It is bringing me to a new page and displaying the contents of all my records in that table, as a plain text format. I was trying to make it so once the search button was pressed, a table of results appeared right below the search bar. The links to the full code have been updated to show the current state of the code.

Ajax request data could not show into the input field

I have created a loop which contains a dropdown list and input field.
What I need is:
When I select a value from dropdown list of Fruit Genres, the Unit Price field will display value come from database. I did all of these, but could not display value to the Unit Price field.
Here is my code:
View page:
<div class="table-responsive">
<table class="table table-hover" id="item-tbl">
<thead>
<tr>
<th class="text-center">Fruit Type</th>
<th class="text-center">Fruit Genres</th>
<th class="text-center">Qty</th>
<th class="text-center">Unit Price</th>
<th class="text-center">Sub Total</th>
</tr>
</thead>
<tbody>
<?php for($i=1; $i<=3; $i++){ ?>
<tr style="">
<td><?php echo $this->Form->input('fruit_type_id', ['options'=>$fruit_types, 'empty'=>'Select Fruit Type', 'label'=>false, 'name'=>'detail_orders['.$i.'][fruit_type_id]']); ?></td>
<td><?php echo $this->Form->input('fruit_genre_id', ['options'=>$fruit_genres, 'empty'=>'Select Fruit Genre', 'label'=>false, 'name'=>'detail_orders['.$i.'][fruit_genre_id]', 'class'=>'fruit_genre']); ?></td>
<td><?php echo $this->Form->input('quantity', ['type'=>'text', 'label'=>false, 'name'=>'detail_orders['.$i.'][quantity]', 'class'=>'quantity', 'id'=>'quantity_'.$i]); ?></td>
<td><?php echo $this->Form->input('price', ['type'=>'text', 'label'=>false, 'name'=>'detail_orders['.$i.'][price]', 'class'=>'price', 'id'=>'price_'.$i]); ?></td>
<td><?php echo $this->Form->input('sub_total', ['type'=>'text', 'label'=>false, 'name'=>'detail_orders['.$i.'][price]', 'class'=>'sub_total']); ?></td>
</tr>
<?php } ?>
</tbody>
</table>
Javascript:
<script type="text/javascript">
$(document).ready(function() {
$(".fruit_genre").on('change' , function() {
var fruitGenreId = +$(this).val();
var priceId = $(this).closest('tr').find('.price').attr('id');
// alert(priceId);
$.ajax({
type: "GET",
url: baseURL+"orders/getFruitById/"+fruitGenreId+".json",
beforeSend: false,
success : function(returnData) {
if(returnData.response.code == '200'){
console.log(returnData.response.data.unit_price);
// $(this).closest('tr').find('.price').val(returnData.response.data.unit_price);
$(priceId).val(returnData.response.data.unit_price);
};
}
})
}).trigger('change');
});
OrdersController.php
public function getFruitById($id){
$this->viewBuilder()->layout('ajax');
$this->loadModel('FruitGenres');
$item = $this->FruitGenres->get($id);
if (!empty($item)) {
$response['code'] = 200;
$response['message'] = 'DATA_FOUND';
$response['data'] = $item;
}else{
$response['code'] = 404;
$response['message'] = 'DATA_NOT_FOUND';
$response['data'] = array();
}
$this->set('response', $response);
$this->set('_serialize', ['response']);
}
I have got the expected data to the javascript console. but could not pass the data to the input field.
I have tried:
$(this).closest('tr').find('.price').val(returnData.response.data.unit_price);
instead of
$(priceId).val(returnData.response.data.unit_price);
into the ajax success function, but it did not worked.
if I add a static id like the following:
$('#price_1').val(returnData.response.data.unit_price);
then it works.
Can anyone please help me? I am stuck on it.
I am using cakephp 3 for my project.
priceId is a value like price_1 without #. To make it a selector by id - prepend it with #:
$("#" + priceId).val(returnData.response.data.unit_price);
You can even simplify your code:
// you get id of the found element so as to find this element again
// you can store founded element instead of it's id
var priceDiv = $(this).closest('tr').find('.price');
// in success callback:
priceDiv.val(returnData.response.data.unit_price);
You can select the element directly instead of getting its ID and select with another jQuery call.
Another thing to note - this in the submit callback refer to the callback function itself, not the element.
$(document).ready(function() {
$(".fruit_genre").on('change' , function() {
var fruitGenreId = +$(this).val();
var $price = $(this).closest('tr').find('input.price'); // Get the element
$.ajax({
type: "GET",
url: baseURL+"orders/getFruitById/"+fruitGenreId+".json",
beforeSend: false,
success : function(returnData) {
if(returnData.response.code == '200'){
console.log(returnData.response.data.unit_price);
// Use $price directly as a jQuery object
$price.val(returnData.response.data.unit_price);
};
}
})
}).trigger('change');
});

jQuery/PHP - Passing data from JS to PHP to perform deletion on database

I want to delete an object on my database through my own admin page. The way it works is simple: when I click the delete button in the row corresponding with the object, the JS code will grab the "id" attribute of the object and pass it to PHP to perform sql delete query. Although the console showed nothing, my code didn't work. Would you mind taking a glance at my code and find out what's wrong with it? I'm using PHP 7. All neccessary libraries is included. Thank you very much!
Here are my code:
HTML:
<table>
<thead>
<th>ID</th>
<th>Name</th>
</thead>
<tbody>
<?php
include("../connect.php");
$sql = "select * from tbl";
$query = mysqli_query($connect,$sql);
while($data = mysqli_fetch_assoc($query)) {
?>
<tr>
<td class="data-id">
<?php echo $data['id'] ?>
</td>
<td>
<?php echo $data['name'] ?>
</td>
<td>
<img src="delete.png" class="delete-button">
</td>
</tr>
<?php } ?>
</tbody>
</table>
JS:
$(document).ready(function() {
$('.delete-button').click(function() {
var id = $(this).parent().siblings('.data-id').text();
$.ajax({
type: 'post',
url: 'http://localhost/myproject/delete.php',
data: {
"id":id
}
});
});
});
PHP delete.php
<?php
include("../connect.php");
if(isset($_POST["id"])) {
$id = $_POST["id"];
$sql = "delete from tbl where id=".$id;
$query = mysqli_query($connect,$sql);
}
?>
PHP connect.php
<?php
$connect = new mysqli("localhost","root","","db");
mysqli_set_charset($connect,'utf8');
?>
Your delete query syntax is wrong. It should be like below,
$sql = "delete from tbl where id=".$id;
Remove '*' from the query
Update: There are 2 more errors in your code & hopefully these corrections might fix your issue
Issue 1: Since your sending text inside a TD as id, it sends the id along the spaces in the HTML. So trim your value. Here is your query,
$sql = "delete from tbl where id=".trim($id);
Issue 2: This might be a typo error. '$connnect' variable should be '$connect' in connect.php file.
It seems that $(this).parent().siblings('data-id').text();
Should be $(this).parent().siblings('.data-id').text();
Missing the dot (.) in the class name.
In your actual code please `` for reserved mysql name
Change to below code :
$sql = "DELETE FROM `tbl` WHERE `id`='$id'";

how to pass data from one html page to second in php?

I have created a page for updation of record. I want to pass the id of student from one page to another. I am trying to send it through window.location but it is not working. In ajax I tried to navigate to other page but didn't succeed in that too. How can i pass the data and receive on other page without showing in query string?
ajax code is
var id = $(this).data('username');
$.ajax({
var id = $(this).data('username');
$.ajax({type: "POST",
cache: false,
data: id,
url: "Update.php",
success: function(dto)
{
//but I do not require this return call I just
// want to pass the data to update.php
}
});
//this is the code where the button is being clicked
<table class="table table-condensed" >
<thead style="background-color:#665851" align="center">
`<tr>
<td style="color:white">Roll No</td>
<td style="color:white">Name</td>
<td style="color:white">Department</td>
<td style="color:white">Click To Update</td>
</tr>
</thead>
<tbody style="background-color:whitesmoke; border:initial" id="tblBody" align="center">
<?php
$database="firstdatabase"; //database name
$con = mysqli_connect("localhost","root" ,"");//for wamp 3rd field is balnk
if (!$con)
{ die('Could not connect: ' . mysql_error());
}
mysqli_select_db($con,$database );
$state = "SELECT rollno ,name, dept FROM student ;";
$result = mysqli_query($con,$state);
$output = 1;
$outputDisplay = "";
$noRows = mysqli_affected_rows($result);
if($result)
{
$num = mysqli_affected_rows($con);
//$row = mysqli_fetch_array($result,MYSQLI_NUM);
while ($row = mysqli_fetch_array($result))
{
$r = $row['rollno'];
$n = $row['name'];
$d = $row['dept'];
$outputDisplay .= "<tr><td>".$r."</td><td>".$n."</td><td>".$d."</td><td align='right'>
<button type='button' name='theButton' value='Detail' class='btn' id='theButton' data-username='$r'> <img src='edit.jpg'/></button>
</td>
</tr>";
}
}
else
{
$outputDisplay .= "<br /><font color =red> MYSql Error No: ".mysqli_errno();
$outputDisplay .= "<br /> My SQl Error: ".mysqli_error();
}
?>
<?php
print $outputDisplay;
?>
</tbody>
</table>
If both pages are at same domain you can use localStorage, storage event to pass data between html documents
At second page
window.addEventListener("storage", function(e) {
// do stuff at `storage` event
var id = localStorage.getItem("id");
});
at first page
// do stuff, set `localStorage.id`
localStorage.setItem("id", "abc");
When you use window.location then your page go to another page. ajax work on active page. You can not use.
Generally you can use sessions for this $_SESSION variable to store it into the session, or you can pass that value via get parameter. And afterwards get that parameter with $_GET
Or $_POST parameter if you want to submit form.
you can try using cookies
Set the cookie
<?php
setcookie("name","value",time()+$int);
/*name is your cookie's name
value is cookie's value
$int is time of cookie expires*/
?>
Get the coockie
<?php
echo $_COOKIE["your cookie name"];
?>
Populate a <form method="post" [...]> in the first page with the information needed; you can change their aspect with CSS as desired.
When the <form> is send you only need a PHP script/page that uses $_POST to fill the new page.
Easier than AJAX if you try to navigate from the first page to the second.
If you already have a form and wanna post that to an update script, you could just add the student id as an hidden form element example:
<input type="hidden" name="student_id" value="<?php echo $student_id; ?>">
Else if you want to redirect from another page to the update page, with a student id, the best way will probably be a $_GET variable.
So the URL would look something like this: http://domain.com/update.php?student_id=1
And then your update.php will include a simple check like this.
if(!empty($_GET['student_id'])) {
$student_id = $_GET['student_id'];
// Ready to update
} else {
// Throw 404 error, or redirect to an create page
}

Reload the query after adding the record to mysql database with ajax without reloading the page

I have a page where user can add the records to the mysql database. On the same page there is a list existing records in the database.
I use ajax to add the record to database, sorry for old version of mysql, will get updated after I get this thing to work first:
$(document).ready(function(){
//on the click of the submit button
$("#btn_submit").click(function(){
//get the form values
var username = $('#hdn_username').val();
var name = $('#txt_name').val();
var brand = $('#txt_brand').val();
//make the postdata
var postData = 'username='+username+'&name='+name+'&brand='+brand;
//call your input.php script in the background, when it returns it will call the success function if the request was successful or the error one if there was an issue (like a 404, 500 or any other error status)
$.ajax({
url : "input.php",
type: "POST",
data : postData,
success: function(data,status, xhr)
{
//if success then just output the text to the status div then clear the form inputs to prepare for new data
$("#status_text").html(data);
$('#name').val('');
$('#brand').val('');
},
error: function (jqXHR, status, errorThrown)
{
//if fail show error and server status
$("#status_text").html('there was an error ' + errorThrown + ' with status ' + textStatus);
}
});
}); });
My html is:
<table class="simplet" width="640" border="0" cellspacing="0" cellpadding="0">
<thead>
<tr>
<th width="300" colspan="2">Product Name</th>
<th width="150">Brand</th>
<th width="100">Quantity</th>
<th width="60">Price</th>
<th width="30">Delete</th>
</tr>
</thead>
<tbody>
<tr><td colspan="6"><div id="status_text_list" /></td></tr>
[insert_php]
$current_user= wp_get_current_user();
$username= $current_user->user_login;
mysql_connect("localhost","xxxxx","xxxx");//database connection
mysql_select_db("xxxx");
$query= "SELECT * FROM wp_userdata WHERE username='$username'";
$result= mysql_query($query);
if (!$result) { die("Error db request: <br />". mysql_error()); }
while ($result_row = mysql_fetch_array($result, MYSQL_ASSOC)){ echo '<tr class="odd-row"><td width="30"></td><td>'.$result_row['product_name'].'</td><td>'.$result_row['product_brand'].'</td><td>'.$result_row['product_quantity'].'</td><td>'.$result_row['product_link'].'</td><td><a class="link-delete" href="#" data-delete-id="' . $result_row['id'] . '">X</a></td></tr>';
}
[/insert_php]
</tbody></table>
<br />
<table border="1">
<tr>
<td align="center">Add Products</td>
</tr>
<tr>
<td>
<form onsubmit="return false">
<table>
<input type="hidden" id="hdn_username" name="username" value="[insert_php]echo $username;[/insert_php]">
<tr>
<td>Product Name</td>
<td><input type="text" id="txt_name" name="name" size="50">
</td>
</tr>
<tr>
<td>Brand</td>
<td><input type="text" id="txt_brand" name="brand" size="50">
</td>
</tr>
<tr>
<td></td>
<td><div id="status_text" /></td>
</tr>
<tr>
<td></td>
<td align="right"><input type="submit" id="btn_submit" name="submit" value="Submit"></td>
</tr>
</form>
</table>
</td>
</tr>
</table>
And my input.php is:
mysql_connect("localhost","xxxx","xxxx");//database connection
mysql_select_db("xxxx");
//inserting data order
$order = "INSERT INTO wp_userdata
(username, product_name, product_brand)
VALUES
('$_POST[username]',
'$_POST[name]',
'$_POST[brand]')";
//declare in the order variable
$result = mysql_query($order); //order executes
if($result){
echo ("DATA SAVED SUCCESSFULLY");
} else{
echo("<br>Input data is fail");
}
When I click the Submit button, form values sent to input.php and the success message is displayed, you can see it here - http://suppliesprices.com/?page_id=4
What I want to achieve is to add the new data row to the displayed list without reloading the page.
I was thinking to render it with javascript and add to a success ajax call, but not sure if it going to work.
How do I change my code to get the desired effect?
To add another row to the table, you can use the jQuery append function. You can do this inside you success function like so:
success: function(data,status, xhr)
{
//if success then just output the text to the status div then clear the form inputs to prepare for new data
if (data.status == 'success') {
$("#status_text").html('DATA SAVED SUCCESSFULLY');
$('#name').val('');
$('#brand').val('');
$('.simplet tbody').append('<tr class="odd-row"><td width="30"></td><td>'+data.product.product_name+'</td><td>'+data.product.product_brand+'</td><td>'+data.product.product_quantity+'</td><td>'+data.product.product_link+'</td><td><a class="link-delete" href="#" data-delete-id="' + data.product.id + '">X</a></td></tr>');
} else {
$("#status_text").html(data.message);
}
},
You will want to update your PHP code to return some more information. Most commonly you would return JSON containing information about whether the transaction succeeded and a copy of the information that was inserted into your database (or an error message if it failed). You could do something like the following:
if($result){
$id = mysql_insert_id();
$retVal = array(
'status' => 'success',
'product' => array(
'id' => $id,
'product_name' => $_POST['name'],
'product_brand' => $_POST['brand'],
'product_quantity' => 0,
'product_link' => '/?product_id=' . $id // not sure if this is the correct format or not
)
);
} else {
$retVal = array(
'status' => 'error',
'message' => 'Product could not be inserted'
);
}
header('Content-Type: text/json');
echo json_encode($retVal);
You definitely should update the database code to follow better security practices, but this should get you started.
Two things you can do.
Option 1:
Just use a regular button type='button' rather than a submit button type='submit'. A submit button by default changes the page, while a regular button does not.
Option 2:
$("#btn_submit").click(function(event){
event.preventDefault();
//get the form values
See docs for event.preventDefault. The default action of a submit button is to submit by going to the page defined in the form's action attribute (or back to the same page if you didn't specify an action attribute). This call prevents that default action so you can use Ajax instead.
And on the form, you can get rid of the onsubmit="return false" because that will not work.
Edit:
A bug I found in your Ajax. You're using GET syntax with POST.
Do not use: var postData = 'username='+username+'&name='+name+'&brand='+brand; followed by data : postData, in your Ajax with POST.
Rather, use in your ajax data: { username: username, name: name, brand: brand }. With POST the = and & are not used.
Also, in PHP: $_POST[username] is wrong. Should be $_POST['username'].

Categories