data not pass using ajax after onclick - ajax

I'm trying to remove an element from the database.
I don't know why, but the data is not getting to the url i inserted.
this is the code (the obj is indeed faded - only in the client side):
$(document).on("click", "#deleteAdmin", function(e) {
$.ajax({
url: "admin/adminProccess.php",
type: "get",
data: $('#idPriv:checked').serialize() + '&str=' + 'deleteAdmin',
success: function(data) {
$('#idPriv:checked').each(function(){
$(this).parent().parent().remove();
});
var item = $(deleteAdmin);
item.fadeOut();
}
});
});
is there something wrong in my code?
when i'm trying to access manually to the url i can see some results - but with my code its not sending the data.
any ideas?
edit: this is my idPriv:
<input type = "checkbox" name="idPriv[]" id="idPriv" onclick="evaluateIT(this)" data-related-item="adminPanelShow" value ="<?php echo $value["id"].':'. $count; ?>" />

Try to change:
$('#idPriv:checked').serialize() + '&str=' + 'deleteAdmin'
to:
$('#idPriv:checked').val() + '&str=' + 'deleteAdmin'

Related

Bootstrap Select 'refresh" continues to add new options instead of removing the old ones

Any help here would be appreciated as I can't see what I'm doing wrong.
I have an empty select picker:
<select class='selectpicker' name='new_teamid' id='new_teamid' style='width:200px;margin-left:-5px;margin-top:0px;' required></select>
This is being populated via AJAX call when another select box option has changed
var query_parameter = document.getElementById("new_deptid").value;
var dataString = 'dept=' + query_parameter;
// AJAX code to execute query and get back to same page with table content without reloading the page.
$.ajax({
type: "POST",
url: "helpers/populateteams.php",
data: dataString,
cache: false,
success: function(html) {
document.getElementById("new_teamid").innerHTML=html;
$('#new_teamid').selectpicker('refresh');
}
});
As you can see, its calling another php page which returns an HTMl string for the options. This works, if i inspect the element, the HTML options are updated correctly. im using = not +=. Problem is, the selectpicker is not removing the previous items. It just keeps adding the new items.
Any idea what I may be doing wrong here?
If you are curious, this is the populateteams.php
$theHTML = "";
$theHTML .= '<option value="" selected>Please Select</option>';
$sql = "SELECT * FROM tool_teams WHERE (dept_id=?) ORDER BY teamname asc";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $dept_id);
if ($stmt->execute() === TRUE) {
$result = $stmt->get_result();
if(!empty($result) && $result->num_rows)
{
while ($row = mysqli_fetch_array($result))
{
$theHTML .= '<option value="'.$row['team_id'].'">'.$row['teamname'].'</option>';
}
}
}
echo $theHTML;
resolved this myself. This is dumb, but this is how you need to do it:
$.ajax({
type: "POST",
url: "helpers/populateteams.php",
data: dataString,
cache: false,
success: function(html) {
document.getElementById("new_teamid").innerHTML=html;
$('#new_teamid').selectpicker('destroy');
$('#new_teamid').selectpicker('render');
},
complete: function(html) {
}
});
You need to destroy and render instead of refresh. This is stupid. But it works

Form-data only append last multiple selection

