Issues with JQuery/AJAX Form Handling [closed] - javascript

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');
?>

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
});

Ajax POST no success nor error not DUPLICATE [duplicate]

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

Is there a more proper way to handle errors using AJAX?

I've never asked anything here, but there's something that bugs me.
You see, I'm toying with PHP for about a year. I've made myself quite a big project while learning PHP, JQuery, MySQL, etc.- it's far from being perfect, or even being finished, but it works and I'm constantly trying to improve existing code while adding new functions. It's a text-based browser MMORPG game (it's still in development), if you want a link, I'll provide it, but I didn't come here to promote it.
The thing is, I feel okay in procedural PHP (though I still have problems with repeating code), so I've decided it's about time to move to OOP. I understand it in theory, know the basics, and I'm slowly advancing in practice, but I wanted your advice, before moving too far.
In my original game with procedural code, I'm often doing something along these lines:
user visits a page, say a shop.php. On opening the site, shop.php retrieves from database list of items that are available to buy. There are blank #success-message and #error-message paragraphs on the site.
user then can choose an item from shop he wants to buy- clicking the item triggers javascript, and an AJAX call is made to the buy-item.php, expecting a json to be returned
in buy-item.php I'm creating an array, say, $result("success" => 0, "message" => "")
buy-item.php checks if the player can afford the item, has space in backpack, etc., and if there's one condition that isn't met, then $result["message"] sets to, say, "You need more gold". If all conditions are met, then result["success"] set's to 1, and $result["message"] to, say, "Purchase successful". Finally, it echoes json_encode($result) to AJAX.
in AJAX success: I check if(result.success), and act accordingly- If purchase was successful, I'd do $("#error-message").html(result.message), and if it was successfull, I'd put result.message in "#success-message" instead (I could display both error and success messages in the same paragraph I guess, but that's simpler for me to do it separately, because these messages are styled differently, say, success is colored green, and error- red).
Now, is that a correct approach to handle errors? Or should I code it completely differently? Will this approach be still valid in OOP?
Let me show you what I mean with this example, I'm toying with at the moment (for simplicity sake, please forget about security or even usefulness of the code):
index.php
<!DOCTYPE html>
<html lang="pl-PL">
<head>
<meta charset="UTF-8">
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous">
</script>
<script src="script.js"></script>
</head>
<body>
<div id="wrapper">
<p id="error-message"></p>
<p id="success-message"></p>
<form id="registration-form" method="post">
<input type="text" placeholder="Account Name" name="nickname"></input>
<input type="text" placeholder="Password" name="password"></input>
<input type="text" placeholder="E-mail" name="email"></input>
<button type="submit">Register</button>
</form>
</div>
</body>
</html>
User.php
<?php
class User{
//register method
public function register($nickname, $password, $email){
$result = array("success" => 0, "message" => "");
//example validation
if($nickname==123){
$result["message"] = "Could not register.";
}
else{
//add user to the database
//sql code here
$result["success"] = 1;
$result["message"] = "Registration successful.";
}
return $result;
}
}
?>
registerProcessing.php
<?php
require_once 'User.php';
$user = new User();
echo json_encode($user->register($_POST["nickname"], $_POST["password"], $_POST["email"]));
?>
script.js
$(function() {
$("#wrapper").on("submit", "#registration-form", function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "registerProcessing.php",
data: $("#registration-form").serialize(),
dataType: "json",
success: function(result){
if(result.success){
$("#success-message").html(result.message);
}
else{
$("#error-message").html(result.message);
}
}
});
});
});
The proper way is study the ajax callbacks and states already made into javascript/jQuery and play with them. If you need more advanced kind of feature, will need to send by backend some headers forcing some statuses that can be handled by the proper callbacks or customized ones.
You can use the HTTP status codes mainly treated with major js libraries/frameworks (even the XMLHttpRequest pure itself that follow the HTTP pattern of codes, see MDN).
Directly answering your question, no, is not right. Your ajax is using a main callback (success) and handling by returned values. It's works, but lacks best practices about callbacks, like I mentioned above.
An example what you can do:
$("#wrapper").on("submit", "#registration-form", function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "registerProcessing.php",
data: $("#registration-form").serialize(),
dataType: "json",
success: function(result){
$("#success-message").html(result.message);
},
error: function(result){
$("#error-message").html(result.message);
}
});
});
or
$("#wrapper").on("submit", "#registration-form", function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "registerProcessing.php",
data: $("#registration-form").serialize(),
dataType: "json",
statusCode: {
404: function() {
$("#error-message").html('NOT FOUND');
},
200: function(result) {
$("#success-message").html(result.message);
},
500: function(result) {
$("#error-message").html(result.message);
}
}
});
});
Or with XMLHTTPREQUEST example:
var request;
if(window.XMLHttpRequest)
request = new XMLHttpRequest();
else
request = new ActiveXObject("Microsoft.XMLHTTP");
request.open('GET', 'http://www.mozilla.org', false);
request.send(); // there will be a 'pause' here until the response to come.
// the object request will be actually modified
switch (request.status){
case 404:
break;
case 500:
break;
case 200;
break
}
To add to #CarlosAlexandre's answer about handling errors using HTTP status codes: for your transition to OOP programming, you should be aware that it is becoming a best practice to use exception handling to pass error conditions around. This could like something like this:
User.php
class User{
//register method
public function register($nickname, $password, $email){
//example validation
if($nickname==123){
throw new InvalidArgumentException('Invalid username');
}
//add user to the database
//sql code here
}
}
registerProcessing.php
require_once 'User.php';
$user = new User();
$response = array(
'success' => 0,
'message' => 'Unknown error',
);
try {
$user->register($_POST["nickname"], $_POST["password"], $_POST["email"]);
$response['success'] = 1;
$response['message'] = 'Registration successful.';
} catch (Exception $exception) {
$response['message'] = $exception->getMessage();
}
echo json_encode($response);

