Delete function not working properly - Ajax - javascript

I have a pm system and I would like for all checked messages to be deleted. So far, it only deletes one at a time and never the one selected. Instead it deletes the one with the youngest id value. I'm new to ajax and all help is appreciated.
Here's my function:
function deletePm(pmid,wrapperid,originator){
var conf = confirm(originator+"Press OK to confirm deletion of this message and its replies");
if(conf != true){
return false;
}
var ajax = ajaxObj("POST", "php_parsers/pm_system.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == "delete_ok"){
_(wrapperid).style.display = 'none';
} else {
alert(ajax.responseText);
}
}
}
ajax.send("action=delete_pm&pmid="+pmid+"&originator="+originator);
}

You may need to modify your form in order to do this. You have to pass the checkboxes to your PHP script as an array through ajax.
<input type='checkbox' name='pm[]' value='1'>1<br>
<input type='checkbox' name='pm[]' value='2'>2<br>
<input type='checkbox' name='pm[]' value='3'>3<br>
With the checkboxes like this, PHP can handle an array as such:
$_POST['pm'];
You will need to modify your ajax script to be able to send the array, and probably change your PHP script to loop thru the array value it receives. It's probably expecting an integer (a single ID) and you are about to send it an array.
Revised Ajax Method:
$("#submit").on('click',function(e) {
e.preventDefault();
var data = {
'pmIds': $("input[name='pm[]']").serializeArray(),
'action' : 'delete_pm',
'originator' : 'whatever'
};
$.ajax({
type: "POST",
url: 'php_parsers/pm_system.php',
data: data,
success: function(result) {
window.console.log('Successful');
},
});
})

Related

Ajax is not sending multiselect data to Django views

I am quite new to Django so bare with me.
I have a multiselct list in my webpage and I need to send the selected items to my views in order to make use of them.
To do so, I used ajax but when it doesn't seem to work for some reason.
This is the script:
$("#var_button").click(function(e) {
var deleted = [];
$.each($("#my-select option:selected"), function(){
deleted.push($(this).val());
});
alert("You have deleted - " + deleted);
e.preventDefault();
$.ajax({
type: "post",
url: "/description/upload-csv/" ,
data: {
'deleted' : deleted }
}); // End ajax method
});
I checked with alert if maybe the variable deleted is empty but it return the selected values so the problem is in my ajax query.
This is the part where I retrieve the data in my views.py
if request.method == 'POST':
del_var = request.POST.getlist("deleted[]")
my_class.del_var = del_var
I changed the data type to text but it doesn't do anything
I cant help you on the Django side.
$.each($('#selector'), (i, e) => {
deleted.push($(e).val());
})
but this will add the value to the "deleted" variable.

Laravel - AJAX POST Array of Choices from Checkboxes

