How my page works:
The quiz php page loads and the user generates a score with a function inside quiz.js. The score is then saved in a variable score inside quiz.js
After generating the score, the user has to press a button to go to the next question in the quiz inside the same page. Pressing the button would send the score to my database with a sql query I have in sendData.php, without reloading the page.
My button looks like this:
<form id="sendData" action="sendData.php" method="post">
<button type="submit" name="send" onclick="sendAjax()">Send</button>
</form>
sendData.php is already finished and working, but for some reason, sendAjax() doesn't work at all:
function sendAjax() {
$.ajax({
url: "sendData.php",
type: "POST",
data: {
score: score,
numQuiz: numQuiz
},
success: function() {
alert("Data succesfully sent");
},
error: function() {
alert("There has been an error");
}
})
}
And my PHP file being like this:
if (isset($_POST['score']) and isset($_POST['numQuiz'])) {
$score = $_POST['score'];
$numQuiz = $_POST['numQuiz'];
// SQL query and stuff goes here
}
But it seems that $_POST['score'] and $_POST['numQuiz'] aren't set. Also, I can see the error pop up inside sendAjax before it loads the PHP file. I've tried adding to the form the attribute action="" but it doesn't work either.
<form id="sendData" action="sendData.php" method="post">
<button type="submit" name="send" onclick="sendAjax()">Send</button>
</form>
You're running the JS when you click a submit button in a form.
So the JS runs, then the browser immediately navigates to a new page (submitting the form, with no data in it, to the PHP) and the XMLHttpRequest object is destroyed before it receives a response.
You then see the result of the standard form submission.
If you just want a button to trigger some JavaScript, then use a non-submit button (<button type="button"), and don't put it in a form.
Better yet:
switch away from onclick attributes (they have a variety of issues) in favour of addEventListener providing a submit event listener on the form
Use preventDefault() to stop the form submission when the JS is successful
Put form controls in the form so it submits useful data when the JS isn't successful
i.e. write Unobtrusive JavaScript then provides Progressive enhancement.
Two things:
You need to tell jQuery to use the application/json content-type:
function sendAjax() {
$.ajax({
url: "sendData.php",
type: "POST",
contentType: 'application/json',
dataType: 'json',
data: {
score: score,
numQuiz: numQuiz
},
success: function() {
alert("Data succesfully sent");
},
error: function() {
alert("There has been an error");
}
})
}
PHP's $_POST variable is not populated as you think it is as the payload is not urlencoded as is standard with say a form submit. So we can parse the JSON payload (body) ussing:
$myData = json_decode(file_get_contents("php://input"));
var_dump($myData->score);
Related
Now before i ask the actual question this is a stupid rant. I swear I hate javascript and everything that is associated with it.
Now actual question.
I have a asp.net web form. I can send data to my web api controller via asp.net code and its working. I'm trying to now post the data via client side ajax using jquery, but I can't get a simple true or false if the form is valid or not. Its a bootstrap v3 form. Someone please help me get off this wild ride. I've searched countless questions but no its not working. Everything is working including post and return message, just this stupid little thing wont't
I just wish to know how to get the form validity status before i ajax. Simple.
Edit:
this button click event works.
$("#additional").click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "/api/data",
data: $('form.form-horizontal').serialize(),
success: function(msg){
swal(msg,"Success","success");
},
error: function(){
swal("failure");
}
});
});
Basically I want the above ajax to run ONLY when form is valid. I have 'required' tags on my form fields already.
Your Question is not clear, but if you mean there is some inputs that they shouldn't be null or empty and after valid theme call ajax you can do some thing like this:
<form class="form-horizontal"> <input type="text" required class="SubscribeText" name="email"> <input type="button" class="postmethod" value="Send"></form>
$(".postmethod").click(function() {
if ($(".SubscribeText").val().length>0) {
$.ajax({
type: "POST",
url: "/api/data",
data: $('form.form-horizontal').serialize(),
success: function(msg){
swal(msg,"Success","success");
},
error: function(){
swal("failure");
}
});
}
});
if you have some inputs, the best practice is use flag, for on click flag=true, which input fails the validation should change the flag to false then if flag is true call ajax method.
I am trying to pass a string stored in a variable to a mysql table via php.
Currently I am using an <input> with type hidden, I assign the variable that I want as its value and post it through a form submit.
it is working but it's ugly.
I know there is $.post and $.ajax but I don't seem to figure out how to use them in the js side and php side. I have looked for them online and there are a lot of questions of this sort but none of them work for me (probably because I am missing knowledge)
How can I do it?
Here is a very basic example. We start out with a form on an HTML page. When this button is clicked, we are going to activate a javascript function.
<html>
<form>
<input type="email" id="email-field" />
<input id="submitButton" type="submit" value="Submit" />
</form>
</html>
Now, here is the javascript function being activated due to the button click. Inside, we extract any information that might have been filled out in the input field with id of "email-field", then send that off via ajax to a php file that sits on the server.
$('#submitButton').click(function() {
var email = $('#email-field').val();
$.ajax({
type: 'POST',
url: './yourphpfilename.php',
data: {
email: email
}
}).done(function(data) {
console.log(data) // Will send you the result that is echoed in the PHP file
})
})
As long as you put the correct url in your ajax request to your PHP file, you can easily receive the data being sent like so,
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$email = $_POST['email'];
echo 'I have received your request.';
}
To send the data back, I use the echo command to do so here.
Try to read some documentation on the $_POST variable in PHP. Notice how I call for ['email']. The identifier inside the brackets directly correlates to the key inside the data object in the js file. For example, say we decided to name our email key something different in the js file.
data: {
useremail: email
}
You would then just change the PHP code like so,
$email = $_POST['useremail'];
This was very confusing for me starting out, and sometimes it's hard to even pose a quality question on it if you have no idea how it works. In the future though, I would atleast try to post some code showing that you attempted the problem.
There are several things you need to do:
You have a form tag and you need to prevent it from submitting, like this:
$("#myformid").submit(function(event) {
//Do something
event.preventDefault();
});
If your form is no longer submitted, then you are on the right track.
You need to use $.ajax to send the request, like this:
$("#myformid").submit(function(event) {
//Here I assume that all variables have been properly initialized
$.ajax({
url: "yoururl",
method: "POST",
data: yourdata, //yourdata should contain the things you intend to send to the server
}).done(function(response) {
//callback
});
event.preventDefault();
});
You will need a PHP code which will properly handle the POST request you send at yoururl. This is how you can check in PHP whether the request method was POST:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
//It is a POST request
} else {
//It is not a POST request
}
I would like to create a simple login form with HTML and Java (and maybe JSON). So, I have a login form with several input fields with the following id-s: txtUsername, txtPasswd, btnLogin.
After click on the button (btnLogin) I would like to send data to the servlet, and get back just a true/false value deepends on the user-passwd combination.
I can write the HTML code of this form, and the server side code, but I don't know, how can I send and recive data without page refreshing.
Here is my frontend code:
<script>
function login(){
var user=document.getElementById("txtUsername");
var passwd=document.getElementById("txtPasswd");
//???
}
</script>
Username: <input type="text" id="txtUsername"/> <br/>
Password: <input type="password" id="txtPasswd"/> <br/>
<input type="button" value="Login" id="btnLogin" onclick="login()"/>
You have to use an AJAX request. One way of doing it is to wire up and event handler on a your login button (like onclick), which calls a JS function to use an Ajax request (XmlHttpRequest), just like you have started.
You can do it in vanilla Javascript, but it is easier to use a library like jQuery. The code would look something like this (with jQuery, note the '$'):
function login() {
$.ajax({
type: 'POST',
url: url, //Url of login endpoint
data: DATA, //Now here you would want to send a payload i.e. your username and password data
dataType: 'json',
contentType: 'application/.json',
success: function(data) {
//HERE 'data' would represent your true or false that came back from the server.
//You can do stuff here with the response
},
error: function(jqXHR, textStatus, errorThrown) {
//IF ERROR then this code would be executed.
}
});
}
Hope this gives you a starting point!
You must use jquery AJAX.
Here is a link to the official documentation: http://api.jquery.com/jquery.ajax/
Hope it helps.
There are a couple of questions that are somewhat similar to this, but I haven't been able to get their solutions to work for me.
Basically, I am making an AJAX call that is working properly--the result is coming back through. The issue is that instead of processing the result, the result-array is printed back to the screen (and deletes everything else). Clearly, it is not handling the incoming result properly, but I'm not sure why.
This is the form being sent:
<form class="removeAndApply" method="post" action="">
…hidden inputs...
<button type="submit">Use</button>
</form>
The PHP that is processing the AJAX:
case "removeAndApply_PromoCode":
…Get data from $_POST….
…process stuff...
$response = …..;
$finalPrice = ….;
$dataArray = array('response'=>$response, 'finalPrice'=>$finalPrice);
header('Content-type: application/json');
echo json_encode( $dataArray );
exit();
break;
Here is a sample result text, as printed on my screen during failure:
{"response":{"Col1":"13","0":"13","Col2":"PC2","1":"PC2","Col3":"1","2":"1","Col4":"45.89","3":"45.89","col5":null,"4":null,"Col6":"1","5":"1"},"finalPrice":0}
And this is the javascript function that is supposed to handle it:
$('.removeAndApply').ajaxForm({url: this.href, type:'post',
data: this.serialize,
dataType: 'json',
success: function(response){
alert("asdf");
}
});
Thanks.
The problem seems to be in HTML button type attribute. When you have a <button type="submit"> in <form> and you clicked it. The form submits, request is sent to the server, browser opening the new response in new document.
If you make some changes:
HTML:
<form class="removeAndApply" method="post" action="">
…hidden inputs...
<button type="button" id="submit-form">Use</button>
</form>
JS:
$('#submit-form').on('click', function() {
$.ajax({
type: 'post',
url: window.location.href,
data: $('.removeAndApply').serialize(),
dataType: 'json',
success: function(res) {...},
error: function(err) {...}
});
});
Everything should be fine.
This is probably better suited for a comment, but I don't have enough rep for that, so:
This is the type of behavior you'd see if you don't bind the ajax form functionality to that form... the button submits the form as normal and you just see plain json coming from the server as a response to the (non-ajax) post. Are you sure that ajaxForm() statement is being executed?
i have a form that deletes the comment its in.
To only allow the page that carries out the php action to be viewed when the form is submitted i do a basic
if (isset($_POST['submit-delete'])) {
// carry out delete
}
this works fine, but i am using ajax to not reload the page.
The response is the same as i have used else where:
$(document).ready(function(){
$(".delrepcomment").submit(function(){
$.ajax({
type: "POST",
url: "process/deletecomment.php",
data: $(".delrepcomment").serialize(),
dataType: "json",
success: function(response){
if (response.commentDeleted === true) {
$('#successdisplay').fadeIn(1000),
$('#successdisplay').delay(2500).fadeOut(400);
}
else {
$('.delrepcomment').after('<div class="error">Something went wrong!</div>');
}
}
});
return false;
});
});
This however doesnt work, unless i remove the check to see if the form has been submitted.
Whats the best way around this? I want to keep the check for the form being submitted incase of js being turned off or any direct access attempts.
Thanks.
You should post the data you require for the script to work. In your case, you have to post a key-value-pair with "submit-delete" as the key and an arbitrary value (unless you check that value later in the code).
On the other hand, PHP stores the used HTTP method in $_SERVER['REQUEST_METHOD'], this would be "POST" in your case.