I have a bit of a problem with my website. I have phpbb integrated into my website and a login form on the homepage. This form needs to execute two different actions. It first needs to run the ucp.php (to log into phpbb) and also the login.php (to hide the form and add control panel on home screen). They both work by themselves, I just need a way to have them together when a user logs in. i have researched this for a while and can't find a solution. Thanks in advances, Josh
I need to combine this
<form action="./forums/ucp.php?mode=login" method="post" enctype="multipart/form-data">
with this
<form action="login.php" method="post" enctype="multipart/form-data">
I think you have a serious design issue in your code if you have to "merge" stuff like that, but in any case:
Just create a new file ie. post_handler.php and toss this code in it:
<?php
include('forums/upc.php');
include('login.php');
?>
Place it in the same directory as login.php.
Then adjust your form to point to post_handler.php?mode=login.
Ofcourse merging files like that could result in crazy unexpected results..
Another option, though more complex, would be to use the login.php as your action and do a curl request to forums/ucp.php inside it. (search for Curl on php.net documentation)
Unfortunately I can not give more suggestions, because what you are trying to do is probably more complex then something that can easily be answered here.
Well you can try trick with ajax. Here is an example that should work with jquery:
Im not sure if preventDefaut() wont make us a problem here and we still be allowed to use .submit() on it. If it wont work. Try to put whole thing into function, remove preventDefault and bind this function into submit button.
<form id="form_id" action="login.php" method="post" enctype="multipart/form-data">
User name: <inputy type="text" id="username" name="username" />
</form>
<script type="text/javascript">
$(function() {
//we prevent normal form submit
$('#form_id').preventDefault();
var data = {} ;
//here u build data u want send by taking it from form field by field
//example
data['username'] = $('#username');
//and you send this data via ajax to your upc script
$.ajax({
type: "POST",
url: '/forums/ucp.php?mode=login',
data: data,
//in case of succes we send form normal way
success: function( xhr ) { $('#form_id').submit(); },
dataType: String
});
});
<script>
Related
Hello guys I'm new to internet languages and I would like your help explained with apples!
I'm trying to make a webserver controlled robot with a raspberry pi 3b+. I already got that working with some HTML calling some PHP code and then executing Python scripts in order to move the robot. The thing is, when I press a button to move the robot the page refreshes then loads everything again making it really annoying. (HTML and PHP are in the same document)
I've read some post where people say to use <button> tags with type="button", but when I do that nothing happens. Let me share with you the code. Other people say to use AJAX, but I don't really know how to.
HTML:
<form action="" method="post">
<div>
<div>
<button type="button" name="boton7"><img src="imagenes/up.png"></button>
</div>
<div>
<button type="button" name="boton8"><img src="imagenes/left.png"></button><!--
--><button type="button" name="boton10"><img src="imagenes/stop.png"></button><!--
--><button type="button" name="boton9"><img src="imagenes/right.png"></button><!--
-->
</div>
<div>
<button type="button" name="boton6"><img src="imagenes/down.png"></button>
</div>
</div>
</form>
PHP:
<?php
//Primera fila || mover_arriba.py
if(isset($_POST['boton6'])){
exec('python /var/www/html/mover_arriba.py');
}
//Primera fila || mover_abajo.py
if(isset($_POST['boton7'])){
exec('python /var/www/html/mover_abajo.py');
}
?>
I would like to know if it can done without using AJAX or JS (interpreted languages are confusing to me) or if I can modify something on this code to achieve what I want. As you can see I used a form, I don't really understand if a button can do something without a form, why sometimes people use input="submit", I've also seen "onclick=". Please use as clear as possible answers.
If you need anything else please let me know!
EDIT: I forgot to mention that if I remove type="button" from this <button type="button" it works.
The bad news is that you will have to use JavaScript and AJAX to accomplish this. There's simply no (reasonable) way around it.
The good news is that what you want to do is actually quite simple. Since there is no conditional data and no return data to handle, the bar is already pretty low. I also assume that you are not worried about bad actors abusing vulnerabilities in your code, so let's dive in.
First off, let's get a library that can do AJAX calls. While not necessary, this makes everything a lot easier.
Inside your <head> element, put the following line:
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
Next, add an ID to your <form> element so it is easier for us to access with jQuery.
<form id="robotform" action="" method="post">
Now let's add some JS below the form to handle the form submissions. It has to be placed after because the html elements need to exist before this code is called. Code below is mostly adapted from the answer to this question: Submitting HTML form using Jquery AJAX
<script type='text/javascript'>
/* Get the name of the button that was pressed */
var buttonpressed;
$('button').click(function() {
buttonpressed = $(this).attr('name');
})
/* attach a submit handler to the form */
$("#robotform").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* target url is the current page */
var url = window.location.href;
/* Create the data as a string so the button name is sent properly */
var data = buttonpressed + '=true';
/* Send the data using post with element id name and name2*/
var posting = $.post( url, data );
/* Alerts the results if unsuccessful */
posting.fail(function( xhr, status, error ) {
alert('Error sending the command: ' + error);
});
});
</script>
One possible solution could be that you could have your PHP code return a 'false' value back to the form. This would prevent the page from refreshing.
This way the PHP code will call the python code but the form will not refresh since it has received a false value back from the PHP function.
I have a form which automatically refreshes the page on submit, I have tried adding:
onSubmit="return false;" to the form element, but then the form just stops and nothing happens when you click submit.
I wouldnt mind the page refresh so much but the form is at the bottom of the page and the refresh kicks you back to the top. So I tried this approach:
<form name='test' method='POST' action="index.php" onSubmit="window.scrollTo(5000,500);">
This works for a split second but then something else overrides it (not sure what)
I have also tried using php: header.location just to get a "headers have already been sent" error.
The site in question can be seen here, and the form is at the very bottom.
The only two jquery libraries I am using that I could foresee any conflicts with are nicescroll and (more likely) waypoints, but i dug through them both and couldn't find any conflicting issues.
If anyone knows of a way to keep the functionality of the form but stop the refresh of the page, that would be wonderful
Thanks
EDIT: After reading the answers below, it looks like I will have to use ajax to acomplish this, I have absolutely no experience with ajax, so I will see how that goes.
It seems you need to go through of way of AJAX submission in that case. In that case, you can use jQuery $.ajax() method to do that. A sample below:
HTML
<form name='test' method='POST' action="index.php">
jQuery
$('form[name=test]').submit(function(e) {
e.preventDefault();
window.scrollTo(5000,500);
// a sample AJAX request
$.ajax({
url : this.action,
type : this.method,
data : $(this).serialize(),
success : function(response) {
}
});
});
Here, .preventDefault() is for stop page refresh on form submit.
Why not submit the form to a hidden IFRAME?
<iframe name="myiframe" style="display: none;"></iframe>
<form name='test' method='POST' action="index.php" target="myiframe">
...
</form>
What about using AJAX instead of a normal form submit?
I am trying to run this tutorial
i did not implement the validation part yet, but my problem shouldn't be based on this. Here is my code:
<script type="text/javascript">
$("#submitbutton").click(function () {
var content = $.("#contentarea").val();
$.ajax({
type: "POST",
url: "addArticle.php",
data: content,
success: $.("#addArticle").append("<p>ok</p>")
});
return false;
})
</script>
As seen in the demo, it should not refresh the page because of the return false statement and also should do a post instead of get. But neither it does. It will continue to reload the page and also append the given content to the url as an argument. How do i prevent this / where is my failure?
Here is the whole thing
The tutorial you have followed is incorrect. There are more ways to submit a form than just clicking on its submit button (for example, you can press return while in a text field). You need to bind your code to the form's submit() event instead of the button's click() event.
Once you have done this, use your in-browser debugger to check whether the code is actually being run when you submit the form.
Also, the success parameter needs to be a function:
submit: function() { $("#addArticle").append("<p>ok</p>") }
EDIT : also, you have written $.( instead of $( several times. This will cause a runtime error, which may cause the code that blocks the submission to fail.
Well well well...
A few less nerves later, it works.
I decided to use the jquery form plugin
But, and i bet you'll love that, i have no idea why it is working:
<script>
$(document).ready(function() {
$('#addForm').ajaxForm(function() {
alert("ok");
});
});
</script>
<div id="addArticle">
<form id="addForm" method="post" action="addArticle.php">
<textarea id="contentarea" required="required" name="content"> </textarea>
<br />
<input type="submit" id="submitbutton">
</form>
</div>
I guess the author has done pretty good work, just wanted to tell my solution to that future guy who is searching on google for that problem.
I have a working PHP registration form that goes through $_POST[] requests to check user inputs.
Username length (3-20)
Username availability
Username /^[A-Za-z0-9_]+$/
etc.
Rather than have it take you to a whole new page to display errors, I want a live request to call for the errors from register.php so they will appear in a div on the registration.
<div id="errors">" . $usernameErrors . "</div>
I've been trying to read up on AJAX but have noticed most codes involve utilizing $_GET[].
What will I have to do to get my current forms integrated with AJAX?
My Current Basic Registration Form Logic:
<form method="post" action="register.php">
<input type="text" name="username" id="username" required />
$usernameErrors
</form>
And register.php contains all of the checks already.
If you're using jQuery, it's pretty simple.
<script type='text/javascript'>
$.post('/register.php',
{username: $('#username').val()
// insert values of other fields here
},
function(response) {
// update your div with errors
$('#errors').html(response);
})
</script>
You should invoke this code, for example, when user changes username in registration form. It will happen in background and update page asynchronously.
Your register.php script should, in this case, emit only errors, not the whole page, or you will see unexpected results. :-)
In order to simplify ajax, you can use jQuery (a very powerful JS lib).
Add jquery***.js to your project and refer it on your page:
<< script type="text/javascript" src="#js/jquery-ui-1.8.16.custom.min.js" />
Then, you create the javascript function that will make the ajax call.
On the ajax call, you specify the php file to call and the function to handle the return of php(callback). On this callback function, you add the error message to body.
function verifyForm(){
$.ajax({
type: "POST",
url: "register.php",
data: "username=NAME_GOT_FROM_FORM_&location=Boston"
}).done(function( returned ) { //the callback
$('#errors').html(returned); // add the string returned to div id=errors
});
}
So, the crux of the problem as you're asking it seems to be that you're (correctly) using a POST request on your register form, but your tutorials all want to use GET. Here's a discussion about the difference between the two methods:
http://thinkvitamin.com/code/the-definitive-guide-to-get-vs-post/
If you're actually registering the user with AJAX (rather than just validating) you should be submitting the AJAX request as a POST. If you're using jQuery, the answer has already been given. If you're not using jQuery, then look for the XMLHttpRequest object in your tutorial, and where its "open" method is called (reference here: http://www.w3.org/TR/XMLHttpRequest/). The first parameter of that function is a request method--change it to "post" rather than "get", and the request will be treated like a POST, which register.php expects.
That being said, it sounds like you just want AJAX to validate the form. In that case, GET is the correct verb to use--all you want to do with AJAX is check data against the database, not actually make a change to data. I would suggest that you actually write a new PHP script like validate_registration.php that will perform only the validation logic in register.php, and then return a JSON array of errors (which would be empty if no errors occurred). You can activate/deactivate your form submit button based on that return value, and let the user submit the form just like your old workflow if everything is okay.
The tl;dr here is that you should read up on what makes $_GET and $_POST different, and then write an AJAX-specific validation script so that you're separating the data-retrieval part of your process from the data-insertion part. Once you understand the difference, the rest should follow.
I'm passing some variable from one file to another php file that contains a form via jQuery ajax. On The form page where data is being passed to have the following code in it, The values are getting passed in properly and and fields are getting populated with the correct entries, i'm able to very this with firebug response, but page is not automatically submitting. Is their anything i should be looking for that is preventing form from auto submitting. If i access the form page directly, i can see auto submit works.
<?php
$title = $_POST['title'];
$wrapper = $_POST['wrapper'];?>
<form action="test.php" method="post" id="publish">
<input type="text" value="<?php echo $title ?>" name="title">
<textarea name="wrapper"><?php echo $wrapper?></textarea>
<input type="submit" value="Submit">
</form>
<script>
window.onload = function(){
document.getElementById('publish').submit();
}
</script>
ajax code that is sending the values looks like this
$.ajax({
type: "POST",
url: "process.php",
data: {
title: 'test',
wrapper: 'testing123'
},
success: function(msg){
alert( "Data Saved: " + msg );
}
});
Spot the difference:
getElementById('publishForm')
id="publish"
From what I see the auto submit is linked to the 'publishForm'
However, your form Id is "publish"
This is probably the cause of the code not working.
Perhaps you should show us the caller code instead of the handler code. Most likely what you're dealing with is the JS not being run during the AJAX call - the PHP page processing is server side.
You could look into sending the form using PHP Curl instead of JS? That would probably address the issue where it works loaded directly, but fails when called from another page.
As far as I understood, that HTML is being loaded through AJAX, right? If so, then window.onload will not be fired since the page was already loaded (AJAX doesn't count). Just do this:
<script type="text/javascript">
document.getElementById('publish').submit();
</script>
EDIT
To break this down:
Your code on SourcePage.php(I made up this name for reference) is posting data to process.php via an AJAX request
process.php then injects "title" & "wrapper" into the html markup and returns html with some javascript to SourcePage.php
You're then expecting that displaying the resulting string (msg) of the returned html on SourcePage.php will get the javascript in that string to execute.
To get this working, you'll need to do a few things.
Parse out the incoming javascript from the html.
Inject the incoming parsed HTML into SourcePage.php's markup.
Pass the parsed out JavaScript into JavaScript's eval function.
Doing this should bring the page from the process.php and successfully execute the JavaScript code on SourcePage.php.
If you were expecting that the JavaScript would run on the server, then I'm afraid you're mistaken as the server(php runtime) will not execute the JavaScript on the server. Perhaps a redirect on the server will accomplish your goal (whatever that may be).
Original
Try this out: http://jsfiddle.net/NiceGuy4263/eJLMS/