Can't echo Ajax variable pass - php

I'm passing 2 variables with ajax to the same .php file. I see them in the console.log but I can't seem to echo them. I already tried several things I found in other questions but it doesn't seem to work. What do I need to add/change?
My code:
<script>
$(document).ready(function () {
$("#slider").bind("valuesChanged", function (e, data) {
$.ajax({
type : "POST",
url : "../wp-content/themes/twentytwelve/fields/test.php",
data : {
minValue : data.values.min,
maxValue : data.values.max
},
cache : true,
async : false,
success : function (data) {
console.log(data);
},
error : function (xhr) {
alert('fail')
}
});
});
});
</script>
and the php part:
<?php if ( $_POST ) {
echo $_POST['minValue'];
}
?>
Btw: it only passes the first value (minValue) and not the other one. How to pass them both? Thanks!

Maybe by printing both values?
<?php
if (!empty($_POST)) {
echo $_POST['minValue'];
echo $_POST['maxValue'];
}
?>

Can you see your request details in the Debug panels like Firebug in FF or (I don't know how it called) in Chromium-based browsers?
Are there all the passed data?
If no then the error in JS.
Also print out the whole POST data on server side to see the POST content.

To pass more values try something like this on php side:
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . "GMT");
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
header("Content-type: application/json");
echo json_encode(array(
'a' => 1,
'b' => 2
));

Related

Send html answer from PHP to Ajax

Here is what I'm trying to do:
I use an Ajax call to select messages from my database, I echo the content in my PHP and i try to get the echoed html in the Ajax success. But it does not work. Here is the code.
JQUERY:
function SelectMessages()
{
console.log("Selecting messages");
console.log("Talk = " + talk);
$.ajax({
url: "select_messages.php",
type: "GET",
data: "talk=" + talk,
success: function (html) {
alert(html);
console.log("In success");
$("#message_box").prepend(html)
},
error: function (html) {
alert(html);
console.log("In error");
}
});//ajax()
}//SelectMessages()
PHP:
<?php
//SELECTING MESSAGES
require 'dbconnect.php';
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
if ($_GET['talk'] != "") {
$request = $bdd->prepare('SELECT AUTHOR,CONTENT FROM MESSAGE WHERE TALK = :talk');
$request->execute(array("talk"=>$_GET['talk']));
while ($data = $request->fetch(PDO::FETCH_ASSOC)) {
echo' <p> '.$data['CONTENT'].'</p>';
}
}
?>
Using this code, I get "In error" displayed on the console and the code in the alert is "[object Object]". However, the status of my query is "OK" in my browser and the echoed result in the network window is the one expected with all the right values of messages.
I just don't understand why I get through the error instead of success.
Please do not mark this as a duplicate as I have already checked and tested the Ajax/PHP solutions and did not get any result.
In your php file you have set content type header as follows
header('Content-type: application/json');
but normally echoed the response as plain text/html. Either you have to send the response in json.
echo json_encode($data['CONTENT']);
Or remove content-type header as json.

session variable cannot be access inside a dynamic javascript file

I know the my question is weird , but it is my situation. I am calling a javascript with
<script src="js/jscript.php"></script>
And in the other hand i am writing javascript inside jscript.php
<?php
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past
header("Content-Type: text/javascript");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Pragma: no-cache");
?>$(document).ready(function(){
....
....
....
alert('hello world!');//all my javascript stuff
<?php
echo $_SESSION['user_id']; //echo nothing
echo $_SESSION['user_email']; //echo nothing
?>
});
And then i tested with my browser , file calling and those call like alert('hello world!') have no problem but until i try to access session variable from jscript.php , its all empty ... I did set those variable correctly
I'm not sure that can work.
I think a better way would be making an ajax call to a PHP page, getting back the data in whatever form you want (json, or just echo $var ...) and then do something with it.
ex with jquery:
<script>
$.ajax({
url: 'mypage.php',
}).done(function(msg) {
// Do something with msg here
});
</script>
and mypage.php could be like :
<?php
$response = array();
$response['user_id'] = $_SESSION['user_id'];
$response['user_email'] = $_SESSION['user_email'];
echo json_encode($response);
?>
When the ajax call is made, the php page will create an array, fill it with the session variables you need and return it to your script in a json form with json_encode.
You get it as a var in .done method and do whatever you need with it.
Adding a session start a very start of jscript.php solved my problem
session_start();
hope its help others.

