i'm creating a plugin for WooCommerce
in my plugin php file when i call a php file with jquery ajax i get empty result
this is my ajax code:
jQuery(function() {
jQuery.ajax({
url: '<?php echo RAKHSH_WC_QUICK_VIEW_URL ?>/rakhsh-data-for-pop.php',
success: function(output) {
alert(output);
}
});
});
and this is my php file:
<?php
$output = 'test';
return $output;
?>
You should change this:
<?php
$output = 'test';
return $output;
?>
To this:
<?php
$output = 'test';
die($output); // or echo or print
?>
Returning a variable will not return it as a response to an ajax call.
try this
<?php
$output = 'test';
echo $output;
?>
You can try this:
create a empty variable and insert your data to this.
var response = '';
$.ajax({ type: "GET",
url: '<?php echo RAKHSH_WC_QUICK_VIEW_URL ?>/rakhsh-data-for-pop.php',
async: false,
success : function(text)
{
response = text;
}
return response;
});
Related
I wrote the following code snippet for Ajax connections, but unfortunately the return value is not displayed in the output, but it does not give a special warning to understand the meaning. Please help.
js
$("#search").on('keyup', function(){var value = $(this).val();
$.ajax('feed.php',{
type: 'POST',
dataType: 'json',
data: {
keyword: value
},
success: function(data){
$("#pre").html(data);
}
});
});
feed.php
<?php
require_once('main.php');
$db = Db::getInstance();
$keyword = $_POST['keyword'];
$records = $db->query("SELECT * FROM dic_word WHERE word LIKE '%$keyword%'");
$out['html']= '';
foreach($records as $record){
$out['html'] .= $record['word'] . '<br>';
}
echo json_encode($out);
?>
js:
jQuery('#search').on('keyup', () => {
jQuery.ajax({
url: 'feed.php',
type: 'POST',
data: { keyword: jQuery(this).val() },
success: response => {
jQuery('#pre').html(response);
}
});
});
feed.php
<?php
require_once('main.php');
$database = Db::getInstance();
$keyword = $_POST['keyword'];
$records = $database->query("SELECT * FROM dic_word WHERE word LIKE '%$keyword%'");
$output = '';
foreach($records as $record){
$output .= $record['word'] . '<br />';
}
echo($output);
?>
PS: You don't need to use json output absolutly. But if there is coercion to using json output, the problem is 2 following items:
You don't set the output "Content-Type" to json: header('Content-Type: application/json');
You shouldn't pass the json object to html method in jQuery and should parsing it at first with JSON.parse(response) class, then with foreach, for or anything else process it
I am trying to refresh my a page if there is a change in orderStatus from database using Ajax and PHP. I set the current orderStatus as predefined data and then use Ajax to get the current orderStatus from database and finally compare if they are not the same. I want to refresh the page if they are not the same.
PHP (autorefresh.php)
<?php
$orderId = $_POST["orderId"];
$query = "SELECT * FROM orderinhomeonlinecall WHERE orderId='$orderId'";
$result = mysqli_query($db, $query);
while($row = mysqli_fetch_array($result))
{
$orderStatus = $row['orderStatus'];
$data = array(
'orderStatus' => $orderStatus
);
echo json_encode($data);
}
?>
Javascript
<script type="text/javascript" >
var predefined_val = '<?php echo $orderStatus; ?>';// your predefined value.
$.document(ready(function(){
setInterval(function(){
$.ajax({
type:"POST",
url:"autorefresh.php", //put relative url here, script which will return php
data:{orderId: <?php echo $orderId; ?>}, // if any you would like to post any data
success:function(response){
var data = response; // response data from your php script
if(predefined_val !== data){
window.location.href=window.location.href;
}
}
});
},5000);// function will run every 5 seconds
}));
The below code should work, Need to mention dataType:"json" else use JSON.stringify(data) to parse response
<script type="text/javascript">
var predefined_val = '<?php echo $orderStatus; ?>';// your predefined value.
$(document).ready(function () {
setInterval(function () {
$.ajax({
type: "POST",
url: "autorefresh.php", //put relative url here, script which will return php
data: {orderId: <?php echo $orderId; ?>}, // if any you would like to post any data
dataType: "json",
success: function (response) {
var data = response; // response data from your php script
if (predefined_val !== data.orderStatus) {
window.location.href = window.location.href;
}
}
});
}, 5000);// function will run every 5 seconds
});
</script>
I have tested this by creating two files(autorefresh.php,index.php) and test db with table and it is working for me. I think the below code would be helpful, If not please share you code, i will check and fix it.
autorefresh.php
// Create connection
$db = new mysqli("localhost", "root", "","test");
$orderId = $_POST["orderId"];
$query = "SELECT * FROM orderinhomeonlinecall WHERE orderId='$orderId'";
$result = mysqli_query($db, $query);
while($row = mysqli_fetch_array($result))
{
$orderStatus = $row['orderStatus'];
$data = array(
'orderStatus' => $orderStatus
);
echo json_encode($data);
}
?>
index.php
<?php
$orderStatus ='pending';
$orderId =1;
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
var predefined_val = '<?php echo $orderStatus; ?>';// your predefined value.
$(document).ready(function () {
setInterval(function () {
$.ajax({
type: "POST",
url: "autorefresh.php", //put relative url here, script which will return php
data: {orderId: <?php echo $orderId; ?>}, // if any you would like to post any data
dataType: "json",
success: function (response) {
var data = response; // response data from your php script
if (predefined_val !== data.orderStatus) {
window.location.href = window.location.href;
}
}
});
}, 5000);// function will run every 5 seconds
});
</script>
I am sending a JSON object from js to post.php
$.ajax({
type:'post',
url:'post.php',
data:{jsonobject:json_str}
});
but I am not able to retrieve the result in a post.php file
$obj = jsonString2Obj($_POST['jsonobject']);
echo $obj->people->user;
function jsonString2Obj($str){
return json_decode(stripcslashes($str));
}
I have no idea about your $jsonr_str.
It's my example:
$json = '{"people":[{"user":"Amy"},{"user":"Lee"},{"user":"David"}]}';
// covert into object
$data = json_decode(stripcslashes($json));
echo "People[0]=" . $data->people[0]->user;
// or covert info array
$data = json_decode($json, true);
// Using print_r()
echo "<pre>" .print_r($data, true). "</pre>";
Try like this
var data = {
people:{user:'Joe Cooper'}
};
$.ajax({
type:'post',
url:'post.php',
data:{jsonobject:JSON.stringify(data)}
});
<?php
$obj = jsonString2Obj($_POST['jsonobject']);
echo $obj->people->user;
function jsonString2Obj($str){
return json_decode(stripcslashes($str));
}
I get this weird error. It happens to be my PHP code that is embedded into jquery.
<?php $user=isset($_GET['u']) ? $_GET['u'] : NULL; //This returns a numeric value ?>
<script>
$("button[name='send_mail']").on('click',function(){
var user = '<?php echo $user;?>'; // <----The Problem
$.ajax({
type:"POST",
url:"ajax/scripts/user_mail.php?u="+user,
success: function(data){
alert(data);
},
});
});
</script>
I tried both, single and double quotes. This piece code happens to work in some of my files and doesn't work in others.
<?php
$user = (!empty($_GET['u']))?intval($_GET['u']):0;
?>
<script language="JavaScript">
console.log("User: " + <?php echo $user; ?>);
// try to debug what is really in the variable
var user = <?php echo $user; ?>;
// same as <?= $user; ?>
</script>
You have a rogue comma in this part of your code:
success: function(data){
alert(data);
}, //<--- here
});
It should be only:
success: function(data){
alert(data);
}
});
This works:
<?php $user=isset($_GET['u']) ? $_GET['u'] : NULL;?>
<span id="user_id_span" style="display:none;"><?php echo $user; ?></span>
<script>
var user = $('#user_id_span').text();
</script>
If your output is more than just a single string or number or single line, this would not work.
I must to check the result of Ajax are same with some PHP variable value.
Is there anyway to do this?
Thank you in advance for help.
My Ajax HTML:
<?php
$x = '<p id="ip"></p>';
$y = '2_2_1_3';
if($x == $y){
echo $x;
}
?>
<a id="input" href="#">Get value<input type="hidden" value="2_2_1_3"></a>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
jQuery(document).ready(function(){
$("#input").on("click", function(){
$.ajax({
type: 'POST',
url: "ip2.php",
data:'ip=' + $(this).parent().find('input').val(),
success: function(data){
$("#ip").html(data);
}
});
});
});
</script>
The PHP script:
<?php
if($_POST['ip'] >= 0){
$ip = $_POST['ip'];
echo $ip;
}
?>
$x = '<p id="ip"></p>';
$y = '2_2_1_3';
if($x == $y){ // this will never be true because $x is diferent of $y
echo $x; //so you will never print this out
}
And you won't have the element with id="ip" to print the result from your ajax
success: function(data){
$("#ip").html(data);
}
For it to work try this:
<?php
$x = '<p id="ip"></p>';
$y = '2_2_1_3';
echo $x;
?>
I'm not entirely sure what you want to do, but you can always send your post data as an object in javascript, for simplicity you can use the post function.
Example:
$.post( "ip2.php", { ip: $(this).parent().find('input').val() }, function( data ) {
console.log( data );
});
More info:
https://api.jquery.com/jquery.post/
https://api.jquery.com/jQuery.ajax/