This may be duplicate but I can't solve it.
I can send multiple images by JQuery/Ajax to my server (Asp.Net Core) and save them successfully. But the problem is when I want to add the second batch files, the first batch will not append to form data. I add images with a button and not by input type="file" field.
HTML:
<form asp-area="User" asp-controller="Item" asp-action="Create" id="createForm" method="post" enctype="multipart/form-data" >
<input asp-for="ImageUrl" id="myInput" type="file" name="inputFile[]" accept="image/*" multiple style="display:none" />
<button id="myButton" type="button">+ Add Files</button>
JS:
$(document).ready(function () {
var inputFile = $('#myInput');
$('#myButton').click(function () {
$('#myInput').click();
});
var files = [];
$('#myInput').change(function () {
var newFiles = [];
for (var index = 0; index < inputFile[0].files.length; index++)
{
let file = inputFile[0].files[index];
files.push(file);
}
});
});
$("#createForm").submit(function (e) {
e.preventDefault();
var formData = new FormData(document.getElementById('createForm'));
//var formData = new FormData(this);
files.forEach(file => {
formData.append('file[]', file);
});
for (var pair of formData.entries()) {
console.log(pair[0] + ', ' + pair[1]);
}
$.ajax({
type: "POST",
cache: false,
processData: false,
contentType: false,
url: $("#createForm").attr('action'),
enctype: 'multipart/form-data',
data: new FormData(this),
});
});
});
Suppose I choose pictures 1,2,3 and submit my form and all 3 pictures save to server side successfully. Now let's try a new record: I add pictures 1,2,3, after that I choose pictures 4,5,6 so I expect to 6 images to be appended to form data. But only the last selection 4,5,6 are saved to server !
This is my console report in below.As you can see I have input-File[]=3 !! Something like I have no jquery and no ajax and just using pure HTML/Input Multiple file and I can upload only my last selections !!
But when I refresh my page and choose just 1,2,3 images (one selection only), I have input-File[]=3 and file[], [object File]=3 and every thing is good.
I tried data: new FormData() and data: formData and many other options on data parameter but no one could solve my problem :(
Update : ******************************:
Case 1:
var formData = new FormData(document.getElementById('createForm'));
. . .
data: formData,
Results: No image save in server and ImageUrl is null in database.
Case 2:
var formData = new FormData()
. . .
data: formData,
Results in error in console : XML Parsing Error: no root element found
Case 3:
var formData = new FormData(this)
. . .
data: formData,
Results : suppose I select images 1,2,3 at first and then select images 4,5,6. I have images 1,2,3,4,5,6 saved on server and 4,5,6 save twice !! I'm getting near but still can't manage it.
.
I think there might be an error in the way that you copied your code. There is an extra }); after $('#myInput').change(function () { ... });
I'm assuming that is not part of the issue and was just a mistake in pasting it over.
The issue I think is that you were trying to send the files over separately from the inputFiles. Updating the for loop in the submit event handler should give you what you are wanting.
$("#createForm").submit(function (e) {
e.preventDefault();
var formData = new FormData();
files.forEach((file) => {
formData.append('inputFile[]', file);
});
for (var pair of formData.entries()) {
console.log(pair[0] + ', ' + pair[1]);
}
$.ajax({
type: "POST",
cache: false,
processData: false,
contentType: false,
url: $("#createForm").attr('action'),
enctype: 'multipart/form-data',
data: formData,
});
});

done not executed ajax

