March 16, 2012

Retrieve PHP Variables with ajax load function

Question by mistertodd

I have an index.php with this code

<div id="example" class="functions"></div> 
<script type="text/javascript">
var ajax_load = "<img class='loading' src='ajax-loader.gif' alt='loading...' />";
var loadUrl = "checks/example.php";
$("#example").load(loadUrl);
</script>

and in the checks/example.php file

$masterurl = $_POST['domain'];
echo $masterurl;

First Problem: the example.php can´t retrieve the $_POST Request, because ajax is outputting it like html. I have looked for JSON solutions – but not found anything for my problem.

Second Problem: if the index.php outputs the value from example.php, how can I take the value and from the and handle the value as another php variable? like

$value = [value from <div id="example"></div>]

UPDATE: First Problem resolved

<div id="example" class="functions"></div> 
<script type="text/javascript">
var ajax_load = "<img class='loading' src='ajax-loader.gif' alt='loading...' />";
var loadUrl = "checks/example.php?domain=http://www.example.com";
$("#example").load(loadUrl);
</script>


$masterurl = $_GET['domain'];
echo $masterurl;

but how can I take the value $masterurl in the index.php for a variable on the index.php?

UPDATE 2:
checks/example.php sends the following value = 35234 this value will be displayed in this div

<div id="example">35234</div>

how can I use this value on the same page for

<?php
$newvalue = "35234" // value from div id example
?>

Answer by Starx

That is an incorrect way to do make an request. .load() will only update the div with the returned value from the path, but does not help to send any data to the target.

Make a valid post, or get, to request the page and update the <div> with the returned code

$.post("checks/example.php", {
   varname : 'val', //send the data to the page using this format
   varname2 : 'value2'
}, function(data) {
   // data will hold the output from the example.php

   $("#example").html(data); //update the div with the output
});

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!