Load php content with jQuery AJAX - php

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?

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;
}
}
});
}

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)

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);
});
});

Related

How to get result from php to html use ajax?

Updated: It still not work after I add "#".
I am new to ajax. I am practicing to send value to php script ,and get result back.
Right now, I met one issue which I can not show my result in my html page.
I tried serves answers online, but I still can not fix this issue.
My index.html take value from the form and send form information to getResult.php.
My getResult.php will do calculation and echo result.
How do I display result into index.html?
Hers is html code
index.html
<html>
<body>
<form name="simIntCal" id="simIntCal" method="post"
>
<p id="Amount" >Amount(USD)</p>
<input id="amount_value" type="text" name="amount_value">
<p id="annual_rate" >Annual Rate of Interest
(%)</p>
<input id="rate_value" type="text" name="rate_value">
<p id="time_years" >Time (years)</p>
<input id="time_value" type="text" name="time">
<input id="calculate" type="submit" value="Calculate">
</form>
<p id="amount_inteCal" >The Amount (Acount
+ Interest) is</p>
<input id="result" type="text">
</body>
</html>
ajax script :
<script>
$('#simIntCal').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'getResult.php',
data: $('#simIntCal').serialize(),
success: function (result) {
$("#result").text(result);// display result from getResult.php
alert('success');
}
});
});
</script>
getResult.php
<?php
if ($_SERVER ["REQUEST_METHOD"] == "POST") {
//do some calculation
$result=10;//set result to 10 for testing
echo $result;
}
?>
You are missing the '#' in front of your css selector for result.
$("result").text(result);// display result from cal.php
Should be
$("#result").text(result);// display result from cal.php
index.php
----php start---------
if(isset($_POST['name'])){
echo 'Thank you, '.$_POST['name']; exit();
}
----php end ---------
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
function test(){
var formDATA = {'name': $('#input_name').val()}
$.ajax({
type: 'POST',
url: 'index.php',
data: formDATA,
success: function(response){
$('#result').html();
}
});
}
</script>
<input id="input_name" type="text" value="">
<button onclick="test();">Test Ajax</button>
<div id="result"></div>
Try something simple, this is a very basic version of ajax and php all in one page. Since the button triggers the function you don't even need a form (doesn't mean you shouldn't use one). But i left it simple so you could follow everything.
Sorry when i added php open and closing tags it didn't show up as code.
Also don't forget to include your jquery resources.
In your html file where you want the result to display, you probably want to be using a div.
Currently your code is using an input field:
<input id="result" type="text">
And what you probably want is something like this:
<div id="result"></div>
Unless you were intending to have the result show up in an input field inside your form, and in that case, the input field isn't actually inside your form code.

how does method POST processes/excecutes in PHP

I am building a web application, I am having lots of confusion when ever I use POST method.
Lets say I have the below code
<?php
$abc = 'abc';
if(some condition){
$abc = 'xyz';
}
if(isset($_POST['submit'])){
header("Location:http://someexample.php/$abc");
die();
}
?>
<form method="POST">
<input type="text" name="textinput" />
<input type="submit" name="submit" value="submit" />
<input type="submit" name="clear" value="clear" />
</form>
so as per my understanding, If I am not wrong.
When I click the SUBMIT / CLEAR button. The PHP file reloads the self page first before redirecting it to the header location.
If I am right. Is there any other way to avoid multiple redirects when we are working on big PHP files. When I have multiple SUBMIT button.
thank you in advance
You are basically redirecting your request to another page. Instead of redirecting the page using header you should use the action attribute of the form.
<form method="POST" action="yourexample.php" id="myForm">
<input type="text" name="textinput" />
<input type="submit" name="submit" value="submit" />
<input type="submit" name="clear" value="clear" />
</form>
the form will redirect you to the second page. If you do not want to reload your page at all you should use ajax. You can use jquery and post your values to another page buy creating a function. In this case your form tag should not have the action attribute or you
should use preventDefault method.
$("#myForm").submit(function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
});
url will be the name of the page to which you want to redirect the user.
The data will be your form. You can use the .serialize() method to get your form data.
var data = $("myForm").serialize();
In success you can define a function on what to do in case of successful result.
Nothing wrong with multiple redirects: this is how traditional web works.
You may get reduce the number of redirects by using AJAX calls though.
Some notes on your pseudo-code:
it is quite useless to echo anything before Location header: noone is supposed to read the message. Not to mention that no output is allowed before headers.
http:// in front of address allowed only in case of fully qualified URI.
so, the code actually have to be
<?php
if(isset($_POST['submit'])){
header("Location: someexample.php");
die();
}
?>
Forms always post to the "action" attribute in it. If you don't want it to post to self, put your form opening tag as <form action="someexample.php" method="post">. The result will be the POST data being sent to someexample.php instead of to the same page as the form.
If you're looking into multiple form options on one page without redirect, take a look into AJAX submits.
The idea would be to send over the form to your receiving file, process the POST data, and return whatever you wanted returned from that process. For example:
$("form").submit( function(event) {
event.preventDefault(); //prevent the file submitting
var formData = $(this).serialize(); //process the form into an array for submission
$.ajax({
url: "receiver.php", //the url of the receiving file
type: "post", //setting method to post
data: formData, //set the data being sent to the form contents
success: function(response) {
$("div").html(response); //set the receiving div to the html you echo'd in the php document
}
});
});
Your receiver.php file can look exactly the same as a normal PHP document receiving POST data, so <?php if(isset($_POST['submit'])) {} ?> will still work exactly as you're expecting, without the page redirects! This solution does require jQuery though.
Edit:
To deal with the questions update of if(criteria) { $abc = 'xyz'; } there are a couple of suggestions.
To keep the asynchronous approach, go with $_SESSION variables. You could set them using the receiver.php and deal with them in the starting document.
To go back to a standard submission method onto the same document, either break your multiple options into radio inputs, checkboxes, or separate forms.
So:
<input type="radio" name="method" value="submit" />
<input type="radio" name="method" value="clear" />
That way you can choose what method to submit there.
Or you can break them into forms:
<form method="post">
<input type="submit" name="submit" value="submit" />
</form>
<form method="post">
<input type="submit" name="clear" value="clear" />
</form>
Finally, you could change the value of a hidden input on click if you wanted to change between submit and clear, so:
The HTML:
<form method="post">
<input type="hidden" id="method" name="method" value="" />
<input type="submit" id="submit" value="submit" name="submit" />
<input type="submit" id="clear" value="clear" name="clear" />
</form>
The jQuery:
$("#submit").click( function(event) {
event.preventDefault();
$("#method").val("clear"); //set the method to clear
$("form").submit(); //submit the form normally
});
$("#clear").click( function(event) {
event.preventDefault();
$("#method").val("submit");
$("form").submit();
});
The PHP:
<?php
if(isset($_POST['submit'])) {
//do something
} elseif(isset($_POST['clear'])) {
//do something else
}