Unable to submit form with ajax without reloading parent

I am building a web application that will create a div on the page, use ajax to load a form into that div, and then have the form submitted without the parent page refreshing. I've read many examples on this site and others of how to do this, yet I'm puzzled why my proof-of-concept test is not working for me.
What successfully happens is that the parent page is creating the new div and is loading the form into the div. However, upon submitting the form, the parent page reloads. Using "Live HTTP Headers" in Opera, I can see that submitting the form is causing a GET rather than a POST, even though my Javascript is attempting to POST.
Can anyone help me understand why this is happening? Any help is very much appreciated.
Here is the code to the parent HTML page:
<html>
<head>
<script src=\"jquery-1.11.1.min.js\"></script>
<script src=\"jquery.min.js\"></script>
<script type=\"text/javascript\">
var num=1;
console.log('starting the code');
$(document).ready(function() {
console.log('document is ready');
$('#form1').submit(function(event) { // catch the form's submit event
console.log('form is going through submit');
$.ajax({ // create an AJAX call...
url: 'add_user.php', // the file to call
type: 'POST', // GET or POST
data: $('#form1').serialize(), // get the form data
success: function(data) { // on success..
$('#assign1').html(data); // update the DIV
},
error: function(xhr, status, e) {
console.log('status');
console.log('e');
}
});
event.preventDefault(); // cancel original event to prevent form submitting
});
});
function addToBox(divID) {
console.log('adding new assign to box');
var myNewDiv = document.createElement(\"div\");
myNewDivID = 'assign'+num;
myNewDiv.setAttribute('id', myNewDivID);
myNewDivID = '#'+myNewDivID;
var myBox = document.getElementById(divID);
myBox.appendChild(myNewDiv);
$.ajax({
type: 'GET',
url: 'add_user.php?id=1',
success: function(data) {
$(myNewDivID).html(data);
},
error: function(xhr, status, e) {
console.log('status');
console.log('e');
}
});
num+=1;
}
</script>
</head>
<body>
<div>
<div id=\"box1\"></div>
<img src=\"/icons/add.png\" alt=\"Create new box\" />
</div>
<div>
<div id=\"box2\"></div>
<img src=\"/icons/add.png\" alt=\"Create new box\" />
</div>
</body>
</html>
Here is the code to the PHP page (named add_user.php) with the form.
<?php
$n=0;
$id=$_GET['id'];
if ($_SERVER['REQUEST_METHOD']=="POST") {
echo "got the form!";
} else {
echo "<form id=\"form{$id}\"><select name=\"quantity\">\n";
for ($n=1;$n<=5;$n++) {
echo "<option value=\"answer{$n}\">option {$n}</option>\n";
}
echo "</select>\n<input type=\"submit\" /></form>";
}
?>
Thanks to the comment by A. Wolff, I replaced $('#form1').submit(function(event) { with $(document).on('submit','#form1', function(event){ and it worked.
Thanks A. Wolff!

PHP if (isset($_POST[''])) +Jquery send in same page [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I would like to send a form so I don't get page refresh when I send a form.
Now when I press submit button I'm running this code:
<?php
if (isset($_POST['send_this_message']) == 'yes')
{
echo "yes this is just example and working";
}
?>
<form method="post" action="">
<input type="submit" name="send_this_message" value="yes">
</form>Now how can send this form but without page refresh with jquery. I have seen several examples but they are all calling external files.. Something like this.
<script>
$(function () {
$("#send").click(function () {
$.ajax({
type: "post",
url: "send.php",
data: $("#myform").serialize(),
success: function (response) {
if (response == "done") {
alert("Form submitted successfully!");
} else {
alert("Form submission failed!");
}
},
error: function (response) {
alert(response);
}
});
});
})();
</script>
This code above is not working for me. I mean I need to somehow execute that isset when pressing on button.
As you want to send data without page refresh, use Ajax to send the data from to your php file: (as example)
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('form').on('submit', function (e) {
$.ajax({
type: 'post',
url: 'post.php', // here your php file to do something with postdata
data: $('form').serialize(), // here you set the data to send to php file
success: function (data) {
alert('form was submitted');
}
});
e.preventDefault();
});
});
</script>
I don't know if I understand very well your question
However you need to set a value for your attribut action in
<form method="POST" action="">
for exemple
<form method="POST" action="responseForm.php">
you are selecting
$("#send")
it does not exist
add the id to the button
<input id="send" type="submit" name="send_this_message" value="yes">
also you need to use preventDefault() for stopping the propagation
Assuming your script is called script.php:
<?php
if (isset($_POST['send_this_message']) == 'yes')
{
// do stuff
echo "done"; // as confirmation for jQuery, see below
die(); // no output the form because ajax function isn't interested in it
}
?>
<form method="post" action="" id="form">
<input type="submit" name="send_this_message" value="yes">
</form>
<script>
$(function () {
$("#form").submit(function (e) {
e.preventDefault(); // prevent the form from being submitted normally
$.ajax({
type: "post",
url: "script.php",
data: $(this).serialize(),
success: function (response) {
if (response == "done") {
alert("stuff done");
} else {
alert("isset wasn't true");
}
},
error: function (response) {
alert("server returned a 500 error or something");
}
});
});
})();
</script>

Categories

Resources