i have problem with php.
AJAX
$(document).ready(function(){
$.ajax({
type: "POST", // i test post, get...
url:'TESTING.php',
data: {name: "alfred"},
success: function(){
alert("success"); // it show "success" !... :/
}
});
});
And php
<?php
//var_dump($_POST); array is empty
$name = $_POST['name']; // error line
echo $name;
?>
I test it on Localhost (if it is the problem). And i dont know, where is mistake.
Thanks for any help
Along with what the comments say about $_GET not grabbing $_POST data you sent, you are not using the return data.
success: function(data){ //response param
alert(data);
}
var weightd = $("#weight").val();
var user_id = <?php echo $current_user->ID; ?>;
$.ajax({
type: "POST",
url:"<?php bloginfo('template_directory')?>/ajax/index.php",
data: { weight:weightd,user_ids:user_id},
success:function(result){
$("#result1").html(result);
setInterval(function() {
$('#result1').hide('slow');
}, 5000);
}});
<div id="result1"></div>
try to user like this
You are sending the data via POST, not GET .
Change
$name = $_GET['name'];
To
$name = $_POST['name'];
Your callback function must have argument,
Change
success: function(){
alert("success");
}
To
success: function(data){
alert("success"); // or whatever you wanna do
}
Here is all code
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script src="//code.jquery.com/jquery.js"></script>
</head>
<body>
</body>
<script>
$(document).ready(function(){
$.ajax({
type: "POST",
url:'TESTING.php',
data: {name: "Alfred"},
success: function(data){ //response param
alert(data);
}
});
});
</script>
<?php
echo "Hi ";
//var_dump($_POST);
$nick = $_POST['name'];
echo $nick;
?>
</body>
</html>
Related
I've one page called test.php that display 2 types of products, first type is Odd second type is Even, the page have one HTML Switch/Toggle
Note( the code work OK and it display results according to switch/toggle value )
I've 1 issue
Code run's ok but it duplicate the switch/toggle (See Images Bellow)
.
test.php
<?php
require ('../../common.php');
echo "
<html>
<head>
<link rel='stylesheet' href='css/toggleOddEven.css'>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script>
to load default odd products on page load
<script type='text/javascript'>
$(window).load(function() {
$.ajax({
type:'POST',
url:'test.php',
data:{
product_type:'odd'
},
success: function(data){
$('#view').html(data);
}
});
});
</script>
Switch/Toggle value
<script type='text/javascript'>
$(function(){
$('#myonoffswitch').click(function() {
if ($('#myonoffswitch').prop('checked')) {
$.ajax({
type:'POST',
url:'test.php',
data:{
product_type:'even'
},
success: function(data){
$('#view').html(data);
}
});
}else{
$.ajax({
type:'POST',
url:'test.php',
data:{
product_type:'odd'
},
success: function(data){
$('#view').html(data);
}
});
}
});
});
</script>
Rest of page code
</head>
<body>
<div class='onoffswitch'>
<input type='checkbox' name='onoffswitch' class='onoffswitch-checkbox' id='myonoffswitch'>
<label class='onoffswitch-label' for='myonoffswitch'>
<span class='onoffswitch-inner'></span>
<span class='onoffswitch-switch'></span>
</label>
</div>
<div id='view'></div>
</body>
</html>
";
if (isset($_POST['product_type'])) {
$product_type = $_POST['product_type'];
$allProducts="SELECT * FROM products_tbl
WHERE product_type = :product_type ";
$stmt = $db->prepare($allProducts);
$query_params = array(
':product_type' => $product_type
);
$stmt->execute($query_params);
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($data as $value):
echo "
<strong># </strong> <a href='prod?id=".$value['product_name']."'>".$value['product_name']."</a> </br>
";
endforeach;
}
?>
why it duplicate the tag ? see bellow image
odd product (default value)
even product
It's because you load the whole page in test.php, not only the result data. This should help:
if (isset($_POST['product_type'])) {
--> keep existing code
} else {
--> Put your large echo into here
echo "
<html>
<head>
<link rel='stylesheet' href='css/toggleOddEven.css'>
...
";
}
A cleaner solution might be to split the data and the UI into seperate PHP files and only request the data PHP.
I have been trying to fetch data from the server using jquery .ajax function.
However it's not working whenever I give data Type as JSON.
It works fine when I don't define dataType, but I need dataType to be JSON..
Below are the codes.
Practice.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Practice</title>
<?php
require("db.php");
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div>Why doesn't it work..</div>
<div id="demo"></div>
<button type="button" id="button" name="button">button</button>
</body>
<script>
//Load table
$('#button').on('click', function(){
// var please = 1;
$.ajax({
type: 'POST',
url: 'AJAX.php',
// data: {id: please},
dataType: 'json',
success: function(data) {
$('#demo').text('Worked!');
console.log(data);
},
error: function(error) {
$('#demo').text('Error : ' + error);
console.log(error);
}
});
});
</script>
</html>
AJAX.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Ajax Practice</title>
<?php
require("db.php");
?>
</head>
<body>
<?php
if (isset($_POST["id"])) {
$id = $_POST["id"];
} else {
$id = 1;
}
$stmt = $conn->prepare("SELECT * FROM projects WHERE id=$id");
$stmt->execute();
$all = $stmt->fetchAll(PDO::FETCH_ASSOC);
$all = json_encode($all);
echo $all;
?>
</body>
</html>
And here is the result of the echo..
[
{
"Project":"BPM",
"Date":"2018-03-02 00:00:00",
"Manager":"Someone",
"Status":"2",
"ID":"1",
"Counter":null
}
]
I'm pretty new to Jquery and web programming generally..
Please advise, your help is greatly appreciated.
Remove all HTML from your AJAX.php then add the code below to the top of your AJAX.php
header('Content-Type: application/json');
<?php
require("db.php");
if (isset($_POST["id"])) {
$id = $_POST["id"];
} else {
$id = 1;
}
$stmt = $conn->prepare("SELECT * FROM projects WHERE id=$id");
$stmt->execute();
$all = $stmt->fetchAll(PDO::FETCH_ASSOC);
$all = json_encode($all);
echo $all;
?>
Change Your Ajax code to This. Because here there is no need of html Content
You can use mysqli_real_escape_string
since you specified dataType: 'json' your js is expecting json format. Right now, you are returning including the <head>, <beody> html tags.
On your AJAX.php
<?php
require("db.php");
if (isset($_POST["id"])) {
$id = $_POST["id"];
} else {
$id = 1;
}
$stmt = $conn->prepare("SELECT * FROM projects WHERE id=$id");
$stmt->execute();
$all = $stmt->fetchAll(PDO::FETCH_ASSOC);
$all = json_encode($all);
echo $all;
?>
You need to parse it in your AJAX. Try this...
$('#button').on('click', function(){
// var please = 1;
$.ajax({
type: 'POST',
url: 'AJAX.php',
// data: {id: please},
dataType: 'json',
success: function(data) {
var response = JSON.parse(data);
$('#demo').text('Worked!');
console.log(response);
},
error: function(error) {
$('#demo').text('Error : ' + error);
console.log(error);
}
});
});
I am having issues with reading Json_encode response in a java script.
The PHP file reads values from database and sends the results as Json_encode array to html.
<?php
include("connect.php");
try {
$conn = new PDO("mysql:host=$servername;dbname=mydb", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "Call print_awb (#output1,#output2,:input_awb_ref_id)";
if (isset($_POST)) {
$p_in_awb_ref_id =reset($_POST["var_p_in_awb_ref_id"]);
}
$stmt = $conn->prepare($sql);
$stmt->bindParam(':input_awb_ref_id',$p_in_awb_ref_id, PDO::PARAM_INT);
$stmt->execute();
$out_awb_ref_id = $conn->query("SELECT #output1")->fetch(PDO::FETCH_ASSOC);
$out_agent_id = $conn->query("SELECT #output2")->fetch(PDO::FETCH_ASSOC);
$output = array(
"out_awb_ref_id" => $out_awb_ref_id,
"out_agent_id" => $out_agent_id,
);
echo json_encode($output);
$stmt->closeCursor();
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
?>
The HTML CODE
<script type="text/javascript">
function get_parameters(){
var quote = ABCD1234;
quote.toString();
window.alert(quote);
$.ajax({
type: "POST",
url: "printawb.php",
data: {var_p_in_awb_ref_id:quote},
dataType: "text",
success: function (result) {
alert(result);
var a = result.out_awb_ref_id;
alert (a);
alert(result['out_awb_ref_id']);
alert(result['out_agent_id'])
},
error:function (jqXHR, status, err){
//Fail
layer_1.html(html);
}
});
return vars;
};
</script>
The response I have is
HVP000062
{"out_awb_ref_id":{"#output1":"MIR"},"out_agent_id":{"#output2":"rtPreston"}}
undefined
undefined
All Need is the values in the 2nd line of the result ie. "MIR" and "rtPreston"
I have tried couple of things:
1. changed the calling function type as 'JSON' but the response was 'Object' without values
2. Tried converting to jsonString
3. tried reading values using JSON.parse(jsonString);
4. result['out_ref_awb_id']
None of them work. Can someone help me how I can get values of these? I can then use them to populate on a html page.
Many thanks
Add this as a first line in the HEAD section of your HTML template
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
Then try this code:
<script type="text/javascript">
function get_parameters(){
var quote = ABCD1234;
quote.toString();
window.alert(quote);
$.ajax({
type: "POST",
url: "printawb.php",
data: {var_p_in_awb_ref_id:quote},
dataType: "text",
success: function (result) {
var data = jQuery.parseJSON(result);
var param1 = data.out_agent_id;
var param2 = data.out_awb_ref_id;
alert(param1["#output2"]);
alert(param2["#output1"])
},
error:function (jqXHR, status, err){
//Fail
layer_1.html(html);
}
});
return vars;
};
</script>
I'm attempting to post some data back to the same page through ajax. In the example below the $name variable is not being updated in my page once the button is clicked. However, if I look at the console log of the response from ajax (using firebug) it shows the correct html, with the name inserted (i.e. <div>Matthew</div>) - the page just isn't being updated with this response. Any ideas for how to fix this would be greatly appreciated.
The code I have is:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
<?php
$name = "A name";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$name = "No name!";
}
else{
$name = $_POST["name"];
}
}
?>
<script>
$(document).ready(function(){
$("button").click(function(){
var mydata = {name: "Matthew"};
$.ajax({
type: 'POST',
data: mydata,
success: function(data){
console.log(data);
}
});
});
});
</script>
<button>Send an HTTP POST request to a page and get the result back</button>
<div id="name">
<?php echo $name;?>
</div>
</body>
</html>
It is because <?php echo $name;?> does not run again when doing the ajax call. You have to replace the content of the div in the success function like this:
success: function(data){
$("div").html(data);
}
I have assigned two variables that are equal to a PHP variable that can change at any time. I am trying to update a div every 5 seconds; for example, to update the number. I am assuming this doesn't work because the PHP doesn't run again once the page has loaded. What is the best way to get around this? I don't mind linking to another page if necessary. Here's my code:
$(document).ready(function() {
var buyprice = <?php echo $coinTicker->price($coin2[1] , 'buy'); ?>;
var sellprice = <?php echo $coinTicker->price($coin2[1] , 'sell'); ?>;
$('#currentbuyprice').html(buyprice);
$('#currentsellprice').html(sellprice);
setInterval(function() {
var buyprice = <?php echo $coinTicker->price($coin2[1] , 'buy'); ?>;
var sellprice = <?php echo $coinTicker->price($coin2[1] , 'sell'); ?>;
$('#currentbuyprice').html(buyprice);
$('#currentsellprice').html(sellprice);
}, 5000);
});
Yeah - that won't work as you know.
setInterval(function() {
var buyprice = <?php echo $coinTicker->price($coin2[1] , 'buy'); ?>;
var sellprice = <?php echo $coinTicker->price($coin2[1] , 'sell'); ?>;
$('#currentbuyprice').html(buyprice);
$('#currentsellprice').html(sellprice);
}, 5000);
That is a javascript + php. The browser runs javascript and php runs on the server. They run at different times and are mutually exclusive. The work apart from each other.
What you want to do (probably) if you are trying to update realtime is to use an ajax call.
http://api.jquery.com/jquery.ajax/
I find the api documentation good for reference but bad for example.
var jqXHR = $.ajax({
url: "target.aspx",
type: "GET",
dataType: "html",
}).done(function (data, status, jqXHR) {
$("#container").html(data);
alert("Promise success callback.");
}).fail(function (jqXHR,status,err) {
alert("Promise error callback.");
}).always(function () {
alert("Promise completion callback.");
})
That makes a pretty good example. Google "jqXHR" for other working examples
$(document).ready(function() {
var buyprice = <?php echo $coinTicker->price($coin2[1] , 'buy'); ?>;
var sellprice = <?php echo $coinTicker->price($coin2[1] , 'sell'); ?>;
$('#currentbuyprice').html(buyprice);
$('#currentsellprice').html(sellprice);
setInterval(function() {
$.get('/get_prices.php', function( data ) {
buyprice = data.buy;
sellprice = data.sell;
$('#currentbuyprice').html(buyprice);
$('#currentsellprice').html(sellprice);
}, "json" );
}, 5000);
});
And in your backend (/get_prices.php in this example, change it!)
<?php
$buy = 1;
$sell = 1;
echo json_encode(array(
'buy' => $buy,
'sell' => $sell,
));
exit;
You can make a simple ajax get request to a seperate php file that returns the data as json:
setInterval(function() {
$.get('/prices.php', function(data){
$('#currentbuyprice').html(data.buyprice);
$('#currentsellprice').html(data.sellprice);
});
}, 5000);
prices.php:
//code that creates $cointTicker and $coin vars goes here
header('Content-Type: application/json');
echo json_encode(
[
'buyprice' => $coinTicker->price($coin2[1] , 'buy'),
'sellprice' => $coinTicker->price($coin2[1] , 'sell')
]
);
You can't update static PHP variables, because the PHP-script gets an request, works and answers to the client, so the session is closed. The are two ways to handle that.
Way 1:
You have to connect your PHP to an Database. So you will send a request to a PHP-file, which updates the numbers in the database, so the values will be safed, also for the next request.
Way2:
You can make PHP Sessions php.net link. So you will save your values temporary in a session. That session will deleted after a while, and maybe that is not that, what you need. sessions are similar to cookies.
Both ways work through an AJAX-Request. So you need an Javascript-Function, that will send your request to that PHP-file, which will update the Database or the Session. You should also have a function to get that values from the Database or the Session.
Using the same approach (making a polling) you can make an ajax query
<!DOCTYPE html>
<html>
<head>
<title>
</title>
<meta charset="utf-8" />
<meta name="description" content="">
<meta name="keywords" content="">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js" charset="UTF-8"></script>
</head>
<body>
<script>
function send(){
$.ajax({
url: "a.php/",
type: 'GET',
success: function(res) {
var myVars = JSON.parse(res);
console.log(myVars[0].buyprice);
$('#currentbuyprice').html(myVars[0].buyprice);
$('#currentsellprice').html(myVars[0].sellprice);
}
});
}
setInterval(function(){ send() }, 3000);
</script>
currentsellprice:
<div id="currentbuyprice">
</div>
currentsellprice:
<div id="currentsellprice">
</div>
</body>
here the minimal part of the server
<?php
$out = "[";
$out .= '{"buyprice":"'. time(). '",';
$out .= '"sellprice":"'. time()/2 . '"}';
$out .="]";
echo $out;
?>
You can find a lot of information related with this topics (ajax and json) in internet.