How can I pass a variable to alert() with $.ajax? - javascript

I want to let the user confirm to deletion of a record by letting them click on the button and the button sends the value Yes to a $_POST request so I can delete the record with PHP, instead it's showing me the javascript file that contains the function.
What am I doing wrong, I've been tinkering and searching for 3 hours straight, while in the back of my mind I know it's a easy fix.
Any help is greatly appreciated.
If you think there is a smarter way to be doing this, please let me know.
$(function () {
$("#DeleteConfirm").dialog({
buttons: {
"Confirm": function() {
var DeleteConfirmation = "Yes";
$.ajax({
type: "POST",
url: "index.php",
data: DeleteConfirmation,
success: function(DeleteConfirmation){
alert(DeleteConfirmation);
},
dataType: "text"
});
},
"Cancel": function() {
$(this).dialog("close");
}
}
});
});

Javascript:
if( confirm('Are you sure?')){
/*proceed?*/
}
That is standard javascript. It wraps your AJAX call within the braces and if the user clicks 'yes' - the ajax call will execute. If he click 'no', then nothing happens. The confirm() prompt pops up an alert on screen with buttons. The resulted is captured by the if. You can also capture the result of that: var res=confirm('are you sure?');.

You need to assign the YES value to a property name:
data: { "confirmed": DeleteConfirmation},
Then in your PHP you can ready this using $_POST["confirmed"].
This does seem a little redundant however, as the user has already clicked the button to confirm the deletion, so there seems little value in sending the value in the POST request. Sending the id of the item to delete would make more sense.

Your ajax is misformed, try:
$.ajax({
type: "POST",
url: "index.php",
data: {answer: DeleteConfirmation }, //what you send to the php
success: function(data){ //answer from your php
alert(data);
},
dataType: "text"
});
},

Related

ASP.net: AJAX Result Not Kicking Off

I think this will be a weird one for you as I am at my wits end with this. On a screen I have in a table, I have a link being clicked that is setting off a javascript/ajax request. I have similar code in another screen that works perfectly as it heads down into the success part of the ajax call and runs code in the success portion of the call. For some reason though I can't seem to get this to work and when I debug it in chrome, I lose my breakpoints and it never seems to get into the success portion of the Ajax call.
#section scripts{
<script>
// Get the bond ID Data from the row selected and return that to the program.
function getIDData(el) {
var ID = $(el).closest('tr').children('td:first').text();
var iddata = {
'ID': ID
}
console.log(iddata);
return iddata;
}
// Submit the data to a function in the .cs portion of this razor page.
$('.updatelink').click(function () {
var bondid = JSON.stringify(getIDData(this));
$.ajax({
url: '/Maintenance/Bond_Maint?handler=UpdateandReloadData',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
type: 'POST',
dataType: 'json',
data: { bondid: bondid },
success: function (result) {
if (result.pass != undefined) {
document.forms[0].submit();
}
},
});
});
</script>
}
The ASP.net code behind that is calling does an update to the database and then passes back a variable containing Success as its message.
//-------------------------------------------------------------------------------
// Try to get and insert the data from a selected row and copy it
//-------------------------------------------------------------------------------
public ActionResult OnPostUpdateandReloadData(string bondid)
{
return new JsonResult(new { pass = "Success" });
}
I'm not sure how else to describe my issue other than when I debug my other code via the browser, it appears to take a different path than this code does and I cannot fathom why. For reference my other code looks like this:
#section scripts{
<script>
// Get the offender ID Data from the row selected and return that to the program.
function getIDData(el) {
var ID = $(el).closest('tr').children('td:first').text();
var iddata = {
'ID': ID
}
console.log(iddata);
return iddata;
}
// Submit the data to a function in the .cs portion of this razor page.
$('.copybtn').click(function () {
var offenderid = JSON.stringify(getIDData(this));
$.ajax({
url: '/Copy_Old_Account?handler=CopyData',
beforeSend: function (xhr) {
            xhr.setRequestHeader("XSRF-TOKEN",
                $('input:hidden[name="__RequestVerificationToken"]').val());
        },
type: 'POST',
dataType: 'json',
data: { offenderid: offenderid },
success: function (result) {
if (result.path != undefined) {
window.location.replace(result.path);
}
},
});
});
</script>
}
Any help would be appreciated.
Okay guys so first off, thank you everyone for responding to my question. Frank Writte and Alfred pointed me into the right direction by looking for the status in the network tab for my calls. I found out that I was getting cancellations for my requests. After looking into that I found this article What does status=canceled for a resource mean in Chrome Developer Tools? that has an answer from FUCO that gave me what I needed to do. Apparently I needed to add event.preventDefault(); in front of my ajax call and all of a sudden my code worked. I'm not sure I completely understand why this works but I can't complain about the results. Again thank you everyone for trying to help. This one has been boggling my mind all morning.

