Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax PHP Jquery - echo-ing back data

I'm having trouble bringing back data from my PHP file. I guess I don't really understand the data parameter of this jquery function so I just went off some tutorials.

Jquery

$.ajax(
    {
        url: 'test.php',
        dataType: 'text',
        data: {test: '1'},
        success: function(data)
        {
            window.alert(data);
        }
    })

Now from my understanding the test: declares the variable used in php and 1 is the value in that variable. But I'm not entirely sure...

Here's my PHP

$item1 = $_POST['test'];

    echo $item1;

Now it's just supposed to alert that value so I know it is at least returning something but in the alert it's just blank so I'm losing the value somewhere, but where?

like image 669
Howdy_McGee Avatar asked Nov 25 '11 06:11

Howdy_McGee


3 Answers

use $_REQUEST it will handle both the GET and POST

$item1 = $_REQUEST['test'];

by default ajax request is GET type, either specify expilicitly the type like

$.ajax(
    {
        url: 'test.php',
        type:'POST'
        dataType: 'text',
        data: {test: '1'},
        success: function(data)
        {
            window.alert(data);
        }
    })

or use $_GET like

item1 = $_GET['test'];

    echo $item1;
like image 79
Rafay Avatar answered Nov 04 '22 12:11

Rafay


The correct way:

<?php
$change = array('key1' => 'blabla', 'key2' => '12432rr424234');
echo json_encode($change);
?>

Then the jquery script:

<script>
$.get("location.php", function(data){
  var mydata= $.parseJSON(data);
  var art1 = mydata.key1;  // <-----------  access the element
});
</script>
like image 5
T.Todua Avatar answered Nov 04 '22 11:11

T.Todua


This is work for me

ajax code

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
        <title>Test Page</title>
        <script>
            $.ajax(
                    {
                        url: 'test.php',
                        type: 'POST',
                        dataType: 'text',
                        data: {latitude: '7.15588546', longitude: '81.5659984458'},
                        success: function (response)
                        {
                            alert(response);
                        }
                    });
        </script>
    </head>
    <body>
    </body>
</html>

php code (test.php)

<?php

$lat = $_REQUEST['latitude'];
$lon = $_REQUEST['longitude'];

echo 'latitude- '.$lat . ', longitude- ' . $lon;
?>
like image 1
Dinesh Avatar answered Nov 04 '22 11:11

Dinesh