Not able to retrieve $_POST values through ajax call - php

I am having little problem with ajax. Here is my code what I have done so far:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
getLocation();
});
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
else{
alert("Geolocation is not supported by this browser.");
}
}
function showPosition(position)
{
latitude =position.coords.latitude;
longitude= position.coords.longitude;
$.post({ url: 'test.php',
data : ({lat :latitude,long:longitude}),
success: function(data){
alert('done');
}});
}
What I am trying to do is call the function on document ready and trying to retrieve the value of ajax call on the same file where I did call this script. Whenever I reload the page, I don't get any value of :
print_r($_POST['lat']);
I don't know what is the actual problem,I already checked in console and didn't get any error. Please help.

To get the value you need to print it in success callback
$.post({ url: 'test.php',
data : ({lat :latitude,long:longitude}),
success: function(data){
alert(data);
}
});
and if you put
if (isset($_POST['lat']) {
print_r($_POST['lat']);
}
you will get the value in alert box.
EDIT: You can check in php if the reqest came from Ajax using this:
if ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
if (isset($_POST['lat']) {
print_r($_POST['lat']);
}
exit();
}
if you put this at the begining you will see only that print_r from ajax call.

The value you are printing is not an array. So you have to print it like,
print $_POST['lat'];
(OR)
echo $_POST['lat'];
AND NOT
print_r($_POST['lat']);
If you want to print all post values mean then you can print it as,
print_r($_POST);

I have solved my problem by own. Here what I have done. I made one more file called test2.php and put my php script over there and call that file in my ajax call. Here the code.
Test.php
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
getLocation();
});
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
else{
alert("Geolocation is not supported by this browser.");
}
}
function showPosition(position)
{
latitude =position.coords.latitude;
longitude= position.coords.longitude;
$.ajax({ url: 'test2.php',
data : ({lat :latitude,long:longitude}),
type: 'post',
success: function(data){
if(data=='true'){
window.location = "http://example.com";
}
}
});
}
</script>
Test2.php
//just for example
<?php
echo 'true';
?>
Hope this will help someone in future.

Related

AJAX Load PHP Response

How can I load data from my PHP response via ajax into a panel?
My PHP outputs correctly and I can see a table in the response, but I can;t get it to build the data on my webpage.
Here is my jquery/ajax so far. It passed the value to PHP correctly and PHP builds the table via its echo, but what am I missing for AJAX to display the table?
PHP:
<?php
foreach ($lines as $value) {
echo "<input name='data[]' value='$value'><br/>";
}
?>
JQUERY:
$(function () {
$('#rotator').change(function (e) {
var rotator = $("#rotator").val();
$.ajax({
type: "POST",
url: "tmp/JFM/National/national.php",
data: {
rotator: rotator
},
success: function (result) {
$('#panel').load(result);
}
})
return false;
});
});
The answer to this was two fold.
I was attempting to append to my main div, which apparently can't happen. I created a new empty div and was able to load the results there.
Beyond that, the comments to change .load(results) to .html(results) were needed.
The correct jquery code is below.
$(function () {
$('#rotator').change(function (e) {
var rotator = $("#rotator").val();
$.ajax({
type: "POST",
url: "tmp/JFM/National/national.php",
data: {
rotator: rotator
},
success: function (result) {
console.log(result);
$('#test').html(result);
}
})
return false;
});
});
move your function from:
$.ajax({...,success: function(){...}});
to
$.ajax({..}).done(function(){...});
if it doesn't work, try to add async:false into the ajax object...
$.ajax({...,async:false}).done(function(){...});
Hope it helps... =}

How to call a php function from ajax?