JSONP data in PHP to JS

I'm using JSONP to dynamically add data into my Android Phonegap app. Since Phonegap 2.5 (and upwards) allows application cache, I would like to use that. Only problem is that at this moment, my data is in a php-file. I read that data from a php-file cannot be cached by the cache manifest, so I'm thinking about changing it to js or something. Any idea how I would do this? I already tried a lot of tutorials on JSONP, but the only way I can get JSONP to work is in PHP. They are also quite vague about how I should save my data file (currently called home.php).
home.php
<?php echo $_GET["callback"] ?> (
[
{
"expo":"pit",
"datum":"05.06.2011 - 05.06.2016",
"img":"images/pit_home.jpg",
"link":"exp1_index.html"
},
{
"expo":"Space Odessy 2.0",
"datum":"17.02 - 19.05.2013",
"img":"images/so_home.jpg",
"link":"exp2_index.html"
}
]
);
script in index.html that calls data from home.php
<script type="text/javascript">
$.ajax({
type: 'GET',
jsonpCallback: 'jsonCallback',
contentType: 'application/json',
dataType: 'jsonp',
url: 'http://mllsdemode.be/Ex-cache/home.php',
success: function(json) {
var $home = $("#home");
$home.empty();
$.each(json, function(i, el) {
$home.append("<td><div class='dsc'>" + el.expo + "<br><em>" + el.datum + "</em></div></td>");
});
},
error: function() { alert("Error reading jsonP file"); }
});
</script>
Well, if I understood well, this is cached, you want it to be cached but not to develop? Then add some headers to develop!
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
To easily forge your JSON, you can use Simple JSON for PHP, it allows you to build complex JSON/JSONP.

jQuery POST handling errors

Explanation
I am sending a POST, and in PHP I am checking if username already exists in database.
If yes, return an error.
But the thing is, I can't use the same function(data) because I want the error to be located in another div.
$.post("events.php?action=send", { data : $(this).serialize() }, function(data)
{
$("#processing").html('');
$("#comments").html(data);
});
Problem
I can't have two variables in anonymous function, like function(data, error), then how am I supposed to fetch the 'error' PHP printed e.g 'User already exist's in database', and then put it in the #errors div?
It depends on how you are handling the error in your PHP code.
In order to even end up in the error handler you need to set the HTTP statuscode to "5XX".
What you probably want to do is to serialize an error object in case the user already exists, and handle it in the success handler like you are doing now:
PHP:
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
$data = array('error' => 'something went wrong');
echo json_encode($data);
JS:
function(data){
if(data && data.error){
//there was an error, handle it here
console.log(data.error);
} else {
//do something else with the user
console.log(data);
}
}
In PHP you can return json error, like print '{"error":'.json_encode($error).'}' and then, in your js put in desired div
$.post("events.php?action=send", { data : $(this).serialize() }, function(data)
{
$("#processing").html('');
$("#comments").html(data);
$("#error").append(data.error);
});
I suggest you to return data as a json string from your server. If you do that, you can get an object from $.parseJSON(data);
// In your php code
$result = new stdClass();
$result->userExists=false;
echo json_encode($result);
Now inside your anonymous function:
// Javascript
data = $.parseJSON(data);
console.log(data);
if (data.userExists) alert("User exists!");

How to stop the results of a jquery php load being cached

I have a new problem which MUST affect practically every person who uses AJAX. I have a HTML/JavaScript page which (using a jQuery call) loads a .php into my page - but it seems to cache the results and often just returns the cached information rather than re-running the PHP script.
The code below is how I'm trying to overcome the problem (thanks bazmegakapa for the code - I've just tried to add the cache:flase bit - but it doesn't seem to work).
$(document).ready(function() {
cache: false
$('#selecthere').load('/temp/php_script.php', function () { //callback
$('select', this).change(function () { //catch onchange event of select
//call your function here, pass the selected value
initialize($(this).val());
});
});
});`
Your php_script.php file should send the correct headers to prevent caching.
<?php
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
?>
Just add a random number to the end
var random = Math.random() * 10;
$('#selecthere').load('/temp/php_script.php?r=' + random, function () {
It looks like you are doing the cache: false wrong.
$(document).ready(function() {
$.ajax('/temp/php_script.php',
{
cache: false,
success: function(result) {
$('#selecthere').html(result);
}
}
);
});

Categories