Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to POST value to PHP in the same page using jQuery

Tags:

jquery

php

I don't know if I'm just dumb. I have been trying to figure this out for the past 1hour. Please help!!

     <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="jquery.js" type="text/javascript"></script>
</head>

<body>
<div id="box" ></div>
<div id="box2"></div>

<script type="text/javascript">
  $(function(){
  $('#box').html("Test");

    //$('#box').attr('name','Indy');
    //var a= $('#box').attr('name');
    $.post(window.location, {name: 'John'});


});

</script>
</body>
</html>
<?php
print_r($_POST);
?>

How do I pass the value? I know this works if the php is in a different file. But this is not the case here.

like image 337
Indy Avatar asked Nov 22 '11 01:11

Indy


1 Answers

You won't be seeing the request's results because $.post() and all the AJAX functions run in the background, which doesn't refresh the page.

As for posting to the current page, just use the window's location:

$.post(window.location, {name: 'John'}, function(data) {
  alert('POST was successful. Server says: ' + data);
});
like image 124
Blender Avatar answered Oct 03 '22 06:10

Blender