Im having this piece of code. Where I use this Action to get trigger an export that downloads an excel file. Which works perfectly when I type the link and argument in my browser, the file gets downloaded.
But I want to call this from an ajaxified context and this is where it all gets wrong.
<script type="text/javascript">
function exportPerson(e) {
e.preventDefault();
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
var action = '#Url.Action("ExportContactAlarmList", "Contact")';
$.ajax({
url: action + '/' + dataItem.Id,
type: "POST",
done: function(response) {
var dataURI = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" +
kendo.util.encodeBase64(response);
kendo.saveAs({
dataURI: dataURI,
fileName: "PersonExport.xlsx",
proxyURL: "#Url.Action("Save", "Home")"
});
}
});
}
</script>
I'm kind of stuck because the done method never gets executed. And I don't know why.
These are my responses from my headers I get back.
Everything looks good, no errors in the console.
Normally I use $.ajax with these functions:
success = A function to be called if the request succeeds
error = A function to be called if the request fails
complete = A function to be called when the request finishes (after success and error callbacks are executed). I also use it to stop the loading bar.
beforeSend = A pre-request callback function. Even used to start loading bar.
So I would suggest you to use this:
success: function(response) {...
ref: http://api.jquery.com/jquery.ajax/
I am not sure, but there are some restrictions to download files using XMLHttpRequest. Maybe if you define the header before... See accepts settings form $.ajax and dataType.
Good luck!
try this
$.ajax({
url: action + '/' + dataItem.Id,
type: "POST",
success: function(response) {
var dataURI = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" +
kendo.util.encodeBase64(response);
kendo.saveAs({
dataURI: dataURI,
fileName: "PersonExport.xlsx",
proxyURL: "#Url.Action("Save", "Home")"
});
}
});
or
$.ajax({
url: action + '/' + dataItem.Id,
type: "POST"
}).done(function(response) {
var dataURI = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" +
kendo.util.encodeBase64(response);
kendo.saveAs({
dataURI: dataURI,
fileName: "PersonExport.xlsx",
proxyURL: "#Url.Action("Save", "Home")"
});
});

when ajax post success i want to refresh a particular <div> in page

i want to refresh a particular div on ajax success, im using the below code but the whole page getting refreshed.
<script type="text/javascript">
$('#post_submit').click(function() {
var form_data = {
csrfsecurity: $("input[name=csrfsecurity]").val(),
post_text: $('#post_text').val()
};
$.ajax({
url: "<?php echo site_url('/post_status'); ?>",
type: 'POST',
data: form_data,
success: function(response){
$(".home_user_feeds").html("markUpCreatedUsingResponseFromServer");
}
return false;
});
return false;
});
</script>
you have an extra return false which is inside the $.ajax block which most probably causes an error so your form isn't submitted via ajax. If you remove that, you shouldn't have any issues.
Use the submit event of the form and remove the return false from the ajax callback:
$('#myFormId').on('submit', function() {
var form_data = {
csrfsecurity: $("input[name=csrfsecurity]").val(),
post_text: $('#post_text').val()
};
$.ajax({
url: "<?php echo site_url('/post_status'); ?>",
type: 'POST',
data: form_data,
success: function(response){
$(".home_user_feeds").html("markUpCreatedUsingResponseFromServer");
}
});
return false;
});
Remove the return false from inside your $.ajax function. Its a syntax error. The $.ajax function only expects a json object as an argument. "return false" cannot be part of a json object. You should keep the JavaScript console open during testing at all times - Press Ctrl-Shift-J in Chrome and select console to see any JS errors.
Also suggest you use <input type=button> instead of <input type=submit> or <button></button>

Pass Ajax POST variable to JQuery UI dialog

Below is an Ajax POST variable I use to return some information to an ASP MVC3 View. However, I cannot get the .dialg() pop-up function to work. Right now you click on the icon that calls GetProgramDetails(pgmname), and nothing happens. First time using Ajax, so any suggestions would be appreciated. Thx!
<script src="http://code.jquery.com/jquery-1.8.3.js" type="text/javascript"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js" type="text/javascript"></script>
<script type="text/javascript">
function GetProgramDetails(pgmname) {
var request = $.ajax({
type: 'POST',
url: '/BatchPrograms/PopDetails',
data: { programName: pgmname },
dataType: 'html'
});
request.done(function (data) {
$('#data').dialog();
});
</script>
EDIT
I've updated the request.done function to include a simple alert to see if the code was being called. After stepping through with Chrome's debugger, I saw that the code inside was completely skipped over.
request.done(function (data) {
alert("HERE!");
$('#programExplanation').html(data);
});
SECOND EDIT
Here is the controller code the ajax is returning a value from:
[HttpPost]
public string PopDetails(string programName)
{
BatchPrograms batchprograms = db.BatchPrograms.Find(programName);
if (batchprograms == null) return string.Empty;
StringBuilder s = new StringBuilder();
s.Append(batchprograms.ProgramName + " - " + batchprograms.ShortDescription);
s.Append("<br />Job Names: " + batchprograms.PrdJobName + ", " + batchprograms.QuaJobName );
s.Append("<br /> " + batchprograms.Description);
return s.ToString();
}
You need to use the success method to handle the callback, like so:
var request = $.ajax({
type: 'POST',
url: '/BatchPrograms/PopDetails',
data: { programName: pgmname },
dataType: 'html'
}).success(function(data){ $('#data').dialog()} );
This will launch the dialog for you, but if you want to get the response data to work with it, you can have GetProgramDetails take a second parameter which is a callback for after the data is loaded like so:
function GetProgramDetails(pgmname, callback) {
var request = $.ajax({
type: 'POST',
url: '/BatchPrograms/PopDetails',
data: { programName: pgmname },
dataType: 'html'
}).success(callback);
}
This way after the response is received you can handle what to do with the data in your implementation of the callback, in this case it seems like you will be setting data in the dialog and launching the dialog.

Resources