Transfer information from php to site without refresh site (ajax)

Hallo,
i’m trying to transfer information from php to html without refresing site.
I have php script, whitch validating data form. I would like to transfer information from php to html.
I know i have to use AJAX but all examples includes validation. How can i induce php without js validation and show information form php?

The answer to this depends on a couple of things.
1: Are you loading a framework that may couch ajax functions (jQuery, etc)
2: What code have you attempted that includes validation? TBH I don’t actually recall many examples of AJAX having validation in them…

On site I’m using jquery 3.3, my php returns echo’s strings

Short look

$errors = [];

if (empty($_POST["profil"])) {
    $errors[] = "complete profil ";
} else { 
	$profil = implode($_POST['profil']);
}
if (empty($_POST["wiztype"])) {
    $errors[] = "complete type ";
} else { 
	$wiztype = implode(", " ,$_POST['wiztype']);
}
...

if (count($errors)) {
    echo 'Please complete: '.implode(', ', $errors);
    exit;
}

$body = "...";

$success = mail($to, $subject, $message, $headers);
echo $success ? "Mail is sended." : "Error sending";

So jquery wraps AJAX requests for you.
I can see in your PHP that you’re going to be sending data via POST.
Have a look at the jQuery documentation for .post() (you’re probably more interested in the examples rather than the technical bits at the top) and give it a whack. If you run into problems, we can address those specifically.

I tryed some like this, but it doesn’t work

 $.ajax({
        type: "POST",
        url: "assets/php/brief-wiz.php",
        success : function(text){
            if (text == "success"){
                success();
            } else {
                errors();
                errors(false,text);
            }
        }
    });
 

can you say what wrong with this code?

It needs the data element supplied to it. It’s gotta know what to send your PHP script! :wink:

It’s all php script:

<?php

$errors = [];

if (empty($_POST["profil"])) {
    $errors[] = "Please complete profil ";
} else { 
	$profil = implode($_POST['profil']);
}

if (empty($_POST["wiztype"])) {
    $errors[] = "Please complete wiztype ";
} else { 
	$wiztype = implode(", " ,$_POST['wiztype']);
}

if (empty($_POST["scale"])) {
    $errors[] = "Please complete scale ";
} else { 
	$scale = ($_POST['skala']);
}

if (count($errors)) {
    echo 'Please complete: '.implode(', ', $errors);
    exit;
}
	
	
$body = "";

$body .=  "<div style='margin-top:20px;'><b>Profil:</b> " . $profil . "</div>";

$body .=  "<div style='margin-top:20px;'><b>Wiztype:</b> " . $wiztype . "</div>";
$body .=  "<div style='margin-top:20px;'><b>Scale:</b> " . $scale . "</div>";

$to       = 'my@mail.com';
$subject  = 'Contact form';
$message  =  $body;

$headers = "From: webmaster@example.com" . "\r\n";
$headers .= "Reply-To: " . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=UTF-8\r\n";

$success = mail($to, $subject, $message, $headers);


echo $success ? "Mail is sucesfull sended" : "Error.";

Thank You for attention :slight_smile:

Right, so your PHP script is expecting 3 things in the data element:
“profil”,“wiztype”, and “scale” (BTW, look out, you’ve called it scale the first time, and skala the second… choose one.)
So, we need to stick some data into our javascript to transmit those values.

I dont know where those values are coming from in your HTML, but it may look something like this:

 $.ajax({
        type: "POST",
        url: "assets/php/brief-wiz.php",
        data: {"profil": document.getElementById("profil").value,
               "wiztype": document.getElementById("wiztype").value,
               "scale": document.getElementById("scale").value,
              },
        success : function(text){
            if (text == "success"){
                success();
            } else {
                errors();
                errors(false,text);
            }
        }
    });

It doesn’t work… what i doing wrong?

it’s html:


<form>
<input class="std-profil profil" type="radio" name="profil[]" value="1">
<input class="std-profil profil" type="radio" name="profil[]" value="2">
<input class="std-profil profil" type="radio" name="profil[]" value="3">
<input class="std-profil profil" type="radio" name="profil[]" value="4">

<input type="checkbox" class="wiztype" name="wiztype[]" value="1">
<input type="checkbox" class="wiztype" name="wiztype[]" value="2">
<input type="checkbox" class="wiztype" name="wiztype[]" value="3">
<input type="checkbox" class="wiztype" name="wiztype[]" value="4">

<input class="scale" name="scale">

<input type="submit" id="submit" name="submit" class="submit" value="send">

</form>

PHP

<?php

$errors = [];

if (empty($_POST["profil"])) {
    $errors[] = "Please complete profil ";
} else { 
	$profil = implode($_POST['profil']);
}

if (empty($_POST["wiztype"])) {
    $errors[] = "Please complete wiztype ";
} else { 
	$wiztype = implode(", " ,$_POST['wiztype']);
}

if (empty($_POST["scale"])) {
    $errors[] = "Please complete scale ";
} else { 
	$scale = ($_POST['scale']);
}

if (count($errors)) {
    echo 'Please complete: '.implode(', ', $errors);
    exit;
}
	
	
$body = "";

$body .=  "<div style='margin-top:20px;'><b>Profil:</b> " . $profil . "</div>";

$body .=  "<div style='margin-top:20px;'><b>Wiztype:</b> " . $wiztype . "</div>";
$body .=  "<div style='margin-top:20px;'><b>Scale:</b> " . $scale . "</div>";

$to       = 'my@mail.com';
$subject  = 'Contact form';
$message  =  $body;

$headers = "From: webmaster@example.com" . "\r\n";
$headers .= "Reply-To: " . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=UTF-8\r\n";

