Get data from php script using Ajax - php

I am trying to use some data calculated with a php script in javascript, this is my code :
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
<button onclick="duplicate()"> button send</button>
<script>
function duplicate()
{
var action = "CreationBoard";
alert(action);
$.ajax({
type : "POST",
url : "file.php",
data : { action : action },
success: function(output) {
alert(output);
}
});
}
</script>
</body>
</html>
So I'm calling file.php to calculate my data :
<?php
if(isset($_POST['action']))
{
$return = some_function($_POST['action']);
}
?>
I need to use $return in javascript, how to do that ?? I've seen many examples, but they only show how to send data with Ajax to php, not from php to ajax.
How should I do that ??

All you need to do
<?php
if(isset($_POST['action']))
{
$return = some_function($_POST['action']);
echo $ return
}
?>
Javascript doesn't know php variable. All it know is the data returned

In your file.php I would do
echo json_encode($return);
And then modify your ajax to expect a json return:
function duplicate()
{
var action = "CreationBoard";
alert(action);
$.ajax({
type : "POST",
url : "file.php",
data : { action : action },
dataType: 'json',
success: function(output) {
alert(output);
}
});
}
the output variable that you have in your alert should look like your array and you can do with that what you want.

Related

Wordpress Plugin Ajax get Javascript Array Data into PHP Variable

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().

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;
}

How to send json to php via ajax?

