Can't get JavaScript result using ajax script - javascript

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

Related

I can not to get the POST value from ajax

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.

AJAX redirect to another php file and pass javascript variable to that same php file

I am new to Ajax. I have here a function that when a button is clicked, you should be redirected to id.php and at the same time pass the value of clicked_id.
Javascript code:
function clicked(clicked_id){
window.alert("clicked");
window.alert(clicked_id);
$.post('id.php',{ID:clicked_id},
function(data){
window.alert("here");
window.location='id.php';
});
}
Inside my id.php,
<?php
$clickedID = $_GET['ID'];
echo 'here at id.php';
echo $clickedID;
?>
Now the problem is that ID in id.php cannot be identified.
Please help me. I already tried both $_POST and $_GET.
I believe that the problem here is in the passing of the variable.
there is no need for ajax if you wanna pass the id to the id.php after redirection
function clicked(clicked_id){
window.alert("clicked");
window.alert(clicked_id);
window.location='id.php?id=' + clicked_id;
}
in id.php you can get the id like this:
<?php $id = $_GET['id'];
function buttonClicked() {
$.ajax({
url: "id.php", //url for php function
type: "POST",
data: {'clicked_id':clicked_id}, // data to sent
dataType: 'json',
success: function (data)
{
}
});
}
And in your id.php file:
$_REQUEST['clicked_id']

Ajax wont retrieve the file from php file

Hi guys this script was working fine when I add a console.log but as soon as I replaced the console.log with the $.ajax() function it wont give me the result back from the php file the ajax function I used was working from my other projects but I cant seem to find out why it wont work on this snippet
Here is my js code :
$(document).ready(function(){
$("#qs").find(".chs").each(function(i,obj){
$(this).addClass("chs"+i);
$(".chs"+i).on("click",function(){
var s = $(this).data("lvs"),carrier= {"vars":s};
$.ajax({
url: aScript.php,
type: "POST",
data: carrier,
dataType: "json"
success: function(data) {
console.log(data) }
});
});
});
});
my php file looks like this
<?php
$json = $_POST['carrier'];
$data = json_decode($json);
$d = $data->vars;
echo $d;
?>
<input type="hidden" id="ss" value="<?=$d?>" />
can someone review this file for me cause I cant seem to find whats wrong please help me find out whats wrong with this script
You should wrap the filename inside quotes, as it is a string variable
$.ajax({
url: 'aScript.php',
type: "POST",
data: carrier,
dataType: "json",
success: function(data) {
console.log(data) }
});
});
There are some issues with your code
in this line url: aScript.php, the url string is not quoted, it should be url: 'aScript.php',
you set dataType: "json" but aScript.php returns html instead of json, remove that line
the data you're passing is not json, it will be serialized into key=value pairs and you'll be able to access it via $d = $_POST['vars'];

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