Reputation: 1
Solution: No need to look for the PHP variables, just prevent default submission and use the Javascript variable in the API call..
I am attempting to use this workaround to wait for form submission before executing API call. However, the first ajax push is not resulting in the $_POST variable receiving the data. Network analysis shows that the variable is being sent. First question on here, so apologies in advance.
$("#form").submit(function(evt) {
evt.preventDefault();
var inputAddress = $(this).find("input[type='text']").val();
// Ajax form Submit
$.ajax ({
url:'index.php',
method: 'POST',
data:{inputAddress:inputAddress},
success: function() {
var add = '<?php echo ($_POST['inputAddress'])?>'; // BLANK?
// API call
var apiResult = $.ajax ({
url: 'https://maps.googleapis.com/maps/api/geocode/json?address='+add+'&key=AIzaSyDcNLmq6E6K-bDefI-28E1qiqugS_-wnhI',
method: 'get',
success: function(data) {
window.console.log(data);
}
})
}
})
})
})
Upvotes: 0
Views: 108
Reputation: 1179
It seems like already have that variable on javascript, so there's no need to get it from $_POST. Try using this way and see if it works:
$("#form").submit(function(evt) {
evt.preventDefault();
var inputAddress = $(this).find("input[type='text']").val();
// Ajax form Submit
$.ajax ({
url:'index.php',
method: 'POST',
data:{inputAddress:inputAddress},
success: function() {
// API call
var apiResult = $.ajax ({
url: 'https://maps.googleapis.com/maps/api/geocode/json?address='+inputAddress+'&key=AIzaSyDcNLmq6E6K-bDefI-28E1qiqugS_-wnhI',
method: 'get',
success: function(data) {
window.console.log(data);
}
})
}
})
})
})
EDIT: Also the first request is unnecessary, so you can remove it:
$("#form").submit(function(evt) {
evt.preventDefault();
var inputAddress = $(this).find("input[type='text']").val();
// API call
var apiResult = $.ajax ({
url: 'https://maps.googleapis.com/maps/api/geocode/json?address='+inputAddress+'&key=AIzaSyDcNLmq6E6K-bDefI-28E1qiqugS_-wnhI',
method: 'get',
success: function(data) {
window.console.log(data);
}
})
})
Upvotes: 1
Reputation: 59
I found a problem in your code. The page containing the above code is a PHP script, I think.
So, the Apache(PHP server) processes <?php echo ($_POST['inputAddress'])?>
and prints Empty value into it.
$("#form").submit(function(evt) {
evt.preventDefault();
var inputAddress = $(this).find("input[type='text']").val();
// Ajax form Submit
$.ajax ({
url:'index.php',
method: 'POST',
data:{inputAddress:inputAddress},
success: function() {
var add = ''; // PHP leaves it Empty...
// API call
var apiResult = $.ajax ({
url: 'https://maps.googleapis.com/maps/api/geocode/json?address='+add+'&key=AIzaSyDcNLmq6E6K-bDefI-28E1qiqugS_-wnhI',
method: 'get',
success: function(data) {
window.console.log(data);
}
})
}
})
})
})
Upvotes: 0