2

I built a single point entry controller in PHP (all routing through index.php). It works great but im having an issue with setting $_POST variable with an ajax call.

i'm guessing because the url of the ajax call is /submit and not /index.php

$url_page is the page name from the browser url. this is handeld in a function that im leaving out of this example

switch($url_page)
{
case '':
  echo 'When login works this will redirect you to to correct page';
break;

case 'admin':
    $template_page->set_values('URL', URL);
    $template_page->set_values('PATH', PATH);
    $template_page->set_values('NAVIGATION', '');
    $template_page->set_values('SIDENAVIGATION', '');
    $template_page->pageContet('admin.html');
    echo $template_page->build_template();
break;      

case 'student':
    $template_page->set_values('URL', URL);
    $template_page->set_values('PATH', PATH);
    $template_page->set_values('INCJS', URL.'/assets/js/studentjs.js');
    $template_page->set_values('NAVIGATION', file_get_contents(TEMPLATES.'/studentNav.html'));
    $template_page->set_values('SIDENAVIGATION', file_get_contents(TEMPLATES.'/userSideNav.html'));
    $template_page->pageContet('students.html');
        echo $template_page->build_template();
break;

case 'submit':

 cannot access $_POST here

break;

default:
    header('Location:'.URL.'/404.html') ;      
    break;
}

And here is the Ajax

$('.navicagtionClass > li > a').click(function() { 
var page = $(this).attr('value');
var obj = {};
obj['page'] = page;

$.ajax({
        url: "/submit",
        type: "POST",
        data: obj,
        dataType: "json",
        success: function(data) {
            console.log(data);
          document.getElementById('PageContent').innerHTML = data.a;
        },
        error: function(xhr, status, err) {
          console.log(err);
        }
  });

});

Jay P
  • 596
  • 7
  • 23
  • Try `print_r(json_decode(file_get_contents('php://input'), 1));`. Probably javascript send it into PHP input stream. – stepozer Jun 14 '15 at 15:09

1 Answers1

0

If I correctly understand your approach, you cannot use the page you are on as the AJAX processor file. You need a separate PHP file to process the AJAX and return it back to index.php.

In the source referenced below, note especially the example prefixed "Try this and you'll see what I mean" -- give it a try.

Source:

values not updated after an ajax response

Community
  • 1
  • 1
cssyphus
  • 37,875
  • 18
  • 96
  • 111