I am familiar of how to get ajax to go to a php page an execute a series of things and then return json data. However is it possible to call a specific function which resides in a given page?
Basically what I want is to reduce the number of files in a project. So I can put a lot of common functions in one page and then just call whatever the function that I want at the moment.
For AJAX request
Include jQuery Library in your web page.
For e.g.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
Call a function on button click
<button type="button" onclick="create()">Click Me</button>
While click on button, call create function in JavaScript.
<script>
function create () {
$.ajax({
url:"test.php", //the page containing php script
type: "post", //request type,
dataType: 'json',
data: {registration: "success", name: "xyz", email: "abc#gmail.com"},
success:function(result){
console.log(result.abc);
}
});
}
</script>
On the server side test.php file, the action POST parameter should be read and the corresponding value and do the action in PHP and return in JSON format e.g.
$registration = $_POST['registration'];
$name= $_POST['name'];
$email= $_POST['email'];
if ($registration == "success"){
// some action goes here under php
echo json_encode(array("abc"=>'successfuly registered'));
}
You cannot call a PHP function directly from an AJAX request, but you can do this instead:
<? php
function test($data){
return $data+1;
}
if (isset($_POST['callFunc1'])) {
echo test($_POST['callFunc1']);
}
?>
<script>
$.ajax({
url: 'myFunctions.php',
type: 'post',
data: { "callFunc1": "1"},
success: function(response) { console.log(response); }
});
</script>
As a structure for this kind of purposes, I suggest this:
PHP
<?php
if(isset($_POST['action'])){
if ($_POST['action'] == "function1") { func1(); }
if ($_POST['action'] == "function2") { func2(); }
if ($_POST['action'] == "function3") { func3(); }
if ($_POST['action'] == "function4") { func4(); }
}
function func1(){
//Do something here
echo 'test';
}
?>
jQuery
var data = { action: 'function1' };
$.post(ajaxUrl, data, function(response) {
if(response != "") {
$('#SomeElement').html(response);
}else{
alert('Error, Please try again.');
}
});
As mentioned, you can't call a PHP function directly from an AJAX call.
If I understand correctly, yes you can.
Put all your functions in one php file and have the ajax pass as a parameter which one you want to call. Then with a switch or if structure, execute the one you want.
jquery:
$(document).ready(function(){
$('#tfa_1117700').change(function(){
var inputValue = $(this).val();
var v_token = "{{csrf_token()}}";
$.post(
"{{url('/each-child')}}",
{ dropdownValue: inputValue,_token:v_token },
function(data){
console.log(data);
$('#each-child-html').html(data);
}
);
});
});
php:
public function EachChild(Request $request)
{
$html ="";
for ($i=1; $i <= $request->dropdownValue; $i++)
{
$html = $i;
}
echo $html;
}

Ajax POST to Cakephp Controller always give array() result

i really struggle to get the POST value in the controller .i am really new to this..Please someone share me some light..being in the dark for long hours now.
i had a checkboxes and need to pass all the ids that had been checked to the controller and use that ids to update my database.i don't know what did i did wrong, tried everything and some examples too like here:
sending data via ajax in Cakephp
found some question about same problem too , but not much helping me( or maybe too dumb to understand) . i keep getting array();
please help me..with my codes or any link i can refer to .here my codes:
my view script :
<script type="text/javascript">
$(document).ready(function(){
$('.checkall:button').toggle(function(){
$('input:checkbox').attr('checked','checked');
$('#button').click( function (event) {
var memoData = [];
$.each($("input[name='memo']:checked"), function(){
memoData.push($(this).val());
});
var value = memoData.join(", ")
//alert("value are: " + value);
//start
$.ajax({
type:"POST",
traditional:true;
data:{value_to_send:data_to_send},
url:"../My/deleteAll/",
success : function(data) {
alert(value);// will alert "ok"
},
error : function() {
alert("false submission fail");
}
});
//end
} ); //end of button click
},function(){//uncheck
$('input:checkbox').removeAttr('checked');
});
});
my controller :
public function deleteAll(){
if( $this->request->is('POST') ) {
// echo $_POST['value_to_send'];
//echo $value = $this->request->data('value_to_send');
//or
debug($this->request->data);exit;
}
}
and result of this debug is:
\app\Controller\MyController.php (line 73)
array()
Please help me.Thank you so much
How about this:
Jquery:
$(document).ready(function() {
$('.checkall:button').toggle(function() {
$('input:checkbox').attr('checked','checked');
$('#button').click(function(event) {
var memoData = [];
$.each($("input[name='memo']:checked"), function(){
memoData.push($(this).val());
});
//start
$.ajax({
type: 'POST',
url: '../My/deleteAll/',
data: {value_to_send: memoData},
success : function(data) {
alert(data);// will alert "ok"
},
error : function() {
alert("false submission fail");
}
});//end ajax
}); //end of button click
},function(){//uncheck
$('input:checkbox').removeAttr('checked');
});
});
In controller:
public function deleteAll()
{
$this->autoRender = false;
if($this->request->is('Ajax')) { //<!-- Ajax Detection
$elements = explode(",", $_POST['value_to_send']);
foreach($elements as $element)
{
//find and delete
}
}
}
You need to set the data type as json in ajax call
JQUERY CODE:
$.ajax({
url: "../My/deleteAll/",
type: "POST",
dataType:'json',
data:{value_to_send:data_to_send},
success: function(data){
}
});

