Javascript Not Calling PHP function in wordpress - javascript

I am trying to get the following code to work:
//In Javascript
function updateContentEditable(){
var span = $(this);
var data = new Object();
data.pid = '1';
data.content = 'this is a test';
data.action = 'update_content'; //This should run update_content php function
$.post(ajaxPath, data, onContentSaved); //ajaxPath returns: /wp-admin/admin-ajax.php
}
//In PHP
function update_content(){
echo "<script>alert (\"php was reached\")</script>";
}
NOTE:
//onContentSaved is this:
function onContentSaved(data){
console.log(data);
}
My problem is the the php function is not being run.
What I'm I doing wrong?

Assuming you are using jquery, try this:
function SendRequestCallBack(webMethod, parameters, callBack) {
$.ajax({
type: "POST",
url: webMethod,
data: parameters,
contentType: "application/json; charset=utf-8",
success: function(results) {
$(".ajaxImage").hide();
eval(callBack(results.d));
}
});
}
function formatData(obj){
alert(obj);
}
$(document).ready(function()
{
SendRequestCallBack("http://url-to-php","{'any':'parameters'}",formatData);
});
Then all the PHP needs to do is echo valid JSON. Or if you like you can change the contentType: parameter to text/xml or text/plain etc depending on what you want it to return. Keep in mind that your PHP needs to output the matching content type as well. for example
<?php
header("Content-type: text/json");
echo {"d":[{"firstname":"John","lastname":"Doe"},{"firstname":"Jane","lastname":"Doe"}]}
?>
If you want to pass data in to the PHP function, set it in the parameters, and make sure that your PHP will accommodate it using the $_POST array.

Related

How to access a javascript variable inside a php query?