I have an AJAX Post that I'm trying to fix, but with a multitude of checkboxes on the input, I'm getting stuck.
At the moment, say I've this:
<input type="checkbox" name="billToEmail[]" value="email1#email.com">email1#email.com
<input type="checkbox" name="billToEmail[]" value="email2#email.com">email2#email.com
And I've a button called "Send Notifications", which starts the following script:
<script>
$('.modal-footer').on('click', '.sendNotificationNow', function() {
$.ajax({
type:'POST',
url: '/shipments/sendNotifications',
data: {
'billTo': $('.billToEmail:checked').val(),
'shipTo': $('.shipToEmail:checked').val(),
'shipFrom': $('.shipFromEmail:checked').val(),
'_token': $('input[name=_token]').val(),
},
success: function(data) {
$('.errorTitle').addClass('hidden');
$('.errorContent').addClass('hidden');
if ((data.errors)) {
setTimeout(function () {
$('#sentNotifications').modal('show');
toastr.error('Validation error - Check your inputs!', 'Error Alert', {timeOut: 5000});
}, 500);
if (data.errors.title) {
$('.errorTitle').removeClass('hidden');
$('.errorTitle').text(data.errors.title);
}
if (data.errors.content) {
$('.errorContent').removeClass('hidden');
$('.errorContent').text(data.errors.content);
}
} else {
toastr.success('Successfully Sent Notifications!', 'Success Alert', {timeOut: 5000});
$('div.notificationssent').fadeOut();
$('div.notificationssent').load(url, function() {
$('div.notificationssent').fadeIn();
});
}
},
});
});
</script>
Now, I'm sure my issues are popping up near the top, where I'm trying to "translate" the multiple values into the data variables. Should I be putting something besides .val()?
I've a few more fields like this that I need to work on with the multiple checkboxes but if I can get some help for the billToEmail alone, I'm sure I can fix the remainder.
First, you don't need the [] sign. So, your checkbox html will look like this :
<input type="checkbox" name="billToEmail" value="email1#email.com">email1#email.com
<input type="checkbox" name="billToEmail" value="email2#email.com">email2#email.com
Second, you need to push selected value on checkbox into javascript array variable using foreach :
var billToEmail= [];
$("input:checkbox[name=billToEmail]:checked").each(function(){
billToEmail.push($(this).val());
});
Third, you need to convert javascript array into string using JSON.stringify().
billToEmails= JSON.stringify(billToEmail);
Then after that, pass the billToEmails variable into your data in AJAX. So, it will look like this :
var dataString = "billTo="+billToEmails+"&shipTo="+$('.shipToEmail:checked').val()+"&shipFrom="+$('.shipFromEmail:checked').val()+"&_token="$('input[name=_token]').val();
$.ajax({
type:'POST',
url: '/shipments/sendNotifications',
data: dataString,
In order to PHP can fetch the array, you need to decode the billToEmails string first using json_decode in your controller.
$variable = json_decode($request->billTo,true);
Try this-
billtoemail = $('input[name='billToEmail[]']:checked").map(function () {
return this.value;
}).get();
or
billtoemail= new Array();
$("input[name='billToEmail[]']").each(function(){
billtoemail.push(this.value);
});
Now send this variable billtoemail like other variable in your ajax. In your controller you can get all the values by a simple foreach($request->billTo as $billtoemail)

Insert data into MySQL Databse with PHP/AJAX, execute success option AFTER it's inserted (Callback)

I've been trying to make a simple site, and I can't quite wrap my head around some of the things said here, some of which are also unrelated to my situation.
The site has a form with 3 input boxes, a button, and a list. The info is submitted through a separate PHP file to a MySQL database, once the submit button is clicked. I'm supposed to make the list (it's inside a div) update once the info is successfully sent and updated in the database. So far I've made it work with async:false but I'm not supposed to, because of society.
Without this (bad) option, the list doesn't load after submitting the info, because (I assume) the method is executed past it, since it doesn't wait for it to finish.
What do I exactly have to do in "success:" to make it work? (Or, I've read something about .done() within the $.ajax clause, but I'm not sure how to make it work.)
What's the callback supposed to be like? I've never done it before and I can get really disoriented with the results here because each case is slightly different.
function save() {
var name = document.getElementById('name');
var email = document.getElementById('email');
var telephone = document.getElementById('telephone');
$.ajax({
url: "save.php",
method: "POST",
data: { name: name.value, email: email.value, telephone: telephone.value },
success: $("List").load(" List")
});
}
Thank you in advanced and if I need include further info don't hesitate to ask.
From this comment
as far as i know the success function will be called on success you should use complete, A function to be called when the request finishes (after success and error callbacks are executed). isnt that what you want ? – Muhammad Omer Aslam
I managed to solve the issue simply moving the $.load clause from the success: option to a complete: option. (I think they're called options)
I haven't managed error handling yet, even inside my head but at least it works as it should if everything is entered properly.
Thanks!
(Won't let me mark as answered until 2 days)
I would first create an AJAX call inside a function which runs when the page loads to populate the list.
window.onload = populatelist();
function populatelist() {
$.ajax({
type: "POST",
url: "list.php",
data: {function: 'populate'},
success: function(data) { $("#list").html("data"); }
});
}
Note: #list refers to <div id="list> and your list should be inside this.
I would then have another AJAX call inside a different function which updates the database when the form is submitted. Upon success, it will run the populatelist function.
function save() {
var name = document.getElementById('name');
var email = document.getElementById('email');
var telephone = document.getElementById('telephone');
$.ajax({
type: "POST",
url: "list.php",
data: {function: 'update', name: name.value, email: email.value, telephone: telephone.value },
success: function() { populatelist(); }
});
}
list.php should look like this:
<?php
if($_POST['function'] == "populate") {
// your code to get the content from the database and put it in a list
}
if($_POST['function'] == "update") {
// your code to update the database
}
?>
I will show you piece of solution that I use in my project. I cannot say it is optimal or best practices, but it works for me and can work for you:
PHP:
function doLoadMails(){
//initialize empty variable
$mails;
$conn = new mysqli($_POST['ip'], $_POST['login'], $_POST['pass'], $_POST['db']);
// Check connection
if ($conn->connect_error) {
die("");
}
//some select, insert, whatever
$sql = "SELECT ... ... ... ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row, j is counter for rows
$j =0;
while($row_a = $result->fetch_assoc()) {
//for each row, fill array
$mails[$j][0] = $row_a["name"] ;
$mails[$j][1] = $row_a["mail"] ;
$mails[$j][2] = $row_a["language"] ;
$j++;
}
}
//if $mails has results (we added something into it)
if(isset($mails)){
echo json_encode($mails);/return json*/ }
else{
//some error message you can handle in JS
echo"[null]";}
}
and then in JS
function doLoadMails() {
$.ajax({
data: { /*pass parameters*/ },
type: "post",
url: "dataFunnel.php",
success: function(data) { /*data is a dummy variable for everything your PHP echoes/returns*/
console.log(data); //you can check what you get
if (data != "[null]") { /*some error handling ..., in my case if it matches what I have declared as error state in PHP - !(isset($mails))*/ }
}
});
Keep in mind, that you can echo/return directly the result of your SQL request and put it into JS in some more raw format, and handle further processing here.
In your solution, you will probably need to echo the return code of the INSERT request.

Wordpress get current page name or id within ajax request callback

I need to get current page id or name from ajax request callback. Initially at loading a page i made an ajax request. In its callback method i need to get the current page id or name. I used following code for ajax request.
$.ajax({
type: "POST",
url: my_site.home_url + '/wp-admin/admin-ajax.php',
data: {
action: "notes_select_page"
},
dataType: "html",
success: function (Response) {
if (Response == "OK") {
Notes.renderBoardList();
} else {
}
},
async: true
});
I took the request from action hook.
add_action('wp_ajax_nopriv_notes_select_page', 'Notes::select_page');add_action('wp_ajax_optimal_notes_select_page', 'Notes::select_page');
And the callback i used several code but doesn't work. Try 1.
public static function select_page(){
global $pagename;
die($pagename);
}
Try 2
public static function select_page(){
global $wp_query;
$pagename = get_query_var( 'pagename' );
if ( !$pagename) {
$post = $wp_query->get_queried_object();
$pagename = $post->post_name;
}
die($pagename);
}
Try 3
public static function select_page(){
global $post;
die($post->ID);
}
But unfortunately any of them doesn't work to get current page ID or name. Callback is working fine with other values.
Thanks in advance.
function get_current_page_id() {
var page_body = $('body.page');
var id = 0;
if(page_body) {
var classList = page_body.attr('class').split(/\s+/);
$.each(classList, function(index, item) {
if (item.indexOf('page-id') >= 0) {
var item_arr = item.split('-');
id = item_arr[item_arr.length -1];
return false;
}
});
}
return id;
}
You don't need ajax for this.
Add this function to your code.
You can now get the page id by using:
var id = get_current_page_id();
To retrieve the post details you have to send the data yourself
data:{
action: "notes_select_page",
post_id: current_post_id, //current_post_id should either parsed from DOM or you can write your ajax in PHP file
}
You can either use a hidden box for current post id and get in the Js file using class or id or write the ajax in you php file itself.
Then you can retrieve via POST
public static function select_page(){
$post_id = $_POST['post_id'];
}
I'm getting post ID from the default WordPress post editing form, like so :
var post_ID = jQuery('[name="post_ID"]').val()*1;
Tje *1 converts the ID into an integer, otherwise it's interpreted as a string.
First take page id by this function
either
<div id="current_page_id"> <?php get_the_ID(); ?> </div>
or
<body page-id="<?php get_the_ID(); ?>">
Now In jquery ajax take following
var page_id = $('current_page_id').html();
OR
var page_id = $('body').attr("page-id");
$.ajax({
type: "POST",
url: my_site.home_url + '/wp-admin/admin-ajax.php',
data: {
action: "pageid="+page_id,
},
dataType: "html",
success: function (Response) {
if (Response == "OK") {
Notes.renderBoardList();
} else {
}
},
async: true
});
There is a solution to solve the issue in Wordpress. Adding ajax code in wp_footer hook, where using php code current page id can be retrieved and pass as ajax value.
You can obtain alternatively by the hidden field the post/page id in the following manner. This code is inserted in the template file (and then the value will be send to your ajax action hook as indicated above):
<?php
echo '<input type="hidden" name="activepost" id="activepost"
value="'.get_the_ID().'" />'
;?>
Check out this for reference: https://developer.wordpress.org/reference/functions/get_the_id/

Update mysql data on textarea click off

I have this code below:
<?php
$stmt = $pdo_conn->prepare("SELECT * from controldata where field = :field ");
$stmt->execute(array(':field' => 'notice_board'));
$result = $stmt->fetch();
?>
<textarea id="notice_board_textarea" data-id="notice_board" rows="8"><?php echo stripslashes(strip_tags($result["value"])); ?></textarea>
<script type="text/javascript">
$('#notice_board_textarea').on('blur', function () { // don't forget # to select by id
var id = $(this).data('id'); // Get the id-data-attribute
var val = $(this).val();
$.ajax({
type: "POST",
url: "dashboard.php?update_notice_board=yes",
data: {
notes: val, // value of the textarea we are hooking the blur-event to
itemId: id // Id of the item stored on the data-id
},
});
});
</script>
which selects data from a MySQL database and shows it in a textarea
then then JS code updates it by POSTing the data to another page but without refreshing the page or clicking a save/submit button
on dashboard.php i have this code:
if($_GET["update_notice_board"] == 'yes')
{
$stmt = $pdo_conn->prepare("UPDATE controldata SET value = :value WHERE field = :field ");
$stmt->execute(array(':value' => $_POST["notes"], ':field' => 'notice_board'));
}
but its not updating the data
am i doing anything wrong?
Wrong:
if ($_POST["update_notice_board"] == 'yes') {
Right:
if ($_GET['update_notice_board'] == 'yes') {
When you append something straight to the URL, it is ALWAYS GET:
url: "dashboard.php?update_notice_board=yes",
Updated answer:
Based on what's written in the comments below, my guess is, it is a server side issue, beyond what is shared here. Perhaps dashboard.php is part of a framework that empty the super globals or perhaps the request is not going directly to dashboard.php
Old suggestions:
When you use type: "POST" you wont find the parameters in the $_GET variable. (U: Actually you probably would find it in $_GET, but in my opinion it's cleaner to put all vars in either $_GET or $_POST, although there may be semantic arguments to prefer the splitting).
Add your parameter to the data object of your ajax call and read it from the $_POST variable instead:
$.ajax({
type: "POST",
url: "dashboard.php",
data: {
notes: val, // value of the textarea we are hooking the blur-event to
itemId: id, // Id of the item stored on the data-id
update_notice_board:"yes"
},
success: function(reply) {
alert(reply);
},
error:function(jqXHR, textStatus, errorThrown ) {
alert(textStatus);
}
});
and
if($_POST["update_notice_board"] == 'yes')
(You may also look in $_REQUEST if you don't care whether the request is get or post.)
Compare the documentation entries:
http://www.php.net/manual/en/reserved.variables.get.php
http://www.php.net/manual/en/reserved.variables.post.php
http://www.php.net/manual/en/reserved.variables.request.php
Working client-side example:
http://jsfiddle.net/kLUyx/

Categories

Resources