$success = mail($to, $subject, $message, $headers);


echo $success ? "Mail is sucesfull sended" : "Error.";

JS

<script>
 $.ajax({
        type: "POST",
        url: "assets/php/brief-wiz.php",
        data: {"profil": document.getElementByClassName("profil:checked").value,
               "wiztype": document.getElementByClassName("wiztype:checked").value,
               "skala": document.getElementsByClassName("skala:checked").value,
              },
        success : function(text){
            if (text == "success"){
                success();
            } else {
                errors();
                errors(false,text);
            }
        }
    });
</script>

Are you just sticking that JS in as-is? It’ll fire as soon as you load the page if you do that.
Wrap it in a function and make that function the onclick action of a <button> in your form (remove the submit).

Also, getElementByClassName is not a function. it’s getElementsByClassName (plural). You’ll need to figure out how you want to handle that in the case of the checkboxes. For the radio and input text elements, select the 0’th element of the result array:
"skala": document.getElementsByClassName("skala")[0].value,
You can also shorthand it a bit because you’re using jQuery (which i forgot when writing my example). Here’s how I would do it if I were you:

Step 1: Drop the <form> tag. Since we’re not using a normal form submission, leaving that will just confuse browsers.
Step 2: Change the submit <input> into a <button onclick='submitform()'>
Step 3: Wrap the JS in: function submitform() { .... }
Step 4: the data element can be constructed thusly:

        "profil": $(".profil:checked")[0].value,
        "wiztype": $(".wiztype:checked").toArray().map(function (x) { return x.value; } ).join(","),
        "skala": $(".scale")[0].value

Step 5 (optional): Your PHP will now need to split the wiztype string back down if you want to do anything special with it. If you’re just regurgitating it into an email, it’ll be fine as-is.

(PS: Again, you’ve called your HTML value “scale”, but are trying to reference it by “skala”. Please be careful, because that’ll trip you up. Choose “scale” or “skala”, and update EVERYTHING to match.)

EDIT: Made it IE-friendly by removing the arrow function. Because IE is stupidly noncompliant.

Instead of mapping the form to an array manually you can also use jQuery.serialize instead, which is a lot easier.

Not saying mapping manually is bad, and it certainly is a good learning experience to see what actually goes on, but once you’ve got that down I would use serialize() instead.

Yeah, I considered serializing, but that just shifts the management over to the PHP side, because you’d receive the serialized data, decode it, extract the values from the array, and join them with commas or spaces or something to stick them into the email.

shrug You either lift on the front end or the back end.

It doesn’t if you send the data over as a string directly, ie.

$.post(
    // ...
    data: $('#some-form').serialize()
)

Then on the PHP side you can access $_POST like you normally do, no additional lifting required.

The data key you pass to $.post can be either an array, which jQuery then transforms to a string for you to put in the request, or you can pass that string yourself and jQuery will pass it through untouched.

So data: 'foo=bar&baz=ban and data: {foo: 'bar', baz: ban'} will result in the same request. You were building the second style, .serialize() builds the first style.

…and what does serialize do with the checkboxes array…?

And what would you have to do in PHP to then put it into the email… (see where i’m going with this? Whichever end you do it, you’ve gotta encode it into a string anyway.)

It encodes it properly for an application/x-www-form-urlencoded form, so again PHP will act as if was just posted using a POST form.

See https://codepen.io/rpkamp/pen/QxYrBq

Nothing special, since the code will continue to work as is.

Sorry yes, you’re right. I hadn’t noticed the PHP code was already doing the lifting, which does make serializing the javascript end the better choice.

2 Likes

Thank You m_hutley and ScallioXTX for interested.
Maybe can You Help me last time :slight_smile:

I don’t know what i’m doing wron, becouse POST doesnt work, all data going to URL.

URL looks like:

http://localhost/site/index?profile%5B%5D=Profile2&wiztype%5B%5D=wiztype1&wiztype%5B%5D=wiztype3&skala=small+scale&submit=Send

Data in URL are correct

<form id="form">
...
<input type="submit" id="submit" name="submit" class="embtn btn-1" value="Send" onclick="submitform()">

</form>

JS

$(document).ready(function() {
  function submitform() {
 	$.ajax({
        type: "POST",
        url: "assets/php/brief-wiz.php",
        data: {
               "profil": $(".profil:checked")[0].value,
               "wiztype": $(".wiztype:checked").toArray().map(function (x) { return x.value; } ).join(","),
               "skala": $(".skala")[0].value,
              },
        success : function(text){
            if (text == "success"){
                success();
            } else {
                errors();
                errors(false,text);
            }
        }
    });
	}});

	function success(){
    $(".form-message")[0].reset();
    form-message(true, "Message Submitted!")
	}
	
	function errors(){
    $(".form-message");
    form-message(true, "Message Error")
	}

Mail don’t send, messages dosn’t show :frowning:

OK i have this and is working fine, but not mach as well.

JS

function submitform() {
$.ajax({
    url : 'assets/php/brief-wiz.php', 
    type: 'post', 
    data: $('form').serialize() 
})
.done(function(data) {
    alert(data);
});
};

It’s showing alert form php, i would like to show this messeges in .form-message div

EDIT:

I have messages in div, but site is refreshing after click on submit button.

Yeah, this is what i meant by your browser being confused.

It sees a form tag, it sees a submit button, and it fires the nonexistant action of the form, which defaults to ‘self-reference, GET method.’

Lets at least prevent the action.

function submitform() {

=>

function submitform(e) {
  e.preventDefault();

onclick="submitform()"
=>
onclick="submitform(event)"