Viewed   69 times

I have an HTML document, which loads content from a PHP file using an AJAX call. The important bit of my code is below:

default.html :

/*more code above*/
var PHP_URL = "content.php";
var Content = document.getElementById('Content');
ajaxRequest = new XMLHttpRequest();
ajaxRequest.onreadystatechange =
    function() {
        if(ajaxRequest.readyState==4) {
            if (ajaxRequest.status==200)
                Content.innerHTML = ajaxRequest.responseText;
            else
                Content.innerHTML = "Error:<br/>unable to load page at <b>"+PHP_URL+"</b>";
            Content.className = "Content Solid";
        }
    }
ajaxRequest.open("GET",PHP_URL,true);
ajaxRequest.send();
/*more code below*/

Is it possible for the file at 'content.php' to detect that it has been called from 'default.html', or a different calling document as necessary?

 Answers

4

Most well-known Ajax frameworks like jQuery and mooTools add a specific header which you can check with PHP:

if (strcasecmp('XMLHttpRequest', $_SERVER['HTTP_X_REQUESTED_WITH']) === 0)
{
    // Ajax Request
}
Saturday, November 26, 2022
 
dramzy
 
2

I think problem with your code is in the line where you set data: '{....}'.
It should be in json format in order to be passed properly (though it also could be in string format but you'll need to parse it on the server side)

The code below should be working right:

$.ajax({
    type: "post",
    url: BaseUrl + "User/Login",
    data: {"apiKey":"c7089786-7e3a-462c-a620-d85031f0c826","appIDGiven":"200","userName":"matt2","password":"pass"},
    success: function(data){
        console.log(data);
    },
    error: function(request){
        console.log(request);
    }
});

On the server side try: $_POST['apiKey'] $_POST['appIDGiven'] and so on.

Saturday, September 17, 2022
3

What to do is in your master template for your cake app create a global javascript variable that can be used throughout your application. Make sure it exists befor you do any JS includes too.

<head>
    ...
    <script type="text/javascript">var myBaseUrl = '<?php echo $html->url; ?>';</script>
    ...
    <script type="text/javascript" src="mycustomJSfile.js">
    ...
</head>

Now you can do things like this from any view file you have in your MVC framework app.

$.post({url: myBaseUrl + 'controller/action'});
Saturday, August 13, 2022
 
4

Simple jQuery example:

var session;
$.ajaxSetup({cache: false})
$.get('getsession.php', function (data) {
    session = data;
});

And getsession.php:

<?php
session_start();
print json_encode($_SESSION);

You're not required to use jQuery for AJAX, but I highly recommend it.

Edit:

In response to:

I want to be able to tell my JS function what variable I want to get.

You can try this (untested):

var session;
$.ajaxSetup({cache: false})
$.get('getsession.php', {requested: 'foo'}, function (data) {
    session = data;
});

And the PHP:

<?php
session_start();
if (isset($_GET['requested'])) {
    // return requested value
    print $_SESSION[$_GET['requested']];
} else {
    // nothing requested, so return all values
    print json_encode($_SESSION);
}

Have a look at the $.get documentation for a more detailed overview.

Wednesday, October 26, 2022
2

For an easy way you can Make following changes to your code:

HTML:

<form action='' method='' id="myform">
Name:<input type='text' name='name' id='name'>
Age:<input type='text' name='age' id='age'>
message:<textarea name='message' id='message'></textarea>
<input type='submit' value='Send'>
</form>

PHP:

(your_page_with_php_script)

<?php
if(isset($_POST['name']) && isset($_POST['age']) && isset($_POST['message'])){

$a = $_POST['name'];
$b = $_POST['age'];
$c = $_POST['message'];

   if($a != NULL && $b != NULL && $c != NULL)
   {
      echo "Success ".a." ".b." ".c;
   }


};
?>

Script: (Include jquery first)

$('#myform').submit(function(){

var name = $('#name').val();
var age = $('#age').val();
var message = $('#message').val();


$.ajax({
  type: "POST",
  url: "your_page_with_php_script.php",
  data: "name="+name+"&age="+age+"&message="+message,
}).done(function( msg ) {
  alert( "Data Saved: " + msg );
});

});
Friday, November 25, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :