iQuery ajax request returns empty $_POST - javascript

I'm creating a table containing a list of uploaded files and I wanted to add a link in the last column to allow the user to delete the corresponding file. I could simply use a link "delete.php?fileid=", but I prefer to use a POST request and so I decided to use a form with the ID of the file in the database being passed as hidden input.
Issue: console.log($(this).closest('form').find(":input").serialize()); returns an empty string. Can you help understanding what is the root cause?
Code of form submission:
$('.f-delete a'). click(function(e){
e.preventDefault();
console.log($(this).closest('form').find(":input").serialize());
$.ajax({
type: "POST",
url: 'delete_image.php',
dataType: 'json',
data: $(this).closest('form').find(":input").serialize(),
success: function(response){
console.log(response);
},
error: function(){
alert('Error: Could not delete the file');
}
});
});
The markup:
<table class="table table-striped">
<thead>
<tr>
<th>Title</th>
<th>Type</th>
<th>Size</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>Test file</td>
<td>image/png</td>
<td>302.65 KB</td>
<td>
<form id="f-1" class="f-delete" method="post" action="delete_image.php">
<input id="id-1" value="1" type="hidden">
<a id="a-1" href="">Delete image</a>
</form>
</td>
</tr>
<tr>
<td>Test file 2</td>
<td>image/png</td>
<td>37.88 KB</td>
<td>
<form id="f-2" class="f-delete" method="post" action="delete_image.php">
<input id="id-2" value="2" type="hidden">
<a id="a-2" href="">Delete image</a>
</form>
</td>
</tr>
</tbody>
</table>

The problem is in your html, for use serialize your input's should have name. For example:
<input id="id-1" value="1" name="id-1" type="hidden">
For serialize use
$(this).closest('form').serialize() //return id-1=1
Result https://jsfiddle.net/cmedina/1Lv8gkms/

Related

Retrive data using PHP and Ajax

Here I am trying to fetch data from Mysql database using PHP and Ajax. My problem is, when I type the Test ID on test_id text box, just it immediatetly shows the Test Name according to the Test ID on test_name text box.
Here I used the function called checkname. In console just it show the Test Name but does not show in the test_name text box.
Here is the HTML code.
<table class="table table-hover table-white">
<thead>
<tr>
<th class="col-sm-1">Test ID</th>
<th class="col-md-6">Test Name</th>
<th style="width:100px;">Amount</th>
<th> Action</th>
</tr>
</thead>
<tbody id="rows">
<tr>
<td> <input class="form-control" type="text" style="width:200px" id="test_id[]" onblur="checkname();" onkeyup="checkname();" onchange="checkname();"> </td>
<td> <input type="text" style="width:300px" class="form-control text-right form-amt" readonly="" id="test_name[]" > </td>
<td> <input type="text" style="min-width:100px" class="form-control text-right form-amt" readonly="" id="amount[]"> </td>
<td><center> <i class="fa fa-plus"></i> </center> </td>
</tr>
</tbody>
</table>
Here is the Ajax code;
<script>
function checkname()
{
var test_id = document.getElementById("test_id[]").value;
$.ajax({
type: 'post',
url: "adminquery/fetch_test_name.php", // request file the 'check_email.php'
data: {'test_id': test_id, },
success: function (data) {
$("#test_name[]").html(data);
}
});
}
</script>
Here is the PHP code
<?php
include('../auth/dbconnection.php');
$output='';
$sql="SELECT * from testings where test_id='".$_POST['test_id']."'";
$result=mysqli_query($conn,$sql);
while($row=mysqli_fetch_array($result)){
$name= $row["testing_name"];
$output.=' <input type="text" readonly="" id="test_name[]" value="'.$name.' "> '.$name.' ';
}
echo $output;
?>
Anyone could help me may highly appreciated.
First lose the brackets in the id.
<input id="test_name" type="text" value="other" />
Then use .val() instead of .html()
$("#test_name").val("something")

