Wordpress Plugin Ajax get Javascript Array Data into PHP Variable - php

function my_action_javascript($val1, $val2) {
?>
<script type="text/javascript" >
jQuery(document).ready(function($) {
var data = {
'email': '<?php echo $val1?>',
'password': '<?php echo $val2?>'
};
jQuery.post({
url: 'dummyurl',
method: "POST",
data: data,
success: function (data) {
console.log(data);
}
})
});
</script>
<?php
}
I got this function in my Wordpress Plugin. I parse in some data in the function and then i do a ajax request in Javascript. That all works just fine and i get the data array as response.
The Question is, how do i get the data from the Array in Javascript into my Variable in PHP so i can put the Data into my Wordpress Options?

Try this.
you need to parse the response.
function my_action_javascript($val1, $val2) {
?>
<script type="text/javascript" >
jQuery(document).ready(function($) {
var data = {
'email': '<?php echo $val1?>',
'password': '<?php echo $val2?>'
};
jQuery.post({
url: 'dummyurl',
method: "POST",
data: data,
success: function (data) {
console.log(data);
var obj = jQuery.parseJSON( data);
console.log(obj.somedata);
}
})
});
</script>
<?php
}

You need to have a PHP script that gets called by the AJAX request that will write the data into your options table. There's a specific way of doing this with Wordpress: https://codex.wordpress.org/AJAX_in_Plugins
In a nutshell, you need to add an action parameter to your POST data and then hook your PHP callback function to this parameter. In your callback, you can then use update_option().

Related

Calling a PHP function from same PHP file throught AJAX

I am trying to call php function through Ajax in same php file.
User enter voucher_id then call ajax that ajax call php function that function is in same file.
How to call that function.
function of PHP code:-
function voucherExist($voucherNo, $sCID, $type){
global $pncon;
$uRow = $pncon->query("SELECT * FROM transactions WHERE voucher_no = '{$voucherNo}' AND company_ID = '{$sCID}' AND type = '{$type}'");
return $uRow;
}
Ajax code:-
<script type="text/javascript">
$(document).ready(function (){
$('#voucher_no').on('change', function () {
var voucher_no = $('#voucher_no').val();
$.ajax({
url: "bankVoucherAddEdit.php",
type: "post",
data: "voucherNo"
});
});
});
</script>
You can get an idea from the below:
<? php
function yourFunction($data){
return $data;
}
if (isset($_POST['voucherNo'])) {
echo yourFunction($_POST['voucherNo']);
}
?>
<script>
$.ajax({
url: 'bankVoucherAddEdit.php',
type: 'post',
data: { "voucherNo": voucher_no },
success: function(response) { console.log(response); }
});
</script>
The thing is that you cannot directly call a PHP function from JS. You can achieve this by RESTful API. They are quite simpler and Standard.
In your case, Send any post value as a flag from JS to PHP, if that POST value exists then call PHP function

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... =}

Execute php using jquery post

I've tried to go to php file using jquery.
Here is my code.
This is index.php
$.post('test.php',data,function(json){},'json');
This is test.php
//set session variable from passed data
$_SESSION['data1'] = $_POST['data1'];
<script>
window.open('test1.php','_blank');
</script>
This is test1.php
echo $_SESSION['data1'];
But this code is not working.
I want to pass data from index.php to test1.php.
How can I do this? I don't want to use GET method because of too long url.
Anyhelp would be appreciate.
I am not quite clear from you explanation right now. But I am here trying to resolve you problem as you can use the jquery post method as follows :
$.post('test1.php',{param1:value1,param2=value2,...},function(data){
//Here you can take action as per data return from the page or can add simple action like redirecting or other
});
Here is a simple example of register :
$.post('', $("#register_form").serialize(), function(data) {
if (data === '1') {
bootbox.alert("You have registered successfully.", function() {
document.location.href = base_url + '';
});
} else if (data === '0') {
bootbox.alert("Error submitting records");
} else {
bootbox.alert(data);
}
$("#user_register_button").button("reset");
});
Try this:
$.ajax({
url: 'test.php',
type: 'POST',
data: {
myData : 'somevalue'
},
success: function(response){ // response from test.php
// do your stuff here
}
});
test.php
$myData = $_REQUEST['myData'];
// do your stuff here
I like use jQuery post a url like this.
$('form').on('submit', function(e) {
e.preventDefault();
var $this = $(this);
$.ajax({
url: $this.attr('action'),
method: $this.attr('method'),
data: $this.serializeArray(),
success: function(response) {
console.log(response);
}
})
});
I you a beginner, you can reference this project
php-and-jQuery-messageBoard

Error Ajax request

When I perform a simple ajax request I get the following error
TypeError: 'toString' called on an object that does not implement interface HTMLAnchorElement.
This is my ajax script
<script type="text/javascript">
$(document).on("ready", function(){
$("#tabla_persona table tr").click(function() {
var cod = $( "#identificador",this);
alert(cod.html());
var parametros={
"cod":cod
};
$.ajax({
type: 'POST',
url: '<?php echo site_url("archivo/prueba"); ?>',
data: parametros,
success: function(resp) {
$("#tabla_usuario_individual").html(resp);
}
});
});
});
</script>
This is my controller
public function prueba(){
$this->load->view('datos_persona');
}
and my simple page to see the result
<a>
Prueba
</a>
Try changing:
var parametros={
"cod":cod
};
to:
var parametros={
"cod":cod.html()
};
Just need simple change.I think the following code will work.
public function prueba(){
echo $this->load->view('datos_persona',true);
}

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