My problem is when the data is submitted and saved using ajax it gives the response text and after that it echo the whole form again.
example:
this is a form
submit button save button
When response received from ajax the page looks like this..
this is a form
ajax response..
this form again
submit button save button
submit button save button
When this button is called
<div id="output"></div>
<button type="button" onClick="save()">Save to drafts</button>
it calls an ajax function to execute
function save(){
var save = new XMLHttpRequest;
var url = "panel.php";
var name = document.getElementById("name").value;
var page = document.getElementById("page").value;
var cont = document.getElementById("cont").value;
var send = "name="+name+"&page="+page+"&cont="+cont+"&call=yes";
save.open("POST", url, true);
save.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
save.onreadystatechange = function(){
if(save.readyState == 4 && save.status == 200){
var output = save.responseText;
document.getElementById("output").innerHTML = output;
}
}
save.send(send);
document.getElementById("output").innerHTML = "saving.... Please wait..";
}
My php script just echo a string saved or not saved.
I'm guessing panel.php is also the page that has the form in the first place.
Make sure you die() after outputting your AJAX response, otherwise it will continue happily along outputting anything else on the page - in this case, your form.
Related
I created a modal form (that pops up upon a link click, i.e trigger()). This is the HTML code:
<div class="modalbg">
<div class="modalPopup">
<form action="samepage.php" class="formContainer" method="post">
<h2>Change Desk Number</h2>
<label for="studentid">
<strong></strong>
</label>
<input type="password" placeholder="Your KEY" name="studentid" required/>
<label id="status" style="color:red;"></label>
<button type="submit" class="btn" onclick="return verify()">Upgrade</button>
<button type="button" class="btn cancel" onclick="closeForm()">Close</button>
</form>
</div>
</div>
The JavaScript that controls this modal is:
function trigger(){
document.getElementById("modalPopup").style.display = "block";
}
function closeForm() {
document.getElementById("modalPopup").style.display = "none";
}
function verify() {
var studentid = document.getElementById("studentid").value;
if (studentid != dbstudentid || !studentid){
document.getElementById("status").innerHTML="Invalid Student ID!";
function trigger(event) { event.preventDefault(); }
return false;
}
else{
document.getElementById("modalPopup").submit();
}
}
Everything works at this point (i.e it pops up whenever I click the link and whenever I knowingly try to enter a wrong studentid, it returns the "Invalid student ID" on the "status" label. (Note: I had already saved the session's student ID in the variable dbstudentid using:
var dbstudentid = <?php echo json_encode($dbstudenid);?>;
My problem however comes from when I try to execute the PHP on the same page.
Whenever I insert the PHP code into the modalbg div or modalPopup div inside it, the entire modal refuses to pop, let alone submit.
This is the PHP code I used (it should be noted that at the beginning of the page, I had already used include(configure-db.php) and session_start() ) :
<?php
if(isset($_POST['studentid'])){
$studentid = $_POST['studentid'];
$desk = 1;
$deskstatus ="";
$select = "UPDATE users SET deskNo = '$desk' WHERE name='$SESSION';
}
if (mysqli_query($MyConn, $select)) {
$deskstatus = "Desk changed successfully!";
} else {
$deskstatus = "Error";
} return $deskstatus;
?>
I have tried everything, the modal just refuses to come every time, let alone successfully make the Desk Update on my Database. to make things worse, whenever I refresh the page, the modal which I set to display:none; by default on CSS suddenly starts showing. But whenever I remove the PHP code, it returns to normal.
Do I need to make the action execute in a separate page? If yes, please how?
Else, how please?
I world highly suggest you think about using AJAX to handle this probolem.
let's clear up things.
you can write var dbstudentid = '<?= $dbstudenid ?>'; instead of var dbstudentid = <?php echo json_encode($dbstudenid);?>; this will give you freedom of JS native datatype.
you need to send this form request through ajax and recive output there.
Change the php code else part to like this
else { $deskstatus = "Error: " . mysqli_error($MyConn); }
Now when there is a actual problem on code you will know what was the problem. and it will not break you interface.
4. Create seperate file that handle this form request.
5. Here is code snippet of plaing JS AJAX implementation
let post = JSON.stringify(postObj)
const url = "https://jsonplaceholder.typicode.com/posts"
let xhr = new XMLHttpRequest()
xhr.open('POST', url, true)
xhr.setRequestHeader('Content-type', 'application/json; charset=UTF-8')
xhr.send(post);
xhr.onload = function () {
if(xhr.status === 201) {
console.log("Post successfully created!");
let AlertDiv = document.querySelector('#alert');
AlertDiv.innerHTML = xhr.response;
}
}
I have 3 files linked together index.php functions.js and compute.php
index.php has a div that calls a function in functions.js: compute() that sends an AJAX request to do something in compute.php
index.php:
<form id = "input_form">
<textarea name = "row" id = "inputform" placeholder="Input row here"></textarea>
<input type = "submit" value = "Enter" onclick="compute(inputform.value);">
</form>
<div id = "output_container">
<p id = "output"></p>
</div>
When the button is pressed, compute() is called passing in whatever was in the textarea as data.
function compute(row){
var xhttp;
if(window.XMLHttpRequest){
xhttp = new XMLHttpRequest();
}
else{
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4) {
output.innerHTML = xhttp.responseText;
}
};
xhttp.open("GET","compute.php?row="+row,true);
xhttp.send(null);
}
This passes the value into a php script which simply is suppose to output what was in the textarea into #output
<?php
$str = $_GET['row'];
echo $str;
?>
When I test my program by clicking the button, nothing happens indicating something went wrong. I tried to pinpoint the problem by adding a window.alert('something'); after the check if(xhttp.readyState == 4) but a popup box never appears, making it seem like the issue is between functions and compute.
I tested out phpinfo(); and it looks like php is working properly on my server as well
Problem: Form is getting submitted without making ajax call, because your code contains type='submit'
Solution: Change type to button:
<input type = "button" value = "Enter" onclick="compute(inputform.value);">
Also update code to fetch the output properly:
if (xhttp.readyState == 4) {
document.getElementById("output").innerHTML = xhttp.responseText;
}
I have a form, which can either be submitted via AJAX or usual way, working with the submit button. The Ajax part is here:
parentForm.onsubmit = function(e) { // e represents trigering event
if(srteValidateMode()){ // works only in WYSIWYG mode
var outputString = srteEditArea.innerHTML; // first we prepare the text output data
outputString = outputString
.replace(/<(\/?)strong>/gi, '<$1b>') // unify output tags for all browsers -> B I P (instead of strong em div)
.replace(/<(\/?)em>/gi, '<$1i>')
.replace(/<(\/?)br>/gi, '<p>')
.replace(/<(\/?)div/gi, '<$1p');
document.getElementById('simpleRTEoutput').value=outputString; // pass output string to hidden form field
if (srteAjaxSubmit) { // ajax version - filling FormData
e.preventDefault(); // canceling the submit function - we will call it with Ajax
var srteFormData = new FormData(e.target); // getting form data from submitted form
var ajaxRequest = new XMLHttpRequest(); // now going to invoke AJAX
ajaxRequest.onreadystatechange = function () {
if (ajaxRequest.readyState == 4 && ajaxRequest.status == 200) {
srteShowInfo(ajaxRequest.responseText); // return message and display as info window
}
}
ajaxRequest.open("POST", e.target.action); // getting target script from form action
ajaxRequest.send(srteFormData); // send FormData
}
else { // Standard submit
return true; // true = standard submit will proceed (works ok)
}
}
else {return false;} // on false return form will not be submitted
};
It works fine. Now I want to add redirection functionality - clicking on another (non submit) button with some onclick function to SAVE (do the predefined submit) AND redirect. I have such Idea (not tested), but not sure it this might work especially in the AJAX part.
function srteSubmitForm(redirectTo) {
if (srteAjaxSubmit) { // redirect when submitted via Ajax Call
parentForm.submit(); // save form data
window.location.href = redirectTo; // change location - does it wait for previous function ?
}
else {
parentForm.action = parentForm.action + '?redirect=' + redirectTo; // rest handled by target PHP
parentForm.submit();
}
}
Button in HTML then would look like:
<input type="button" onclick="srteSubmitForm(\"somepage.php?page=A\")" value="Redirect A">
<input type="button" onclick="srteSubmitForm(\"somepage.php?page=B\")" value="Redirect B">
<input type="button" onclick="srteSubmitForm(\"somepage.php?page=C\")" value="Redirect C">
I am not sure, if I need to wait for the AJAX to be finished somehow before redirect ? Or any other way how redirect after the submit?
no jQuery solutions, please.
Thanks, Jan
Why not add a 'callback' parameter to your submit method that gets called when the call completes.
parentForm.submit(function(status){
//The call completed, you can display a confirm message 'Form submitted,
//now redirecting' (because it's not nice to redirect without warning ;)
window.location.href = redirectTo;
});
And in your submit:
ajaxRequest.onreadystatechange = function () {
if (ajaxRequest.readyState == 4 && ajaxRequest.status == 200) {
srteShowInfo(ajaxRequest.responseText);
if(callback instanceof Function) callback(ajaxRequest.responseText);
}
}
I have a form on my site that when submitted takes the user from Page1.html to Page2.html.
I would like to display a message between the form being submitted and "Page2 loading".
Can someone provide me with an example of this?
If your form submit data via ajax then you could try something this:
$('form#myform').submit(function(e) {
e.preventDefault();
$('#message').html('Sending....'); // #message may be a div that contains msg
$ajax({
url: 'url_to_script',
data: 'your_data',
success: function(res) {
// when submit data successfully then page reload
window.location = 'page2.html'
}
});
});
What you're looking to do can't be done by standard form submission.
You'll want to submit the form using ajax, and display a "Please wait" message while you are waiting for a response. Once the response is received and validated to be OK, you can then redirect the user to the page you now call page2.
The easiest way to submit a form via ajax is to serialize it to a string and pass it along. Then, you'll need a page to process the received data, and return an OK or and ERR.
The JS will then need to decipher next action.
This is not tested, but copied and pasted from various working projects.
You'll need to download and include the json2.js project.
page1
<div id='pleaseWait'>Please Wait...</div>
<form id="theForm" onsubmit="doAjaxSubmit();">
<input type='text' name='age' id='age' />
<input type='submit' value='submit'>
</form>
<script type="text/javascript">
function doAjaxSubmit(){
var j = JSON.stringify($('#theForm').serializeObject());
$('#pleaseWait').slideDown('fast');
$.post('processor.php?j=' + encodeURIComponent(j), function(obj){
if(obj.status=='OK'){
window.location='page2.php';
}else{
$('#pleaseWait').slideUp('fast');
alert('Error: ' + obj.msg);
}
}, 'json');
return(false);
}
$.fn.serializeObject = function(){
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
</script>
processor.php
<?php
$j=json_decode($_POST['j'], true);
if ((int)$j['age']<=0 || (int)$j['age']>120){
$result = array('status'=>'ERR', 'msg'=>'Please Enter Age');
}else{
//Do stuff with the data. Calculate, write to database, etc.
$result = array('status'=>'OK');
}
die(json_encode($result));
?>
This is essentially very similar to the answer below (by #thecodeparadox), but my example shows how to pass the entire for without having to manually construct your data object, shows how to validate on the PHP side as well as return the appropriate JSON data to either redirect the user, or to display an error, and uses animations to display the message.
Here's how the situation looks :
I have a couple simple forms
<form action='settings.php' method='post'>
<input type='hidden' name='setting' value='value1'>
<input type='submit' value='Value1'>
</form>
Other small forms close to it have value2, value3, ... for the specific setting1, etc.
Now, I have all these forms placed on the settings.php subpage, but I'd also like to have copies of one or two of them on the index.php subpage (for ease of access, as they are in certain situations rather frequently used).
Thing is I do not want those forms based on the index.php to redirect me in any way to settings.php, just post the hidden value to alter settings and that's all.
How can I do this with JS ?
Cheers
Yes, you could use an ajax call to send a request to the settings.php file. You'd probably want that PHP code to return something that the JavaScript can use to know if the request was successful or not (for example, using JSON instead of HTML).
Here is an ajax getData function.
function getData(dataSource, targetDiv){
var XMLHttpRequestObject = false;
if (window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
XMLHttpRequestObject = new
ActiveXObject("Microsoft.XMLHTTP");
}
if(XMLHttpRequestObject) {
var obj = document.getElementById(targetDiv);
XMLHttpRequestObject.open("GET", "settings.php?form="+dataSource+"&t="+new Date().getTime());
XMLHttpRequestObject.onreadystatechange = function()
{
if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200) {
obj.innerHTML = XMLHttpRequestObject.responseText;
}
}
XMLHttpRequestObject.send(null);
}
}
use this function to send the form to your setting.php file which should return confirmation message to index.php(inside targetDiv).
Parameters of the function
1) dataSource - is the variable value that you send to settings.php
2) targetDiv - is the div on index php that with display the response from settings.php
Hope it makes sense.