Home > Software design >  Ajax POST can't read from PHP
Ajax POST can't read from PHP

Time:01-17

Im writing a javascript and wanted to send the data to PHP page addProject-logic.php through ajax POST.

Although the POST request success on the javascript, but on my php page i couldnt echo, it showed undefined "latLng"

My file structure: Structure

addMap.js :

google.maps.event.addListener(marker, 'dragend', function (marker) {
  var latLng = marker.latLng
  currentLatitude = latLng.lat()
  currentLongitude = latLng.lng()
  var latlng = {
    lat: currentLatitude,
    lng: currentLongitude,
  }

  //Post LAT LNG TO POST
  function postLatLng() {
    $.ajax({
      type: 'POST',
      url: '../includes/actions/addProject-logic.php',
      data: {
        latLng: latlng,
      },
      success: function (response) {
        window.alert('Success')
      },
    })
  }

  var geocoder = new google.maps.Geocoder()
  geocoder.geocode(
    {
      location: latlng,
    },
    function (results, status) {
      if (status === 'OK') {
        if (results[0]) {
          input.value = results[0].formatted_address
          map.setZoom(18)
          map.panTo(latLng)
          postLatLng()
        } else {
          window.alert('No results found')
        }
      } else {
        window.alert('Geocoder failed due to: '   status)
      }
    },
  )
})

i create a function postLatLng then execute in another action

Whenever I echo on php addProject-logic.php page, echo $_POST['latLng']; it showed undefined array key latLng

CodePudding user response:

Your example is a bit vague as you don't show what addProject-logic.php file does but here's a fresh example with a javascript call and a php code.

I'm simplifying by using javascript (you can convert to jQuery) and removing geocode as it seems it is not the issue here (but then, your example is vague).

I'm using fetch to make the requests in order to show the different steps. Notice the JSON.stringify call.

// Data is 
var latlng = {
    lat: 42,
    lng: 42
}

function postLatLng() {
    fetch('addProject-logic.php', {
        method: 'POST',
        body: JSON.stringify({
            latLng: latlng
        })
    })
    // the response sent back via php is json
    .then(response => response.json())
    .then(json => {
        // The data returned by the php script contains latLng
        window.alert(json.latLng)
    })
    .catch(err => {
        console.error(err)
    })
}

On the php side:

<?php
// Header for the JSON response
header('Content-Type: application/json; charset=UTF-8');

// parsing the post content
// My guess is you miss both this call and the JSON.stringify in the js
$data = json_decode(file_get_contents('php://input'), true);

// here we send back the post data.
echo json_encode([
    'latLng' => $data["latLng"],
]);
  • Related