I am creating an AJAX+PHP submit form, for example purposes. For this, I will need Ajax, PHP and index.html file to write into the inputs. The problem is that, when I submit I have no way of redirecting a page, so I created this hack. (since page redirect get permission from the PHP script first) otherwise show error.
AJAX
function submit_form(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
if(xmlhttp.responseText.trim() == 'success'){
location.href = '/success';
}
//
var e = doc.querySelector('.form-error').innerHTML = xmlhttp.responseText;
}
}
And this is my PHP.
<?php
echo "/success";
if($_GET){
}else{
echo "error, no value found";
}
as you can see, this allows me to redirect the page, as the javascript will read the "/success" and redirect the document, but one problem with this is that, I don't like using echo, because the page actually shows "success" before redirect. I don't want it to show anything to the page.
Change your echo statement to return json_encode(), then in your JS code, you can parse it using JSON.parse();
In your PHP removes the slash of this line: echo "/success";
And in your java script code, add a else sentence before print error:
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
if(xmlhttp.responseText.trim() == 'success') {
location.href = '/success';
}
else {
var e = doc.querySelector('.form-error').innerHTML = xmlhttp.responseText;
}
}
}
Related
is there any way to pop an alert only after a .php file running from php server is done executing? this may be the only way to fix my problem if there is...
my .php is:
<?php
$output = exec("arduino_debug.exe --upload RIKDuino\RIKDuino.ino
IF !ERRORLEVEL! == 0 (
echo upload success!!
pause)
IF !ERRORLEVEL! NEQ 0 (
echo upload failed
pause) 2>&1" );
echo $output;
?>
my function that executes the .php file in my html page
function UploadToRIK()
{
ForIde();
var xmlhttp;
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status== 200)
{}
}
xmlhttp.open("POST","Arduino/upload.php",true);
if(window.confirm ('Code will be Uplaoded to RIK Robot! Please Press OK to Continue...'))
{
xmlhttp.send("upld");
}
}
You are almost there. Just add the logic you want inside the callback function which is attached to the onreadystatechange event:
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status== 200)
{
//put some logic, for example:
alert('All good! ' + xmlhttp.responseText);
}
}
This way you will see the alert popping out when a response is received (and the http status is 200), after your PHP script finishes.
You can also check for other states (or http statuses different from 200), in the case of failure, for example and treat them properly.
For further info about it, try
readyState
and
XMLHttpRequest
Im working on an ajax form to show errors without reloading the page. So if everything is good, the user we be redirected to home.php. At the moment the user will also be redirected when there is an error.
This is my code so far:
index.php:
<script>
function myFunction()
{
var elements = document.getElementsByClassName("formVal");
var formData = new FormData(elements);
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
window.location.replace("/index.php");
}
}
xmlHttp.open("post", "login.php");
xmlHttp.send(formData);
}
</script>
login.php
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if (!$user->logUser($$_POST['username'], $_POST['password'])) {
echo 'ok';
} else {
echo 'not ok';
}
}
?>
Remove loop from the code and pass elements in FormData() because passing element will take all the fields inside the form
var elements = document.getElementsByClassName("formVal");
var formData = new FormData(elements);
Throw a 401 error if it fails login, this will stop the redirect.
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if (!$user->logUser($$_POST['username'], $_POST['password'])) {
echo 'ok';
} else {
header("HTTP/1.1 401 Unauthorized");
exit;
}
}
?>
do you know jquery ?
jquery w3 school search on google
avaible
$('#data-div-id').load('www.sdasd .php ? or whatevver');
function tmp_func_sil_ok(e){
$.ajax({type:"GET",url:"go.php",data:{'snf_sil':e},success: function(e){msg_("<h3>Başarılı</h3>");}});
}
I want to have a hyperlink on a html page run a variable that is defined in my python file. The variable is going to clear my database. Here is the code I am trying to use.
Python
#app.route('/log')
def log():
cleardb = db.session.delete()
return render_template('log.html', cleardb=cleardb)
Html
<a onclick="myFunction()">Clear database</a>
Javascript
<script>
function myFunction()
</script>
I don't know what javascript I need to run the variable. I want to make the cleardb get triggered so that it will delete the database.
Thanks
You need to make an ajax request with javascript to /log, it would look something like this:
function myFunction() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if (xmlhttp.status == 200) {
//Do Success functionality here
}
else if (xmlhttp.status == 400) {
//Handle 400 errors here
}
else {
//All other errors go here
}
}
};
xmlhttp.open("GET", "/log", true);
xmlhttp.send();
}
I often seen websites with a search function and when they search for something, the web page often changes the url to something along the lines of
search.php?q="searchquery"& etc , i have a search page on my site and i use ajax to submit a form that has a search input and sends to a php page which searches through my database and returns data to a specific div on the original page via echo.
function getdata() {
var str = document.getElementById("searcb");
document.getElementById("demo").innerHTML = "You are searching for: " + str.value;
document.getElementById("searchresults").style.display="block";
if (str == "") {
document.getElementById("demo").innerHTML = "";
return;
}
else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("searchresults").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "getuser.php?q=" + str.value, true);
xmlhttp.send();
return false;
}
}
HTML
<form onsubmit="return getdata()">
<input type="search" id="searcb" name="searchBar"></br></br>
</form>
My question is what am i doing differently that causes my url to remain the same compared to a common search engine
In general the url change because a post that reload the page is performed. Your url will not change because you call make an ajax call that will not reload your corrent page .
I'm getting really confused with php,ajax and javascript.
I'm using some ajax code I got from w3 schools to handle a form and display it below the form input. However, I can't seem to get my php and Javascript right. I'm using JavaScript in php tags where I then Get my variable in the same php tags and echo it. I then try to get that variable in ajax. I don't think I'm correctly getting the variable with ajax and inside my php. Does anyone have some advice.
Thanks
Heres my javascript in my html doc
<script>
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "hackacronymphp.php?phpAnswer=" + str, true);
xmlhttp.send();
}
}
</script>
Here's the last part of my script with my php afterward all inside one php tag
var stringe = vari.join("");
console.log(stringe);
var answer = dataarray[stringe];
console.log(answer);
</script>
$phpanswer = $_GET['answer']
echo $phpanswer ;
?>