tags:

views:

36

answers:

2

This question may seem completely stupid, but say i have a PHP page with some form processing at the top in php and a html form underneath with the action of submitting to same page and method of post. How do i get the result via ajax, ie. send form to self without refreshing the page, if that makes sense? Thanks

+1  A: 

In your page, check if the page has POST parameters. If it does, process them and return a confirmation. If it doesn't, display the form.

Andreas Jansson
hmmm, maybe i didnt explain right, if i have the form and the user presses submit, then i want the form to be processed by the php without the page refreshing. But what i'm saying is the form is submitting to itself (ie. the same page)
benhowdle89
yes, just do an ajax request onsubmit with the contents of the form ( .val() of your input fields) and return false.
Andreas Jansson
ok got it, thanks
benhowdle89
A: 

It sounds like you're asking about Ajax basics, right? I suggest using jQuery to handle the Ajax part.

Put jQuery in your page, and then do something like

$(document).ready(function(){
  $('#submit_button').click(function(){
    var something='value to send to PHP';
    $.post('name_of_page.php',{"a_var":something},function(data){ /* do something with the data you received back*/ },'json');
    });
  });

Then in your PHP page, set up to handle a post or normal HTML output.

<?php
if($_POST['a_var']){
  $result=do_something($_POST['a_var']);
  echo json_encode($result);
  exit;
  }
//if there was no POST value, it continues to here
<html>
This is the rest of your page.
You'd have the form and the above javascript and so on here.
</html>
Cole