I want to access a javascript variable inside a php query
function myFunction2(){
Total=parseInt(point2)
<?php
$con->query("UPDATE eventlist SET P2 = $this.Total WHERE Eid=$PID");
?>
}
I want the query to set p2=value of total
I understand that php is a serverside script and I cant do this like this. What is an alternative to this.?
EDIT
ok i got this on the JS side
function myFunction2(){
var Total = parseInt(point1)+parseInt(point2);
$.ajax({ url: 'ajax.php',
data: {'total' : Total},
type: 'post',
dataType:'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error");
}
and if i put
echo $_POST['total']
in ajax.php i get an alert with the value passed. So i think the value is being passed properly.
But what i need to do is a Mysql Query.
$con->query("UPDATE eventlist SET P2 = $_POST['total']; WHERE Eid=1");
Something like this. How do i do this
Try send javascript value to another php page which contain your query
function myFunction () {
var param = "value";
$.post('query.php', { postvalue: param}, function(data) {
//do what you want with returned data
//postvalue should be the name of post parameter in your query page
})
}
Change your PHP in this way:
$total = $_POST['total'];
$con->query("UPDATE eventlist SET P2 = $total WHERE Eid=1");

Javascript and PHP. Sending Multiple Array to PHP Using Ajax and Convert it to PHP Array

I need some help. I am trying to send multiply array of width and length to php, straight forward. I don't want to save it to any HTML field, however it's not working. I am getting the width and length from html text are and convert it to a number and then add it to an array in javascript.
Here is the code for that
var widthL = [];
var lengthL = [];
var widths = document.wall.width.value;
var lengths = document.wall.length.value;
var wNumber = Number(widths);
var lNumber = Number(lengths);
widthL.push(JSON.stringify(wNumber));
lengthL.push(JSON.stringify(lNumber));
This is the Ajax code I am using to send it to PHP
$.ajax( {
type: "POST",
url: "./Summary.php",
data: {"widths": widthL, "lengths" : lengthL},
cache: false,
success: function (response) {
console.log("This is the width", widthL, " This is the length", lengthL);
}
});
In PHP I am using this code to receive it. But I am not getting things back.
<?php
$lengths = json_decode($_POST['lengths']);
$widths = json_decode($_POST['widths']);
echo 'This is the width: '.$widtsL;
echo 'This is the length: '.$lengths;
?>
I was hopping that someone could help me out here.
First you should specify the content type in the ajax POST:
$.ajax( {
type: "POST",
url: "./Summary.php",
contentType: "application/json; charset=UTF-8", // Add content type
data: {"widths": widthL, "lengths" : lengthL},
cache: false,
success: function (response) {
console.log("This is the width", widthL, " This is the length", lengthL);
}
});
then in PHP:
$request_body = file_get_contents('php://input'); //This reads the raw POST data
$json = json_decode($request_body); // Then parse it to JSON
$lengths = $json->lengths;
$widths = $json->widths;
please add a POST parameter name as dataType,type it value JSON,
the Ajax data param value use key=value&key=value format
then in php file enter debug code

How do I get two arrays in Ajax call?

JS CODE:
$.ajax({
url: 'assignavailtrainers.php',
data: {action:'test'},
type: 'post',
success: function(data) {
}
});
PHP CODE:
<?php
$username = "trainerapp";
$password = "password";
$hostname = "localhost";
$link = #mysql_connect($hostname, $username, $password);
if(#mysql_select_db("trainer_registration"))
{
$select_query_num = #mysql_query("select program_id,facilitator_id,availability_status from program_facilitator where availability_status in (1,2)");
$select_query_name = #mysql_query("select facilitator_id,firstname,lastname,email_id from facilitator_details");
$num_rows = #mysql_num_rows($select_query_num);
$trainerdetails = [];
$traineravaildetails = [];
$i = 0;
$j = 0;
while($row = #mysql_fetch_assoc($select_query_num))
{
$trainerdetails[$i]['pgidi'] = $row['program_id'];
$trainerdetails[$i]['facilitatorid'] = $row['facilitator_id'];
$trainerdetails[$i]['avail_status'] = $row['availability_status'];
$trainerdetails[$i]['idi'] = $row['facilitator_id'];
$i++;
}
while($row1 =#mysql_fetch_assoc($select_query_name))
{
$traineravaildetails[$j]['facilitatorid'] = $row1['facilitator_id'];
$traineravaildetails[$j]['firstname'] = $row1['firstname'];
$traineravaildetails[$j]['lastname'] = $row1['lastname'];
$traineravaildetails[$j]['emailidvalue'] = $row1['email_id'];
$j++;
}
echo json_encode(array('result1'=>$trainerdetails,'result2'=>$traineravaildetails));
}
?>
Please help me with the code in the ajax success function area. I've tried using initChart2 but I get an error which says initChart2 is not defined. I don't seem to understand of how to get two arrays from PHP in ajax since I'm a newbie ajax. If someone can help me with the code along with explanation, it'd be great. And I also need to know how to differentiate outputs in ajax which are sent from PHP.
You have two choices:
First one is to simply parse received (text) data to JSON:
var jsonData = JSON.parse(data);
// or simply data = JSON.parse(data);
But the best one in my oppinion is to specify json dataType to the $.ajax() request:
$.ajax(
data: {action:'test'},
type: 'post',
dataType: 'json',
success: function(data) {
...
}
});
This way, $.ajax() will also check for the validity of the received JSON data and error callback will be called instead of success one in case of wrong JSON data received.
...also is important to note you missed to send the json content-type header in your php with:
header("Content-Type: application/json");
Sending this header the dataType: 'json' parameter is no longer (strictly) necessary because $.ajax() guesses it by default attending to the received content-type. But, personally, I prefer to do both.
See $.ajax() documentation.
You forgot:
header("Content-Type: application/json");
… in your PHP.
While you are outputting JSON, you are telling the browser that it is HTML (which is the default for PHP) so jQuery isn't converting it to a useful data structure.
Add that and then you should be able to access data.result1 and data.result2.
To get ajax data:
$.ajax({
url: 'assignavailtrainers.php',
data: {action:'test'},
type: 'post',
success: function(data) {
data.result1;
data.result2;
}
});
You can use console.log(data); to view data structure

Using ajax to call php and return multiple variables?

I am trying to use javascript to call a php script which then will return multiple variables back to my javascript so I can manipulate them.
This is my JS.
$.ajax({
url: 'test.php',
data: { id : lastFileId },
success: function(output) {
alert(output);
}
});
my PHP
<?php
$fileId = ($_GET['id']);
$num1 = 1;
$num2 = 2;
?>
From here, how can I return variables $num1 and $num2 so i can use them in my javascript. Is it possible?
also this is a very basic idea of what I have planned to do if I can achieve this.
You can return as many variables as you want with json_encode().
Try in your PHP:
<?php
echo json_encode(array($num1, $num2));
?>
You can add to that array , $num3, $num4, ... and so on.
In your JS, you can access each number as follows.
First, you will need this line of code to parse the encoded JSON string, in your success function.
var result = $.parseJSON(output);
That sets result as a JSON object. Now you can access all fields within result:
result[0] -- $num1 in PHP
result[1] -- $num2 in PHP
You can go for Json in PHP and javascript if you want array in response for a ajax request
PHP Code
<?php
$fileId = isset($_GET['id'])?$_GET['id']:0;
echo json_encode(array("field"=>$fileId,"num1"=>1,"num2"=>2));
?>
Js Code
jQuery.ajax({
type: "GET",
url: 'test.php',
dataType: "json",
success: function(response) {
console.log(response);
alert(response.num1);
}
});
convert json to object
jQuery.ajax({
type: "GET",
url: 'test.php',
dataType: "json",
success: function(response) {
item=JSON.parse(response);
console.log(item);
alert(item.num1);
}
});
Use a simply string and explode(split) it further in ajax response. Here is PHP code
<?php
$fileId = ($_GET['id']);
echo $num1."|".$num2;
?>
Now split(explode) the response with JavaScript
$.ajax({
url: 'test.php',
data: { id : lastFileId },
success: function(output) {
var my_arr = output.split("|");
console.log(my_arr[0] + "" + my_arr[1]);
}
});
you can simply return it like that
return ['num1'=>$num1,'num2' => $num2];
and also, you can access it as followed,
respone.num1

Transfer data to javascript array with mysql data request via php and $.ajax

I have the following code for requesting data from a mysql database:
jquery/javascript:
ajaxGet = function (url) {
var result = $.ajax({
url:url,
type:"POST",
data:{action:'call_this'},
dataType: 'json',
success:function(data) {
}
});
return result;
}
php:
<?php
if($_POST['action'] == 'call_this') {
// call waypoint search
include ('link.php');
$sql="SELECT * FROM Waypoints"; //data in table Waypoints
$result = mysqli_query($link,$sql);
$wptdata=array();
while($line = mysqli_fetch_assoc($result)){
$wptdata[] = $line;
};
mysqli_close($link);
echo json_encode($wptdata);
};
?>
To get the data as a javascript array, I would like to be able to say something like this:
wpdata=ajaxGet('datacall.php');
Suggestions on how to get this to work? If I put alert(data[0].name) within the success function, it comes up with the right result, so the call to the database table is definitely working. But I can't seem to figure out how to get the array out of the $.ajax call.
Thanks for any help- have been searching through other questions, and just came seem to find a solution. I would like to keep the ajaxGet function if at all possible- once I get it working, I will be able to update it so that it is flexible as to what kind of data are called from the table.
The answer is no. You cannot do this is any way that is sane. Use callbacks/promises - that's the way to go!
function ajaxGet(url) {
return $.ajax({
url: url,
type: "POST",
data: {
action: 'call_this'
},
dataType: 'json'
});
}
ajaxGet().done(function(wpdata) {
// use wpdata here
});

Categories