jquery .ajax's .done function get done on alert only

This seems a bit strange and i cant get a hold of the situation, apparently i used jquery's .ajax() function to process some script to get some data from the database. The script works fine and data gets returned as accordingly:
$.ajax({
type: "POST",
url: "getevaluationdata.php",
data: { evaluation_ID: value }
})
.done(function( msg ) {
$("#error2").html(msg);
});
After the scripts process, it is suppose to populate the data echoed in the script to the div i mentioned, but this does not happen. However, if i write an alert statement before the div population, the div gets populated. meaning:
$.ajax({
type: "POST",
url: "getevaluationdata.php",
data: { evaluation_ID: value }
})
.done(function( msg ) {
alert(msg);
$("#error2").html(msg);
});
I dont seem to get why this is happening and what I can do to resolve this.
P.S. I have done this before, and this was working correctly before
Is it possible #error2 is not on the page yet?, so the alert gives it time? try putting the ajax call in
$(function(){
$.ajax({
type: "POST",
url: "getevaluationdata.php",
data: { evaluation_ID: value }
}).done(function( msg ){
$("#error2").html(msg);
});
});
Another thing you can try for reference is using the success callback
$.post("getevaluationdata.php",{evaluation_ID:value},function(msg){
$("#error2").html(msg);
});

I need to get a variable between jQuery function and AJAX

I have two buttons on the form I'm getting, this first piece of coce allow me to know which was the button clicked by getting the id of it.
var button;
var form = $('.register_ajax');
$('#vote_up, #vote_down').on("click",function(e) {
e.preventDefault();
button = $(this).attr("id");
});
and this other send the form data through AJAX using the info already obtained from the button using the script above.
form.bind('submit',function () {
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
cache: false,
dataType: 'json',
data: form.serialize() + '&' + encodeURI(button.attr('name')) + '=' + encodeURI(button.attr('value')) ,
beforeSend: function() {
//$("#validation-errors").hide().empty();
},
success: function(data) {
if(data.message == 0){
$("#fave").attr('src','interactions/favorite.png');
$("#favorite").attr('value',1);
console.log(data.errors);
}
if(data.message == 1)
{
$("#fave").attr('src','interactions/favorite_active.png');
$("#favorite").attr('value',0);
}
if(data.message == "plus")
{
$("#vote_up").attr('class','options options-hover');
$("#vote_down").attr('class','options');
console.log(data.message);
}
if(data.message == "sub")
{
$("#vote_down").attr('class','options options-hover');
$("#vote_up").attr('class','options');
console.log("sub");
}
},
error: function(xhr, textStatus, thrownError) {
console.log(data.message);
}
});
return false;
});
The problem is that the data is not being passed to the ajax function, the button info is being saved on the button var, but it's not being obtained at time on the ajax call to work with it (or at least that is what I think). I'd like to know what can I do to make this work, any help appreciated.
1st edit: If I get the button data directly like button = $('#vote_up'); it doesn't work either, it only works if I get the button directly like this but without using the function.
2nd edit: I found the solution, I posted below.
var button is in the scope of the .on('event', function(){})
You need to declare the variable in the shared scope, then you can modify the value inside the event callback, i.e.
var button,
form = $('.register_ajax');
$('#vote_up, #vote_down').on("click",function(e) {
e.preventDefault();
button = $(this).attr("id");
});
You are being victim of a clousure. Just as adam_bear said you need to declare the variable outside of the function where you are setting it, but you are going to keep hitting these kind of walls constantly unless you dedicate some hours to learn the Good Parts :D, javascript is full of these type of things, here is a good book for you and you can also learn more from the author at http://www.crockford.com/.
I Found the solution, I just changed a little bit the click function like this:
var button;
var form = $('.register_ajax');
var data = form.serializeArray();
$('#vote_up, #vote_down').on("click",function(e) {
e.preventDefault();
button = $(this).attr("id");
data.push({name: encodeURI($(this).attr('name')), value: encodeURI($(this).attr('value'))});
form.submit();
});
using e.preventDefault(); and form.submit(); to send the form. also I changed the data.serialize to serializeArray(); because it's more effective to push data into the serializeArray(). in the second script I just changed the data.serialize() and used the data variable that I already filled with the serializeArray() and the data.push():
form.bind('submit',function () {
alert(button);
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
cache: false,
dataType: 'json',
data: data,
//here goes the rest of the code
//...
});
return false;
});
it worked for me, it solved the problem between the click and submit event that wasn't allowing me to send the function through ajax.