Ajax function issue on return true and false in wordpress

I am validating a form with ajax and jquery in WordPress post comments textarea for regex. But there is an issue when i want to alert a error message with return false. Its working fine with invalid data and showing alert and is not submitting. But when i put valid data then form is not submit. May be issue with return false.
I tried making variable and store true & false and apply condition out the ajax success block but did not work for me.
Its working fine when i do it with core php, ajax, jquery but not working in WordPress .
Here is my ajax, jquery code.
require 'nmp_process.php';
add_action('wp_ajax_nmp_process_ajax', 'nmp_process_func');
add_action('wp_ajax_nopriv_nmp_process_ajax', 'nmp_process_func');
add_action('wp_head', 'no_markup');
function no_markup() {
?>
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery('form').submit(function (e) {
var comment = jQuery('#comment').val();
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: 'action=nmp_process_ajax&comment=' + comment,
success: function (res) {
count = res;
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
return false;
}
}
});
return false;
});
});
</script>
<?php
}
And i'm using wordpress wp_ajax hook.
And here is my php code.
<?php
function nmp_process_func (){
$comment = $_REQUEST['comment'];
preg_match_all("/(->|;|=|<|>|{|})/", $comment, $matches, PREG_SET_ORDER);
$count = 0;
foreach ($matches as $val) {
$count++;
}
echo $count;
wp_die();
}
?>
Thanks in advance.
Finally, I just figured it out by myself.
Just put async: false in ajax call. And now it is working fine. Plus create an empty variable and store Boolean values in it and then after ajax call return that variable.
Here is my previous code:
require 'nmp_process.php';
add_action('wp_ajax_nmp_process_ajax', 'nmp_process_func');
add_action('wp_ajax_nopriv_nmp_process_ajax', 'nmp_process_func');
add_action('wp_head', 'no_markup');
function no_markup() {
?>
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery('form').submit(function (e) {
var comment = jQuery('#comment').val();
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: 'action=nmp_process_ajax&comment=' + comment,
success: function (res) {
count = res;
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
return false;
}
}
});
return false;
});
});
</script>
<?php
}
And the issue that i resolved is,
New code
var returnval = false;
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
async: false, // Add this
data: 'action=nmp_process_ajax&comment=' + comment,
Why i use it
Async:False will hold the execution of rest code. Once you get response of ajax, only then, rest of the code will execute.
And Then simply store Boolean in variable like this ,
success: function (res) {
count = res;
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
returnval = false;
} else {
returnval = true;
}
}
});
// Prevent Default Submission Form
return returnval; });
That's it.
Thanks for the answers by the way.
Try doing a ajax call with a click event and if the fields are valid you submit the form:
jQuery(document).ready(function () {
jQuery("input[type=submit]").click(function (e) {
var form = $(this).closest('form');
e.preventDefault();
var comment = jQuery('#comment').val();
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: {'action':'nmp_process_ajax','comment':comment},
success: function (res) {
var count = parseInt(res);
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
} else {
form.submit();
}
}
});
});
});
note : you call need to call that function in php and return only the count!
Instead of submitting the form bind the submit button to a click event.
jQuery("input[type=submit]").on("click",function(){
//ajax call here
var comment = jQuery('#comment').val();
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: 'action=nmp_process_ajax&comment=' + comment,
success: function (res) {
count = res;
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
return false;
}else{
jQuery("form").submit();
}
}
});
return false;
})
Plus also its a good idea to put return type to you ajax request.
Let me know if this works.

Simple success/error return with ajax and php

Just starting to learn about ajax although I am running into trouble trying to return a success message in an array.
<script type="text/javascript">
$(function () {
$('#delete').on('click', function () {
var $form = $(this).closest('form');
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize()
}).done(function (response) {
if (response.success) {
alert('Saved!');
} else {
alert('Some error occurred.');
}
});
});
});
</script>
<?php
$array = array();
$array['success'] = TRUE;
echo $array;
?>
response.success should refer to $array['success'] correct?
You are trying to echo your array, which will just spit out "Array".
Instead you need to encode your array as JSON and echo that out.
Change this:
echo $array;
To this:
echo json_encode($array);
Also you probably need to add your dataType in your ajax params so jQuery auto-parses the response:
dataType : 'json' // stick this after "data: $form.serialize()" for example
Also, here's a good post to read on how to properly handle success/errors with your ajax calls (thanks #Shawn):
Jquery checking success of ajax post

Categories