I can not to get the POST value from ajax - javascript

I would like to get the value from ajax with post in php, but this is not working, here is my code:
<script type="text/javascript">
function deletarPerson(id_person) {
let pag = "<?php echo plugin_dir_url(__DIR__) . 'admin/'; ?>";
jQuery.ajax({
url: pag + "/config.php",
method: "post",
data: {
id_person: id_person
},
dataType: "html",
success: function(result) {
<?php
$aux = $_POST['id_person'];
?>
alert('<?php echo $aux ?>')
},
})
}
</script>
Someone can help me?

Your Javascript ajax code:
function deletarPerson(id_person) {
jQuery.ajax({
url: "/echo.php", // <-- sending to echo.php on the server
// ...use whatever PHP file, on the server,
// you need to get the necessary information
method: "post",
data: {
id_person: id_person
},
dataType: "text",
success: function(result) {
alert(result) // <-- now use Javascript and the result variable,
// which is text sent back from the server,
// and do what you need to with it on the client
},
})
}
...and your PHP file:
<!-- echo.php -->
<?php
$aux = $_POST['id_person'];
echo $aux; // <-- whatever is echo'ed or print'ed in this file
// gets sent back to the server as text
// and is loaded in the Javascript result variable
// OR you can actually get some useful information from the server
// and send that back instead
?>
Read more about the distinct executions contexts between PHP on the server and Javascript/HTML/CSS... on the client.

Related

Can't get JavaScript result using ajax script

I am calling php file with ajax script.but when I am trying to call JavaScript in called php file it's not giving me JavaScript result in response. It's give me
Full script stored in variable.
index.php
$.ajax({
type: "POST",
dataType: "json",
url: "response.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
//Here i am print response
}
});
response.php
$return = $_POST;
$return["js"] = "<script>test();</script>";
$return["json"] = json_encode($return);
echo json_encode($return);
?>
<script>
function test(){
return 'Hello';
}
Can any one suggest me. Thanks in advance

Send variable to php via ajax

I'm trying to send a input value to php via ajax but I can't seem to get this right. I'm trying to create a datatable based on the user input.
This is my code:
<input class="form-control" id="id1" type="text" name="id1">
My javascript code:
<script type="text/javascript">
$(document).ready(function() {
var oTable = $('#jsontable').dataTable(); //Initialize the datatable
$('#load').on('click',function(){
var user = $(this).attr('id');
if(user != '')
{
$.ajax({
url: 'response.php?method=fetchdata',
data: {url: $('#id1').val()},
dataType: 'json',
success: function(s){
console.log(s);
oTable.fnClearTable();
for(var i = 0; i < s.length; i++) {
oTable.fnAddData([
s[i][0],
s[i][1],
s[i][2],
s[i][3],
s[i][4],
s[i][5],
s[i][6],
s[i][7]
]);
} // End For
},
error: function(e){
console.log(e.responseText);
}
});
}
});
});
</script>
My php script:
<?php
$conn = pg_connect(...);
$id1 = $_POST["id1"];
$result = pg_query_params($conn, 'SELECT * FROM t WHERE id1 = $1 LIMIT 20', array($id1));
while($fetch = pg_fetch_row($result)) {
$output[] = array ($fetch[0],$fetch[1],$fetch[2],$fetch[3],$fetch[4],$fetch[5],$fetch[6],$fetch[7]);
}
echo json_encode($output);
?>
I don't know a lot of js but my php is correct i test it. So i guess the problem is in the javascript code.
The problem is, my datatable is not being created based on the user input.
Thank you!
change
data: {url: $('#id1').val()},
to:
type: 'POST',
data: {id1: $('#id1').val()},
However the problem might be bigger. You might not be getting the correct data from PHP. You can debug by adding the error option to your ajax() call, like this:
$.ajax({
url: 'response.php?method=fetchdata',
type: 'POST',
data: {id1: $('#id1').val()},
dataType: 'json',
success: function(s){
},
error: function (xhr, status, errorThrown) {
console.log(xhr.status);
console.log(xhr.responseText);
}
});
Then check your browser's Console for the output, this should give you some type of error message coming from PHP.
My assumption is that since you are using dataType: 'json', the ajax request expects JSON headers back, but PHP is sending HTML/Text. To fix, add the correct headers before echoing your JSON:
header('Content-Type: application/json');
echo json_encode($output);

I can't passing variable to PHP from JavaScript and jQuery load the response

I want passing 2 parameters to PHP page via AJAX and load the response, but this code is not working.
JavaScript:
$(".show_category").click(function(){
var category_id = $(this).attr('data-category');
$.ajax({
url: "conx.php",
method: "POST",
data: {
action: "sort_category",
category_id: category_id
},
success: function(data) {
$("#con").load("conx.php");
}
});
});
PHP:
<?php
echo "1".$_POST["action"]."<br/>";
?>
You issue is here:
success: function(data) {
$("#con").load("conx.php");
}
At this point, you have already posted the data and received the HTML response. There is no need to make another HTTML request by calling .load, and doing so will mean requesting it again without the POST data, so it will not have the intended effect. Just use the HTML you already have in the data argument.
success: function(data) {
$("#con").html(data);
}
On a side note, this PHP code is a reflected XSS vulnerability:
<?php
echo "1".$_POST["action"]."<br/>";
?>

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

Why Does My AJAX Response Contain HTML Source?

hope you're all doing well. Here's the deal. I make an AJAX call to PHP and PHP decodes the JSON string then echoes a property from the json object but in the AJAX response alert, I get the correct value from the json property AND the source of the current page, for example:
jsonProperty<!DOCTYPE HTML>
<html>
<head>... [the rest of the page's source]
Here is my code:
PHP
<?php
private function validate_review(){
$json = json_decode($_POST['data']);
echo $json->review;
}
?>
AJAX:
<script>
var reviewData = {
title : $('#fieldtitle').val(),
raiting : starRaiting,
review : $('#fieldreview').val()
}
$.ajax({
type: 'post',
url: 'http://localhost/codeigniter/new-review',
data: {data: JSON.stringify(reviewData)},
success: function(result){
alert(result);
}
});
</script>
Why would the response also include the source of the page, this is completely counter-intuitive and strange. Help?
Request:
specify your request dataType
$.ajax({
type: 'post',
url: 'http://localhost/codeigniter/new-review',
data: {data: JSON.stringify(reviewData)},
dataType: 'jsonp', //tell the server that you expect json
success: function(result){
alert(result);
}
});
Response:
<?php
//DO NOT echo any output before header
header('Content-Type: application/json'); //said this response content is json
?>
and die instead of echo json content
I think your code still includes the template.
private function validate_review(){
$json = json_decode($_POST['data']);
die($json->review);
}
This should work.

Categories