I have a form that collect user info. I encode those info into JSON and send to php to be sent to mysql db via AJAX. Below is the script I placed before </body>.
The problem now is, the result is not being alerted as it supposed to be. SO I believe ajax request was not made properly? Can anyone help on this please?Thanks.
<script>
$(document).ready(function() {
$("#submit").click(function() {
var param2 = <?php echo $param = json_encode($_POST); ?>;
if (param2 && typeof param2 !== 'undefined')
{
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: param2,
cache: false,
success: function(result) {
alert(result);
}
});
}
});
});
</script>
ajaxsubmit.php
<?php
$phpArray = json_decode($param2);
print_r($phpArray);
?>
You'll need to add quotes surrounding your JSON string.
var param2 = '<?php echo $param = json_encode($_POST); ?>';
As far as I am able to understand, you are doing it all wrong.
Suppose you have a form which id is "someForm"
Then
$(document).ready(function () {
$("#submit").click(function () {
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: $('#someForm').serialize(),
cache: false,
success: function (result) {
alert(result);
}
});
}
});
});
In PHP, you will have something like this
$str = "first=myName&arr[]=foo+bar&arr[]=baz";
to decode
parse_str($str, $output);
echo $output['first']; // myName
For JSON Output
echo json_encode($output);
If you are returning JSON as a ajax response then firstly you have define the data type of the response in AJAX.
try it.
<script>
$(document).ready(function(){
$("#submit").click(function(){
var param2 = <?php echo $param = json_encode($_POST); ?>
if( param2 && typeof param2 !== 'undefined' )
{
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: dataString,
cache: false,
dataType: "json",
success: function(result){
alert(result);
}
});}
});
});
</script>
It's just really simple!
$(document).ready(function () {
var jsonData = {
"data" : {"name" : "Randika",
"age" : 26,
"gender" : "male"
}
};
$("#getButton").on('click',function(){
console.log("Retrieve JSON");
$.ajax({
url : "http://your/API/Endpoint/URL",
type: "POST",
datatype: 'json',
data: jsonData,
success: function(data) {
console.log(data); // any response returned from the server.
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="submit" value="POST JSON" id="getButton">
For your further readings and reference please follow the links bellow:
Link 1 - jQuery official doc
Link 2 - Various types of POSTs and AJAX uses.
In my example, code snippet PHP server side should be something like as follows:
<?php
$data = $_POST["data"];
echo json_encode($data); // To print JSON Data in PHP, sent from client side we need to **json_encode()** it.
// When we are going to use the JSON sent from client side as PHP Variables (arrays and integers, and strings) we need to **json_decode()** it
if($data != null) {
$data = json_decode($data);
$name = $data["name"];
$age = $data["age"];
$gender = $data["gender"];
// here you can use the JSON Data sent from the client side, name, age and gender.
}
?>
Again a code snippet more related to your question.
// May be your following line is what doing the wrong thing
var param2 = <?php echo $param = json_encode($_POST); ?>
// so let's see if param2 have the reall json encoded data which you expected by printing it into the console and also as a comment via PHP.
console.log("param2 "+param2);
<?php echo "// ".$param; ?>
After some research on the google , I found the answer which alerts the result in JSON!
Thanks for everyone for your time and effort!
<script>
$("document").ready(function(){
$(".form").submit(function(){
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "response.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
$(".the-return").html(
"<br />JSON: " + data["json"]
);
alert("Form submitted successfully.\nReturned json: " + data["json"]);
}
});
return false;
});
});
</script>
response.php
<?php
if (is_ajax()) {
if (isset($_POST["action"]) && !empty($_POST["action"])) { //Checks if action value exists
$action = $_POST["action"];
switch($action) { //Switch case for value of action
case "test": test_function(); break;
}
}
}
//Function to check if the request is an AJAX request
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
function test_function(){
$return = $_POST;
echo json_encode($return);
}
?>
Here's the reference link : http://labs.jonsuh.com/jquery-ajax-php-json/

How to get the return value of a php function when calling from jQuery?

I have a php function return a string value which will put into html file.
function getDirectionInfo($routeNumber) {
//some code here
$dirinfo = "<p> some text </p>";
return $dirinfo;
}
if (isset($_POST['getDirectionInfo'])) {
getDirectionInfo($_POST['getDirectionInfo']);
}
So in jQuery, I have a following function
$(".onebtn").click(function(){
$("#directioninfo").empty();
var routeNumber = $(this).text();
$.ajax({
url: "./systemView_Function.php",
type: "POST",
data: {"getDirectionInfo": routeNumber},
success: function(data) {
console.log("HIHIHIHI");
$("#directioninfo").append(data);
}
});
})
Now console.log prints the "HIHIHIHIHI", but jQuery does not append the data to html. Anyone know how to get the return value of php function when calling from jQuery?
Instead of return use:
echo json_encode($dirinfo);
die;
It's also good idea to add dataType field to your $.ajax() function params set to json, to make sure, that data in your success function will be properly parsed.
You just need to send the response back using echo
Use var routeNumber = $(this).val(); to get the button value
PHP:
<?php
function getDirectionInfo($routeNumber) {
//some code here
$dirinfo = "<p> routeNumber". $routeNumber." </p>";
return $dirinfo;
}
if (isset($_POST['getDirectionInfo'])) {
echo getDirectionInfo($_POST['getDirectionInfo']);
}else{
echo "not set";
}
AJAX & HTML
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
$(".onebtn").click(function(){
$("#directioninfo").empty();
var routeNumber = $(this).val();
console.log("routeNumber = " + routeNumber);
$.ajax({
url: "systemView_Function.php",
type: "POST",
data: {"getDirectionInfo": routeNumber},
success: function(data) {
console.log("data = " + data);
$("#directioninfo").append(data);
}
});
})
});
</script>
</head>
<body>
<div id="directioninfo"></div>
<input type="button" value="12346" class="onebtn" />
</body>
</html>
Thank you for everyone. I have just found that I made a very stupid mistake in jQuery. I should use var routeNumber = parseInt($(this).text()); instead of var routeNumber = $(this).text(); So the following code work to get the return value of php function when calling from jQuery.
in php
function getDirectionInfo($routeNumber) {
//some code here
$dirinfo = "<p> some text </p>";
echo json_encode($dirinfo);
}
if (isset($_POST['getDirectionInfo'])) {
getDirectionInfo($_POST['getDirectionInfo']);
}
in jQuery
$(".onebtn").click(function(){
$("#directioninfo").empty();
var routeNumber = parseInt($(this).text());
$.ajax({
url: "./systemView_Function.php",
type: "POST",
data: {"getDirectionInfo": routeNumber},
dataType: "JSON",
success: function(data) {
$("#directioninfo").append(data);
}
});
})

Where to put 2nd jQuery.ajax function and isset() checking of the POST variable?

This is a page using a single jQuery.ajax posting to the same page and is working fine.
<?php
if (!isset($_POST['varA'])) {
?>
<html>
<head>
<script type="text/javascript">
$(document).ready(bingo);
function bingo()
{
jQuery.ajax({
type: "POST",
data: {varA: "123"},
success: function(data)
{
$("#test").html(data);
}
});
}
</script>
</head>
<body>
<span id="test"></span>
</body>
</html>
<?php
}
else
{
print_r($_POST['varA']);
}
?>
Situation: I have another variable that I wish to set using another separate jQuery.ajax. However, my page content duplicated itself when I put them altogether like this.
Bad Example (depicting what I'm trying to do)
<?php
if (!isset($_POST['varA'])) {
?>
<html>
<head>
<script type="text/javascript">
$(document).ready(bingo);
function bingo()
{
jQuery.ajax({
type: "POST",
data: {varA: "123"},
success: function(data)
{
$("#test").html(data);
}
});
}
function buttony() //added 2nd independent jQuery.ajax function
{
jQuery.ajax({
type: "POST",
data: {varB: "456"},
success: function(data)
{
$("#test2").html(data);
}
});
}
</script>
</head>
<body>
<span id="test"></span>
<span id="test2"</span> //added 2nd span
<input type="button" value="Clicky" onclick="buttony()"/> //added
</body>
</html>
<?php
}
else
{
print_r($_POST['varA']);
}
if(isset($_POST['varB'])) //added isset() checking
{
print_r($_POST['varB']);
echo 'varB Okay';
}
else
{
echo 'varB Not';
}
?>
Additional information: Posting of variables for both jQuery.ajax of "Bad Example" are working fine.
Note: Pictures below are not from the codes above, just an example of what I meant by "content duplicated itself".
Before
After
Question: May I know where should I put my 2nd jQuery.ajax function and isset() checking of the POST variable, in such a way that both jQuery.ajax functions will work correctly and won't conflict with each other?
You shouldn't have to pass the bingo function the document ready function. Try
$(document).ready(function() {
function bingo()
{
jQuery.ajax({
type: "POST",
data: {varA: "123"},
success: function(data)
{
$("#test").html(data);
}
});
}
bingo();
function buttony() //added 2nd independent jQuery.ajax function
{
jQuery.ajax({
type: "POST",
data: {varB: "456"},
success: function(data)
{
$("#test2").html(data);
}
});
}
buttony();
}); //end document ready
I used window.location to replace the use of 2nd jQuery.ajax to avoid complication.
Sample example
Inside JavaScript function
window.location = "samePage.php?varB=abc";
Checking of POST variable varB
if(isset($_REQUEST['varB'])
{
$getValue = $_REQUEST['varB'];
}
I'm leaving the question open for the community to tackle on how to do proper nesting of using 2 or more jQuery.ajax in the same page.

Categories