JavaScript function not posting - javascript

I have a javascript function that should remove a table row from a PHP page. My question is what am I missing to make this post to my PHP page.
the line clicked to do the remove
echo '<td align="right"><i class="glyphicon glyphicon-remove" id="abc" onClick="remove(id)"></i></td>';
the javascript:
function remove(id){
var rem = confirm('Are you sure you want to remove the id ' + id + '?');
if (rem == true){
alert(id); //just to see if my data is making it this far, it is
$.ajax({
data: 'id' + id,
url: 'pages/ini.php',
method: 'POST',
success: function(msg){
alert('Data entered!');
location.reload();
}
});
}
}
the php page:
$test = $_POST['id'];
But all that it is return is an empty value. I tried to display it and all I got was empty data, or when I'd do echo $test; Id get a blank page with no console errors

through $.ajax your request getting posted but your clicked "id" of element not getting passed because you have write
data: 'id' + id
instead of
data: {'id' : id }
This will actually send clicked element "id" to your PHP Code.
Hope, this will help you.

Related

send jQuery generated table to another php page

In my project (some kind of online game store), i have a jQuery generated table from click on original table row. The original table is populated from mysql database. On submit i need to send that generated table to another php page. I'm quite new with it and so far this is my code:
on php_first.php
generated table
<form action="php_second.php" id ="form_send" name ="form_send1" method="POST">
<div>
<table id="generated_table" style="display:none" name ="generated_table1">
<tr><th>Game</th><th>Platform</th> <th>Genre</th> <th>Price</th><tr>
// generated rows here
</table>
<input type="submit" value="Confirm" id="btnOrder" style="display:none"></input>
</div>
</form>
generated rows
$(document).ready(function(){
$('#original_table tbody tr').click(function(){
var data = $(this).children("td").map(function(){
return $(this).text();
}).get();
var row= '<tr name ="new_row"><td name = "game">' + data[0] + '</td><td name = "platform">' + data[1] +
'</td><td name = "genre">' + data[2] + '</td><td name = "price">' + data[3] +
'<button type="button" onclick="remove(this)" class ="btn_remove">Remove</button>' +'</td></tr>';
$("#generated_table tbody").append(row);
$('#generated_table').show();
$('#btnConfirm').show();
});
ajax post to php_second.php
$('#btnOrder').click(function(){
var table= $('#generated_table');
$.ajax({
url: 'php_second.php',
type: 'POST',
data: {data: table},
async: false,
success: function(data){
alert(data);
}
});
However, ajax dosen't do alert(data) so i asume this is the problem but i cant determine it.
and on php_second.php
<table id="table_order" name = "table_order1" style="display:show">
<?php
if(isset($_POST['generated_table'])){
$table= $_POST['generated_table'];
echo $table;
}
?>
</table>
The problem is that i cannot post table data to another php (and print that table on other php when redirected). Tried to use ajax to send row data on row click, or passing div where table is but nothing. It shows no errors but no data is passed.
This is my first question so it is possible that i missed out some details to make the problem more clear. Thanks!
EDIT
I've tried Kalaikumar Thangasamy's code and ajax is working fine now, but the problem is on other php page.
<?php
if(isset($_POST['data'])){
$table = $_POST['data'];
echo $table;
}
else {
echo "None selected";
}
?>
The $_POST['data'] or any other parameter from first php is always null.
Change data: {data: table} to data: {'generated_table': escape(table)}. Posting data as but referring post data in $_POST['generated_table']. You suppose to be used $_POST['data']. Try this
var table= $('#generated_table').html();
$.ajax({
url: 'php_second.php',
type: 'POST',
data: {'generated_table': escape(table)},
async: false,
success: function(data){
alert(data);
}
});

Not able to POST Variable to Another Page (PHP, Javascript, AJAX)

I have a while loop (inside the "searchvessel.php") that display the content of a query and have a button "upgrade" for each record of that query.
`while($fetch = $read->fetch_array()) {
?>
<tr>
<td id="1" style="display:none;"><?php echo $fetch['VesselID']?></td>
<td id="2"><?php echo $fetch['VesselName']?></td>
<td><input type="submit" class="button" name=<?php echo $fetch['VesselID']; ?> value="Upgrade"/></td>
</tr>`
This "Upgrade" button when click will call to a Javascript code that use the value inside the tag name to pass to another page using AJAX.
<script type = "text/javascript">
$('.button').click(function(){
alert($(this).attr('name'));
$.ajax({
type: "POST",
data: {
name: $(this).attr('name')
},
url: "vesselrecord.php",
dataType: "json",
async: true,
beforeSend: function(){
$(".ajaxTest").text("Trying to upgrade...");
},
complete: function(){
window.location.href = "vesselrecord.php";
},
success: function(data) {
$(".ajaxTest").text(data.a);
if (data.b == "true") {
location.reload();
}
}
});
});
</script>
I were able to prompt/alert the value of vessel identification using the "alert($(this).attr('name'));" then
Move/Transfer to the "vesselrecord.php
But inside the "vesselrecord.php" there is no value in the $_POST['name']. Looks like there is an issue on my ajax code. Can you guide me on this? TIA.
Below is my code inside the "vesselrecord.php"
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$vessel_id = strip_tags($_POST['name']);
}
When you change the location of the window, you make a $get request not $post, that is why you are not getting any value $_POST['name'].
You can change the location from-
window.location.href = "vesselrecord.php"
to-
window.location.href = "vesselrecord.php?myquerystringdata=" + $(this).attr("name");
and then on you php file you can write code to get value from query string.
'name' is nested within 'data'. Maybe you need to access data.name? I'm more used to JS than PHP so I'm not sure how to express this. Hope this helps.
data:{
name:'Al'
}

How to POST with AJAX using just an a tag

I have an a tag that is dynamically generated with database content, it includes a data-target that I capture in javascript when it is clicked on, this is an example of one of the generated buttons:
Edit
Simple, right?
Now, what I do in the JS when it is clicked, is as so:
var $this = $(this),
$target = $this.data("target"),
$endpointURL = "";
$endpointURL = $target.split("?id=")[0];
$id = $target.split("?id=")[1];
This allows me to set the endpoint I want, in out example above, it would be "edit" and also set the id which is just a number at this point.
Now, I have to POST this ID to the edit endpoint to return the right info, correct?
So, here is my AJAX for that:
$.ajax({
type: "POST",
data: '{"id": ' + $id + ' }',
url: "../assets/scripts/php/" + $endpointURL,
success: function (data) {
$("#content-lockup").html(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log("error: " + textStatus + ", error thrown: " + errorThrown);
}
});
This does not throw an error and does indeed output a var dump of the $_POST array as I have set it to, however it doesnt contain my ID that I passed over, here is the code on the endpoint and a screenshot of the output:
<?php
var_dump($_POST);
?>
Why would the vardump on $_POST not contain the id that I passed over in the apparently successful AJAX request?
What I expect is that I can say on the endpoint, something like:
$id = $_POST['id'];
Maybe its something obvious that i'm doing wrong but yeah, any ideas?
it's because you are passing a string to data that isn't form encoded
Make it an object and jQuery will encode it for you
data: {"id": $id },
If it's a string it needs to be in format
data: 'id=' +id + '&someOtherParam=' + somevar

JQuery / AJAX delete item from database

I'm trying to make a CRUD in jquery/ajax/php for learning purposes.
But I can't figure out what I'm doing wrong with the delete part.
My goal is to delete an record from the database without refreshing the page.
Ajax function:
$(document).on('click', '.deleteOrder', function(e){
var id = $(this).attr('id');
console.log('Clicked order: ' + id);
$.ajax({
type: 'POST',
url: 'orders/deleteorder/',
data: {
orderId: id
},
success: function(data){
updateOrder(e);
},
error: function(){
console.log('error');
}
});
});
Php function:
public function deleteOrder(){
$orderId = $_POST['id'];
$count=$this->connection->prepare("DELETE FROM orders WHERE orderNumber = :number");
$count->bindParam(":number",$orderId,PDO::PARAM_INT);
$count->execute();
echo 'Finished order ' . $orderId;
}
First check the delete function called or not through ajax, in browser Network tab (you see this when clicking F12 button in browser)
you did not call deleteOrder function .

php + JS button value save

Logic is that , on click div.buttons gonna hide and get second form : save date to mysql .. problem is in this : 1) i have to save grab name or value from buttons : problem no refresh page . i tried send date to php with ajax , with GET or POST methodes from js .. buttons are taken mysql and echoed in php like this : PHP: foreach ($res as $row) {
echo '<tr><td><button id="pupShow" name="'.$row["ID"].'">'.$row["SubjectName"].'</button> </td></tr>';
} JS:
$("button#pupShow").click(function () {
$("div.pupInput").show("slow");
$("div.showMarks").toggle("slow");
$("div.lessons").toggle("slow");
alert(this.name);
// $GLOBALS['myglob'] = this.name;
// window.location.href ="subID.php?subID="+this.name;
// return false;
this is js were i handle click on button
any help ?
i got eye on transforming first buttons into selected manue . so i could grab them by name from php , but its destroy my visual ..
If you don't want to reload the page, then you can try:
foreach ($res as $row) {
echo '<tr><td><button id="pupShow" name="'.$row["ID"].'" onclick="return false;">'.$row["SubjectName"].'</button> </td></tr>';
}
or
$("button#pupShow").click(function (el) {
el.preventDefault();
var data = 'nume=' + el.val()
$.ajax({
url: "subID.php",
type: "POST",
data: data,
cache: false,
success: function (html) {
if (html) {
// animations here
alert('Success! Form submitted');
} else{
alert('Error! Please try again');
}
}
});
I didn't test it but it should help you understand how the function will look like.
So you want to submit some data without refreshing the page? Since you're using jQuery, you can do something like this:
$.post("test.php", {name: "Mathematics"}).done(function(data) {
console.log("Response loaded: " + data);
});

Categories