Ajax request is not working php [duplicate]

This question already has an answer here:
ajax request without data not working
(1 answer)
Closed 8 years ago.
I have asked this earlier but still I wasn't lucky to get it work. Simply I am trying to update profile picture with a default picture when Delete button is clicked and I am trying to use ajax to do this, however whenever I click on the button nothing happens and the picture is not updated. I have tested the php page by itself and it works nicely but the js isn't working so could someone spot what I am doing wrong here?
html
<button href="javascript:void(0);" onclick="delete;" class="btn btn-default delbutt">Delete</button>
js
function delete()
{
$.ajax({
type: "POST",
url: "test.php?action=delete",
cache: false,
success: function(response)
{
var $divs = $("<div>" + response + "</div>");
$("#phd").fadeOut('slow');
$(".suc_pic").fadeIn('slow').empty().append($divs.find("#msg"));
}
});
}
and here is the php lastly
$username = $_SESSION["userCakeUser"];
if(isset($_POST["action"]) && !empty($_POST["action"]) || isset($_GET["action"]) && !empty($_GET["action"]))
{
if(isset($_GET["action"]) == "delete")
{
$profile = 'default.jpg';
$pp = $db->prepare("update users set profile = ? where username = ?");
echo $db->error;
$pp->bind_param('ss', $profile, $username->username);
$pp->execute();
}
}
else {
echo "Something is wrong. Try again.";
}
POST queries are by default not cached in jQuery ajax (1), so you probably should just use the $.post helper instead. Also, querystring values are not parsed to the $_POST super-global, so your code as-is will always read null from $_POST["action"].
function delete(){
$.post(
"test.php",
{
action: 'delete'
},
success: function(response){
var $divs = $("<div>" + response + "</div>");
$("#phd").fadeOut('slow');
$(".suc_pic").fadeIn('slow').empty().append($divs.find("#msg"));
}
);
}
(1) As defined in the API reference:
Pages fetched with POST are never cached, so the cache and ifModified
options in jQuery.ajaxSetup() have no effect on these requests.
It is my understanding that jQuery AJAX requests should have a data: option in there somewhere. Also, I see you're using GET to make the request, but tell jQuery to use POST.
$.ajax({
type: "GET",
url: "test.php",
cache: false,
data : {
action : 'delete'
success : function(response)
{
etc...
I'm no jQuery expert, but I think that may be your problem. The only other thing I can think of is the success function isn't working properly. Check your F12 menu and post any warnings/errors so we can see it.

Ajax link to run codeigniter controller then update html

Sorry for the most simplest of questions but I can't seem to get anything to work. It's the first time I've really played around with AJAX.
I'm developing in codeigniter and I have a link that when clicked runs the controller: photo function: like and allows the logged in user to like the photo then redirects the user back to the photo and displays a slightly different version of the button showing that the user likes the photo.
<?php if ( $like_count > '0' ) { echo $like_count; } ?>
It works fine but I thought it would be cool to replace it with an ajax function so it's more of a fluid motion instead of navigating off the page and then back again.
Any help would be greatly appreciated.
$(".uk-button").click(function(e) {
e.preventDefault();
//Here you can add your ajax
$.ajax({
url: site_url + 'photo/like',
data: {
liked : 1
},
type: 'POST',
dataType: 'json',
async : false,
success: function(success_record) {
console.log(success_record,":success_record");
//You might receive your like count from PHP here
}
});
});
In your success record you would get your PHP record values. Based on that you can increment or decrement count in success function
You can do something like this:
$(document).ready(function()
{
$('.likeLink').on('click', funciton()
{
var obj = $(this);
var id = obj.attr('id'); //anything you want to pass to update your like somewhere
$.ajax(
{
type: 'POST',
url: 'YourFilePathWhereYouWillDoTheLike',
data:
{
id: id,
},
cache: false,
success: function(response)
{
obj.html("You have liked this!");
}
});
return false;
})
})

Categories

Resources