Ajax POST no success nor error not DUPLICATE [duplicate] - javascript

This question already has answers here:
How to prevent buttons from submitting forms
(20 answers)
Closed 5 years ago.
Im experiencing a weird error in an ajax request. upon calling an alert in both error and succes, the alerts arent displayed. This implies that the ajax request isn't processed. But I have no clue whatsoever why this is the case. Code is below.
var bool;
function set(n, thread_id) {
bool = n;
// update_upvotes(thread_id);
}
function vote(thread_id) {
if (bool == 1) {
alert("begin ajax");
$.ajax({
type: "POST",
url: "../includes/thread_upvotes.inc.php",
data: {
thread_id: thread_id
},
succes: function(data) {
alert("data:"+data);
},
error: function() {
alert("hi, im broken");
}
});
} else {
$.ajax({
type: "POST",
url: "../includes/thread_downvotes.inc.php",
data: {
thread_id: thread_id
}
});
}
}
Here the form which calls the function
<iframe class="foo" name="foo" id="foo"></iframe>
<form class="voteform" target="foo" onsubmit="vote('.$thread_id.') & update_upvotes('.$thread_id.');">
<button onclick="set(1);" id="'.$thread_id.'1" name="upvote" type= "submit" class="vote right up" value="'.$thread_id.'"> '.$num_upvotes.' </button>
<button onclick="set(0);" id="'.$thread_id.'0" name="downvote" type= "submit" class="vote left down" value="'.$thread_id.'"> '.$num_downvotes.' </button>
</form>
Thanks in advance.
EDIT: This post has been marked as a duplicate, the answer provided by the person who marked this as a duplicate is not satisfactory. We removed the form out of our code and the ajax request is still not being processed...

It seems this url "../includes/thread_upvotes.inc.php", is wrong. Remove the dots

Related

specifying javascript function from button form

