0

I have two PHP variables that I want to pass to javascript using AJAX.

test.php

$Longitude = json_encode($Long);
$Latitude =  json_encode($Lat);

Index.js

$.ajax({
  type: 'POST',
  dataType: "json",
  url:'test.php',
  data:
  success: function(data)
  {
    console.log("testing");
  }
});

I am new to programming. Please guide how to refer these variable names in the ajax call.

0

3 Answers 3

1

Pass in array and encode it.

test.php

$data = ['Longitude ' =>$Long, 'Latitude ' => $Lat ];

echo json_encode($data);

index.js

 $.ajax({
  type: 'POST',
  dataType: "json",
  url:'test.php',
  data:
  success: function(data)
  {
   try {
      data = JSON.parse(data);
    }catch(e) {}
    console.log(data);
  }
});
Sign up to request clarification or add additional context in comments.

1 Comment

I believe syntax is completely correct. Still it keeps giving me a missing } syntax error.
0

Set your php variable into two hidden text box. Like below.

<input type="hidden" name="Longitude" id="Longitude" />
<input type="hidden" name="Latitude" id="Latitude" />

now get that both the field name into javascript. Like below.

var lats = $("#Longitude").val();
var longs = $("#Longitude").val();

Now pass above data into your ajax call. Like below.

$.ajax({
  type: 'POST',
  dataType: "json",
  url:'test.php',
  data:{ lats:lats,longs:longs},
  success: function(data)
  {
    console.log("testing");
  }
});

1 Comment

The user would like to pass those variables into their page via AJAX, not to include those variables directly in the page.
0

You are going to need to echo the variables you want to access in order for javascript to be able to read them.

try something like this in test.php:

$data = ['lat' => $lat, 'lon' => $lon];
echo json_encode($data);

then in index.js in the success function:

console.log(data);

Comments