Having Issues with ajax submit reloading, the anonymous function is not executing

I spent quite a bit of time looking for this and maybe I'm not approaching this correctly, but I'm trying to .submit and .post after clicking a submit. In other instances I have been able to get the ajax submit to work properly without the refresh, but when I do it in this manner it just doesn't work. I'm curious to know why.
Form
<form id="search" action="process.php" method="post">
Name: <input id="search_text" type="text" name="name" />
<input type="submit" value="Submit" />
</form>
Ajax
$('#search').submit(function() {
$.post(
$(this).attr('action'),
$(this).serialize(),
function(data){
$('#page_nav').html(data.html_page_nav);
$('#results').html(data.table_html);
},
"json"
);
return false;
});
This works and it will submit without reloading just fine
Below is where I have the problem.
On the php server side I am sending back html that I want to be able to submit, which the initial search will put into the original html page.
$html_page_nav = "
<ul>
";
for($i=1; $i <= get_query_pages(get_query_count($query), 50); $i++) {
$html_page_nav .= "
<li>
<form id='page_".$i."' action='process.php' method='post'>
<input type='hidden' name='action' value='change_page'/>
<input type='hidden' name='page' value='".$i."'/>
<input type='submit' value='".$i."'>
</form>
</li>
";
}
$html_page_nav .= "
</ul>
";
I try to do the same thing as above, but the submit does not work properly
$(document).ready(function() {
$('#page_1').submit(function() {
console.log("this will not display");
$.post(
$(this).attr('action'),
$(this).serialize(),
function(data){
},
"json"
);
return false;
})
...other jquery
});
This submit will not work properly, the function() will not execute and it will submit like the regular submit and go to the url rather then execute without refreshing the entire page.
Any suggestions or approaches would be much appreciated.
Thanks in advance!
Delegate the submit action to execute on content which will be loaded in future. By default the normal event handlers attached to the content loaded on DOM but not the one which will gets loaded in future, say through Ajax. You can use jQuery "on" function to delegate the action on content which will load in future.
eg.
$('body').on('submit', '#page_1', function() {
// do it here
});
I had a similar problem using ajaxForm n all. I jus used $("#Form").validate();
for it and the page doesnt get refresh

ajax post but can't prevent refresh