I'm using Ajax to display a comments widget on my site and am trying to upgrade from Recaptcha v2 to Recaptcha v3. So far it's gone well, comments successfully post, but instead of displaying the "thanks for submitting" modal, it just redirects to the form submission URL with the success data. This is not ideal.
The main change I made was to change the button code in my comment_form.html to this:
<button class="button g-recaptcha" id="comment-form-submit"
data-sitekey="{{ site.reCaptcha.siteKey }}"
data-callback='onSubmit'
data-action='submit'>
Submit
</button>
</form>
<script>
function onSubmit(token) {
document.getElementById("new-comment").submit();
}
</script>
(and added the id="new-comment" to the top of the form)
previously i had
<button class="button" id="comment-form-submit">Submit</button>
the relevant javascript code is:
(function ($) {
var $comments = $('.js-comments');
$('.js-form').submit(function () {
var form = this;
$("#comment-form-submit").html(
'<svg class="icon spin"><use xlink:href="#icon-loading"></use></svg> Sending...'
);
$(form).addClass('disabled');
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
contentType: 'application/x-www-form-urlencoded',
success: function (data) {
showModal('Comment submitted', 'Thanks! Your comment is pending. It will appear when approved.');
$("#comment-form-submit")
.html("Submit");
$(form)[0].reset();
$(form).removeClass('disabled');
grecaptcha.reset();
},
error: function (err) {
console.log(err);
var ecode = (err.responseJSON || {}).errorCode || "unknown";
showModal('Error', 'An error occured.<br>[' + ecode + ']');
$("#comment-form-submit").html("Submit")
$(form).removeClass('disabled');
grecaptcha.reset();
}
});
return false;
});
I'm pretty sure it's like a one line change to make the Ajax process the reply, but I'm totally out of my depth with javascript, so any thoughts are greatly appreciated.
--
Edit: The other example I saw calls the onSubmit function from their callback but since I'm using this weird main.js I don't know how to reference $('.js-form').submit(function (event) { from onSubmit
The default browser behaviour after submitting a form is to redirect on success, try preventing this by calling preventDefault on the event, eg:
$('.js-form').submit(function (event) {
event.preventDefault();
// the rest of your code
});

attempts to trigger "click" on enter not working [duplicate]

This question already has answers here:
How to prevent ENTER keypress to submit a web form?
(29 answers)
Closed 3 years ago.
I am trying to trigger my onclick of a button when i hit enter to make my site more user friendly. I have tried all of the below methods and all of them have the same error
this is my html (please note im using pug)
input#userInterests.form-control(type='text' placeholder='Interests' name='userInterests')
button#AddInterest.btn.btn-success.btn-block.btn-lg(type='button', onclick='add_interest()', value='interests') Update Interests
this is the posting function:
function add_interest() {
var interests = document.getElementById('userInterests').value;
interests = interests.split(" ");
interests.forEach(function (data) {
if (!validInterest(data))
{
swal(
'Error!',
`${data} is not a correctly formatted interest`,
'error'
)
return ;
}
});
interests.forEach(function (data) {
if (validInterest(data))
{
let form =
{
interest: data
}
$.ajax({
type: "POST",
url : '/user/account/addinterest',
data: JSON.stringify(form),
contentType: "application/json; charset=utf-8",
dataType: "json",
});
}
});
document.getElementById("interestsPara").innerHTML = "Updated your interests";
$('#userInterests').val('');
}
these are all the methods ive attempted and none of them work. please note i am obviously not doing all of these at the same time and uncommented each one one at a time for testing. I have tested all of these with and without $(document).ready
$(document).ready(function(){
$("#userInterests").keyup(function(event) {
if (event.keyCode === 13) {
$('#AddInterests').trigger("click");
$('#AddInterests').click(add_interest());
$("#AddInterests")[0].click();
$("#AddInterests").click();
setTimeout(function(){ $('#AddInterests').click()}, 100);
setTimeout(function(){ $('#AddInterests')[0].click()}, 100);
add_interest();
document.getElementById("AddInterests").onclick();
document.getElementById("AddInterests").onclick = add_interest();
$('#AddInterests').trigger('click');
$("#AddInterests")[0].click(add_interest());
}
})
});
This is my 'error'
Cannot POST /user/account
my function does work and posts correctly when i manually click the button
(this is a group project and some of this isnt mine so please dont flame me too hard and give constructive criticism)
Thank you #freedomn-m
The problem was the default form behaviour to submit on enter that i didnt realise existed. I set my form to onsubmit return false as follows and this worked
<form onsubmit="return false;">
as described by This Post
I tried to use event.preventDefault() but it did not work

How to call PHP function using jquery? [duplicate]

This question already has answers here:
using jquery $.ajax to call a PHP function
(6 answers)
Closed 7 years ago.
This seems straightforward, but I can't get it to work. I have a button, when it's clicked I'd like to execute a php function which is defined in the same file as the button. My code is below, I get the "clicked" alert when the button is clicked, but no alert on response from the function.
//this is in myfile.php
<?php
echo '<button type="button" name="save_button" onclick="save()">Save</button>';
?>
<script type="text/javascript">
function save()
{
alert("clicked");
$.ajax({
url: 'myfile.php',
type: 'post',
data: { "set_description": ""},
success: function(response) { alert(response); }
});
}
</script>
<?php
function set_description() {
return "a string";
}
?>
Change the type of the jquery Ajax code from post to get since you want to use the response, else I can't see something wrong there

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.

Issues with JQuery/AJAX Form Handling [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I have two files. This is my main file - index.php which has javascript in the head, here's the javascript:
<script
src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<script>
$(function () {
$('form#revisionnotes').on('submit', function(e) {
$.ajax({
type: 'post',
url: 'submits/updatenotes.php',
data: $('form').serialize(),
success: function () {
alert('You have successfully saved the revision notes.');
}
});
e.preventDefault();
});
});
</script>
So when my form:
<form id="revisionnotes" name="revisionnotes" method="post">
<textarea style="width:100%;height:290px; padding:10px;" id="notes" > <?php echo $db->result("SELECT * FROM revision_notes", "notes");?></textarea><br/>
<input type="submit" value="Save" name="submit" id="submit" class="btn btn-primary">
</div>
</form>
From there in my updatenotes.php I was going to do a database INSERT, however that didn't work so I then tried adding a javascript alert to see if that'd work either:
<script type="text/javascript">
alert("hi");
</script>
And that didn't work either, I'm completely stumped. Could somebody please explain to me where I'm going wrong? I've never used this type of form-submitting before.
Thanks.
You do not say where exactly the trouble lies, so this is an incomplete answer:
$(function () {
alert("Alpha - jQuery is called");
$('#revisionnotes').on('submit', function(e) {
alert("Bravo - submit received");
var data = $(this).serialize();
alert("Charlie - data serialized");
$.ajax({
type: 'post',
url: 'submits/updatenotes.php',
data: data, // $('form').serialize(),
success: function (data, textStatus, jqXHR) {
alert("Delta - POST submission succeeded");
}
});
e.preventDefault();
});
});
The above should allow you to see where (if) the workflow fails to follow the plan.
At this point the POST should have been fired, and using Firebug or WebDev you should be able to inspect the results. Otherwise, temporarily convert the POST to GET, copy the URL and paste into another browser window.
Note: do not put Javascript in the POST-receiving script, since chances are that it won't be executed. You're not "going" to that page, just doing a submit; that's why you don't see your alert.
Ordinarily you would return some information from the submission page in JSON format and let success() extract it from the data variable. Note that "success" only means that the target script received the submission, not that it did handle it properly.
Example of success function (and how to "talk" to it)
success: function(data, textStatus, jqXHR) {
if (data.status != 'OK') {
alert("ERROR " + data.message);
return;
}
if (data.message) {
alert(data.message);
// do not return
}
// other
}
So you'd start with a submit script like this (I repeat, this is awkward. You really want to do this with proper logging and Firebug!), commenting the various jqExit's once you check they code is working up to any given point:
<?php
function jqExit($status, $message = false) {
$packet = array('status' => $status);
if (false !== $message) {
$packet['message'] = $message;
}
exit(json_encode($packet));
}
jqExit('ERROR', "Alpha - got POST");
// Connect to database
jqExit('ERROR', "Bravo - connected to DB");
// Decode and validate POST
jqExit('ERROR', "Charlie - data ready");
// Perform update
if (...update failed...) {
jqExit('ERROR', "reason why it failed");
}
// Finally everything is OK
jqExit('OK');
?>

Categories

Resources