Trufa
Trufa

Reputation: 40717

Load php content with jQuery AJAX

My problem:

I have index.html:

<form action="toload.php" method="post">
Input: <input type="text" name="something" value="" /><br />
<input type="submit" value="Submit!" />
</form>

toload.php is something like:

<?php

echo "Your input was: " . $_POST["something"];

?>

The question is quite simple.

When I press the Submit! button, I would like to dynamically load the content toload.php in index.html without the need of a refresh.

Thanks in advance! please comment for any needed clarification.


EDIT, a more verbose explanation:

I'm not sure I'm being clear (or maybe I'm not understanding the answers do to my lack of technical skills) so I'll give it another go. (re-write)

I have an HTML for with a submit button that sends a variable through POST method.

This variable is used by a PHP file and after a certain process, it inserts and update a MySQL database and echoes out some other stuff.

This is working JUST FINE.

But now I want to improve it by avoiding the page "reload" (going to the .php).

I want the HTHL that comes as an output of my HTML file to be dynamically shown in my HTML page.

Is it more clear now?

Upvotes: 2

Views: 10636

Answers (3)

FeRtoll
FeRtoll

Reputation: 1267

something like this with jQuery!:

<form action="toload.php" method="post">
Input: <input type="text" id="something" name="something" value="" /><br />
<input type="submit" value="Submit!" onclick="submitme()" />
<div id="something2"></div>
</form>

and function to submit:

function submitme(){
var tosend=document.getElementById("something").value;
$.ajax({
        type: 'POST',
        url: 'toload.php',
        data: 'something='+tosend,
        success: function(msg){
            if(msg){
                document.getElementById("something2").innerHTML=msg;
            }
            else{
                return;
            }
        }
    });
}

Upvotes: 3

mVChr
mVChr

Reputation: 50185

In your case you can use $.post()DOCS. If you gave your form an id="myForm" then you could load the return data into the form's parent in the callback as follows:

$('#myForm').submit(function(e){
  e.preventDefault();
  $.post("toload.php", $("#myForm").serialize(), function(data) {
    $(this).parent().html(data);
  });
});

Upvotes: 0

Radek
Radek

Reputation: 8376

You must use AJAX (XMLHttpRequest) for that - http://www.w3schools.com/XML/xml_http.asp.

(You've said simply - as long loading 100KB of jQuery is not simply IMHO, I suggested pure JavaScript solution)

Upvotes: 0

Related Questions