How to push Json object to Json array using for loop?

I have a html table where onclick dynamically rows added. I need to convert that row textbox values into JSON array.
Note: Ajax must be used because I need to save data to sql server.
Here is my attempt.
$(function() {
$("[id*=btnSave]").click(function() {
$("[id*=data_table] tbody").each(function() {
var arr = [];
var user = {};
for (i = 0; i <= 1; i++) {
user.DueDate = $(this).find('tr:eq(' + i + ') td:eq(0) input').val();
user.DueAmount = $(this).find('tr:eq(' + i + ') td:eq(1) input').val();
arr.push(user); // Json array has every json object value
$.ajax({
async: true,
cache: false,
type: "POST",
url: "Default.aspx/Save",
data: JSON.stringify(user),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
alert("Data added successfully.");
alert(JSON.stringify(user)); //Json object value //Alert 2
alert(JSON.stringify(arr)); //Json array value //Alert 3
}
}); //End of ajax
return false;
} //End of for loop
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table cellspacing="3" cellpadding="3" id="data_table" width="50%">
<thead>
<tr>
<th width="30%">Due date</th>
<th width="26%">Amount Due</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td width="30%">
<input type="text" id="Text1" autocomplete="off" placeholder="Due Date" runat="server" />
</td>
<td width="25%">
<input type="text" runat="server" id="new_Amount_1" placeholder="0.00" autocomplete="off" />
</td>
<td>
<input type="button" value="Delete" />
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>
<input type="button" value="Add row" id="btnAddRow" />
<input type="button" value="Save" id="btnSave" />
</td>
</tr>
</tfoot>
</table>
I used for loop to get every dynamically added row values.
My output should be like this.
Alert2 Json object format
{"DueDate":"17/09/2019","DueAmount":"100"}
Alert3 Json array format
[{"DueDate":"17/09/2019","AmountDue":"100"},{"DueDate":"18/09/2019","AmountDue":"200"},{"DueDate":"19/09/2019","AmountDue":"300"}]
But in My output Alert3 I am getting first object only
[{"DueDate":"17/09/2019","DueAmount":"100"}]
What I have done wrong? I think for loop is not correct. Please help me with that.
Yes, you can use .serialize() or .serializeArray() and these two functions only runs on a form tag.
In your code if you are adding tr tag each time that you press btnAddRow, your for loop is wrong:
for (i = 0; i <= 1; i++)
Replace with:
for (i = 0; i <= $(this).find('tr').length; i++)
Instead of looping this, you can directly use the serializeArray or serialize if you need a custom format
$("form").on("submit", function(event) {
event.preventDefault();
console.log($(this).serializeArray());
$.ajax({
async: true,
cache: false,
type: "POST",
url: "Default.aspx/Save",
data: JSON.stringify($(this).serializeArray()),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
console.log("Data added successfully.");
}
}); //End of ajax
});
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<form>
<table cellspacing="3" cellpadding="3" id="data_table" width="50%">
<thead>
<tr>
<th width="30%">Due date</th>
<th width="26%">Amount Due</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td width="30%">
<input type="text" name="Text1" autocomplete="off" placeholder="Due Date" runat="server" />
</td>
<td width="25%">
<input type="text" runat="server" name="new_Amount_1" placeholder="0.00" autocomplete="off" />
</td>
<td>
<input type="button" value="Delete" />
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>
<input type="button" value="Add row" id="btnAddRow" />
<input type="submit" value="Save" id="btnSave" />
</td>
</tr>
</tfoot>
</table>
</form>

Universal form submitting function for all forms in a page

I'm trying to write a universal jquery function to submit all forms in a table when their submit button is clicked.
What I've got so far is this:
<div class="tabelaportes">
<div class="galltitle">Tabela de Portes de Envio</div>
<table cellpadding="0" cellspacing="0" border="1">
<tr>
<td class="tdleft">Peso inicial (kg) </td>
<td class="tdleft">Peso final (kg) </td>
<td class="tdleft">Valor (€) </td>
<td class="tdleft">Acção</td>
</tr>
<tr>
<td class="tdright">
1.00 kg
</td>
<td class="tdright">
2.00 kg
</td>
<td class="tdright">
3.00 €
</td>
<td class="tdright">
<form method="post">
<input type="hidden" name="kgid" value="34"/>
<input type="submit" name="rmkgid" value="Remover"/>
</form>
</td></tr>
<tr>
<td class="tdright">
3.00 kg
</td>
<td class="tdright">
4.00 kg
</td>
<td class="tdright">
5.00 €
</td>
<td class="tdright">
<form method="post">
<input type="hidden" name="kgid" value="56"/>
<input type="submit" name="rmkgid" value="Remover"/>
</form>
</td></tr>
<tr>
<form method="post">
<td>
<input type="text" name="kg_i"/>
</td>
<td>
<input type="text" name="kg_f"/>
</td>
<td>
<input type="text" name="kg_p"/>
</td>
<td>
<input type="submit" name="addprice" value="Adicionar"/>
</td>
</form>
</tr>
</table>
</div><script>
function submitPortes() {
var siteurl = window.location.href;
$("form").submit(function(sp) {
//get form values
var submitname = $(this).parents("tr").find("input[type=submit]").attr("name");
var submitval = $(this).parents("tr").find("input[type=submit]").val();
var dataString = $(this).serialize() + "&"+ submitname + "="+ submitval;
console.log("dataString: " + dataString);
//submit form
$.ajax({
type: "POST",
url: siteurl,
data: dataString,
success: function(){
$.ajax({
url: siteurl,
type:"GET",
success: function(portes){
//reload page
var reloadPortes = $(portes).find("div.tabelaportes table").html();
$("div.tabelaportes table").hide().html(reloadPortes).fadeIn("fast");
//reload form to add more
submitPortes();
}
});
}
});
return false;
});
}
submitPortes();
</script>
So, in this case all the forms are in a table. Each row has its own form to remove a row and in the last row, you add rows to the table.
The function submits the forms and reloads the table.
When removing a row, the function works every time, but when adding a row, it only works the first time. What can I do to make it work every time?
Is it even possible to have one function for all forms?
I'm not quite sure what you mean by "It only works the first time". but perhaps try registering the event at the table level, so that it will be re-evaluated to include the addition of more form elements.
$('#tabelaportes').on('submit', 'form', function(){...});
(note: this may not work with your initialization pattern, perhaps move init inside a $(document).ready( function() {}); block?)

How to load only the content area when click submit button?

My code is like this :
<html>
<head>
<title>Test Loading</title>
</head>
<body>
<div id="header">
This is header
</div>
<div id="navigation">
This is navigation
</div>
<div id="content">
<form action="test2.php" method="post">
<table>
<tr>
<td>First Name</td>
<td>:</td>
<td><input type="text" name="first_name"></td>
</tr>
<tr>
<td>Last Name</td>
<td>:</td>
<td><input type="text" name="last_name"></td>
</tr>
<tr>
<td>Age</td>
<td>:</td>
<td><input type="text" name="age"></td>
</tr>
<tr>
<td>Hobby</td>
<td>:</td>
<td><input type="text" name="hobby"></td>
</tr>
<tr>
<td></td>
<td></td>
<td><input type="submit" Value="Submit"></td>
</tr>
</table>
</form>
</div>
<div id="footer">
This is footer
</div>
</body>
</html>
The complete code of test1.php : http://pastebin.com/idcGms0h
The complete code of test2.php : http://pastebin.com/rvBPTrhn
I want to load only the content area and skip header, navigation and footer loading
Besides that, I also want to add loading
Seems to use ajax, but I am still confused
How to load only the content area when click submit button?
Any help much appreciated
Cheers
you need to use ajax. please try this instead
before submit
<!DOCTYPE html>
<html>
<head>
<title>Test Loading</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<div id="header">
This is header
</div>
<div id="navigation">
This is navigation
</div>
<div id="content">
<form action="" id="info">
<table>
<tr>
<td>First Name</td>
<td>:</td>
<td><input type="text" name="first_name"></td>
</tr>
<tr>
<td>Last Name</td>
<td>:</td>
<td><input type="text" name="last_name"></td>
</tr>
<tr>
<td>Age</td>
<td>:</td>
<td><input type="text" name="age"></td>
</tr>
<tr>
<td>Hobby</td>
<td>:</td>
<td><input type="text" name="hobby"></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</form>
</div>
<button id="submit">Submit</button>
<div id="footer">
This is footer
</div>
</body>
</html>
<script type="text/javascript">
var postData = "text";
$('#submit').on('click',function(){
$.ajax({
type: "post",
url: "test2.php",
data: $("#info").serialize(),
contentType: "application/x-www-form-urlencoded",
success: function(response) { // on success..
$('#content').html(response); // update the DIV
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
})
});
</script>
before submit form
test2.php contents
<table>
<tr>
<td>First Name</td>
<td>:</td>
<td> <?php echo $_POST['first_name']; ?></td>
</tr>
<tr>
<td>Last Name</td>
<td>:</td>
<td><?php echo $_POST['last_name']; ?></td>
</tr>
<tr>
<td>Age</td>
<td>:</td>
<td><?php echo $_POST['age']; ?></td>
</tr>
<tr>
<td>Hobby</td>
<td>:</td>
<td><?php echo $_POST['hobby']; ?></td>
</tr>
after submit form
You need to use ajax . to update only a part of the page. firstly,give
unique id's to form elements
1. i have given form an id regForm
2. submit button an id submitButton
you can either listen to form submit or click of the submit button
listening to the click of submit button ....
$("input#submitButton").on("click",function(event){
event.preventDefault();
var data = $('form#regForm').serialize();
$.ajax({
url: "test2.php",
method: "POST",
data: { data : data },
dataType: "html"
})
.done(function( responseData ) {
console.log("theresponse of the page is"+responseData);
$("div#content").empty();
///now you can update the contents of the div...for now i have just entered text "hey i m edited" ....and i have considered that you will echo out html data on test2.php .....so specified data type as html in ajax.
$("div#content").html("hey i m edited");
})
.fail(function( jqXHR, textStatus ) {
console.log("error occured");
});
})
Well you have to use jquery ajx for that.istead of writting a big code you can just use this plugin http://malsup.com/jquery/form/ when you using this plugin you don't have to change anything of your form (except setting a form ID)
$(document).ready(function() {
var options = {
target: '#output', //this is the element that show respond after ajax finish
};
// bind to the form's submit event
$('#myForm').submit(function() {
$(this).ajaxSubmit(options);
return false;
});
});
Change your form like that:
<form action="test2.php" method="post" id="myForm">

send data to a new jsp page when user click on a row

<form action="" method="get" enctype="application/x-www-form-urlencoded">
<h3>Current Users</h3>
<c:if test="${!empty userList}">
<table class="data" id="results" border="1" >
<tr>
<th>Name</th>
<th>Email</th>
<th>Last Seen</th>
</tr>
<c:forEach items="${userList}" var="user">
<tr onmouseover="ChangeColor(this, true);"
onmouseout="ChangeColor(this, false);"
onclick="DoNav('${pageContext.request.contextPath}/secure/detailUserView');">
<td>${user.name}</td>
<td>${user.email}</td>
<td>${user.create_date}</td>
</tr> >
</c:forEach>
</table>
</c:if>
<div id="pageNavPosition"></div>
</form>
Now what i want is to send the user information to a new jsp page when user click on a particular row. how can i do it please suggest
Romi.
http://www.w3schools.com/html/html_forms.asp
You can use forms to submit data. The values on the tags will be submitted as request params to the url specified in the form's action.

Categories

Resources