I have a problem with my page refreshing after ajax posts, I've tried like 6 differing variations and at one point I was getting the proper result but couldn't stop the page from refreshing and after searching the net and around on this site now none of it is working and it's still refreshing...
current code is:
$('#submit_btn').click(function() {
/*event.preventDefault();*/
var curPassword = $("input#curPassword").val();
var newPassword = $("input#newPassword").val();
var new2Password = $("input#new2Password").val();
/*var params = 'curPassword='+ curPassword + '&newPassword=' + newPassword + '&new2Password=' + new2Password; */
var params = {
curPassword: curPassword,
newPassword: newPassword,
new2Password:new2Password
};
$.ajax({
type: "POST",
url: "testAjax.php",
data: params,
success: function(msg){
alert(msg);
}
});
return false;
});
the form is:
<form method="post" action="" name="confirmChange" class="confirmChange">
<label for="curPassword">Current Password:</label>
<input type="password" name="curPassword" id="curPassword" value="" />
<label for="newPassword">New Password:</label>
<input type="password" name="newPassword" id="newPassword" value="" />
<label for="new2Password">Confirm New Password:</label>
<input type="password" name="new2Password" id="new2Password" value="" />
<br />
<input type="button" name="confirmChange" class="confirmChange" id="submit_btn" value="Change" />
Appreciate any help in getting this to work =/
Update:
Took out the other non-directly-related code as it kinda cluttered the question. Also updated code to refelect latest revision.
I changed the ajax url to a simple textAjax.php with a simple echo hello world nothing else, where I'm still getting nothing.
Update 2
Tried changing javascript code to:
$('#submit_btn').click(function() {
alert('Button Clicked');
});
And I'm getting nothing... If that is the form below how is it possible the click function isn't working at all?
You don't need to use the type="submit" for your input. Just use type="button" and call the ajax function on the button's click event.
<input type="button" name="confirmChange" class="confirmChange" id="submit_btn" value="Change">
$('#submit_btn').click(function() {
(ajax code here)
});
preventDefault() would also work, but, in my opinion, why prevent an event from naturally occurring when you can just avoid using the submit button altogether?
Update: I just realised that using the submit would allow users to hit enter to trigger your actions, so perhaps there's also some merit in that. In any case, here's a similar question that contains elaborations into preventDefault().
Update 2: You need to fix your parameters in the ajax function. Use an array instead of trying to build a query string:
var params = {
curPassword: curPassword,
newPassword: newPassword,
new2Password:new2Password
};
Encapsulate your AJAX call within the following code block
$('form.confirmChange').submit(function(event) {
event.preventDefault();
#Rest of your code goes in here
});
preventDefault() will prevent the default action of an event from triggering.
Try this
<script>
function refreshpage(){
(ajax code here)
return false;
}
</script>
<form onsubmit="return refreshpage();">
<input type = "submit" value="submit_btn">
</form>
I think I fixed it by using:
$('#submit_btn').live('click', (function() {
I at least started getting a response when clicking, but I'm not updating or getting any echo's back from the php file but hopefully that'll be easier to debug. :)
I had the same problem. Just like you, I had wrapped my <input> tags inside a <form> tag pair. Even though there was no <submit>, I found that when I clicked my button to trigger the Ajax call, it was refreshing the page - and actually submitting the form to the page.
I ended up removing the <form> tags and this behaviour stopped, but the Ajax still works as expected. I hope this helps anyone else that is experiencing this.
Use a loop to run the ajax call only once.
var i;
for(i=0;i<1;i++){
//ajax code here
}
So, then it will not call again and again..

1 form 2 actions

<form name="ipladder" id="ipladder" action="/checkuser/master-check.php" method="post">
<input name="ipladder" type="text" id="ipladder" />
<input type="submit" name="submit" id="botton" value="Check" />
<input type="submit" name="geo" id="botton"/>
</input></form>
I have one input box and 2 submit buttons. When the first button is pressed (name="submit") I want it to go to master-check.php as specified in the action= parameter. However when the geo button is pressed, I want it to go through a different action which I haven't specified because I didn't know how to do so.
What can I do so I can have 1 input box and 2 buttons each processing through different action files?
Maybe you can try altering the "action" parameter of your form in an onclick method that, after changing, submits the form. Something like:
$('#btn1').click(function(){
$('#ipladder').attr('action', 'location1.php');
$('#ipladder').submit();
});
$('#btn2').click(function(){
$('#ipladder').attr('action', 'location2.php');
$('#ipladder').submit();
});
Another option of couse, is to post to 1 page...and handle the logic (some redirect or whatever) there.
Make a single PHP script that handles which button has been pressed and then redirects to correct PHP handling script (after correcting what Juhana commented of course).
Instead of using form action, I think you can use Ajax to achieve what you want. It will be something like this:
<form name="ipladder" id="ipladder" method="post">
<input type="text" id="ipladder2" name="ipladder2" />
<input type="button" id="button1" name="submit" value="Check" onclick="action1()" />
<input type="button" id="button2" name="geo" value="Something else" onclick="action2()" />
</form>
and in the header you can define 2 Ajax functions:
<script type="text/javascript">
function action1()
{
$.ajax({
type: "POST",
url: "/checkuser/master-check.php",
data: $("ipladder2").val(),
success: //do something,
dataType: //return dataType
});
}
function action2()
{
$.ajax({
type: "POST",
url: //other URL,
data: $("ipladder2").val(),
success: //do something else,
dataType: //return dataType
});
}
</script>
Well you can achieve your goal by single php page as well.
on mastercheck.php something like this can help you.
<?php
if($_POST['submit'])
{
//you code for master-check.php
}
else if(isset($_POST['geo']))
{
//you code for other page goes here
}
?>

Categories