My Ajax application was working fine, until I implemented an if statement in the PHP script... then like a contagious disease it seems that if I do anything to the data in PHP it returns nothing back to the Javascript layer.
All I can do is echo the data back...
For instance the query string I'm sending to the PHP reads...
index.back3.php?form=login&json={"email":"mo#maurice-campobasso.com","password":"asdasdfas"}
and I know its getting there because in the simplest debugging PHP file (index.back3.php) that I created all I have is a simple echo statement... and it never fails to send back the data to the Javascript file.
when index.back3.php reads
<?php echo $_GET[json]; ?>
the alert that I have triggering off in the javascript reliably spits out the json string.
also when it reads
<?php echo $_GET[form]; ?>
when I get any more complicated than that nothing comes back to the javascript. Even a simple concatenation...
<?php echo ($_GET[form] . $_GET[json]); ?>
...returns nothing!
A simple if...else statement also returns nothing.
<?php
if(!isset($_GET[form]) {
echo "no!";
} else {
echo "yes!";
}
?>
And this important operation also...
<?php
$array = json_decode($GET[json], true);
var_dump($array);
?>
returns nothing.
OK... so just to make sure everything is above board here is my Ajax output function in the Javascript layer.
function responseAjax() {
if (myRequest.readyState == 4) {
if(myRequest.status == 200) {
var foo = myRequest.responseText;
alert(foo);
} else {
alert("An error has occured: " + myRequest.statusText);
}
}
}
Can someone please explain what's going on? I'm truly stumped.
if(!isset($_GET[form]) {
echo "no!";
} else {
echo "yes!";
}
?>
you are missing a closing parenthesis in the if statement. And as said a few times before, put quotes around your array keys.
While in development, you should also maybe turn on error_reporting to E_ALL. it helps find out what a small error might be.
$_GET['form'] is the right way.
and using form as variable name is not at all good.
use anyother variable and pass $_GET['formname'].
Try to access the php page directly through url and pass the parameters , check first the php
return error or its working propelry.
You can use PHP , jquery and ajax in simple ways.
try to find .post or .get methods in jquery
http://api.jquery.com/jQuery.post/
$.post('ajax/test.html', function(data) {
$('.result').html(data);
});
I managed to sort it out, it had to do with a line of code which I omitted from this post, because I thought it was reduntant. The full version of the function went like this.
function responseAjax() {
if (myRequest.readyState == 4) {
if(myRequest.status == 200) {
var foo = myRequest.responseText;
var cookieData = eval("(" + foo + ")"); //this was the problem!!
alert(foo);
document.cookie = 'email =' + cookieData.email + '; path=/';
document.cookie = 'firstname =' + cookieData.FirstName + '; path=/';
} else {
alert("An error has occured: " + myRequest.statusText);
}
}
}
It was the 'var cookieData' line... though I'm not sure why.
Related
I am trying to show some data using jsonp and jquery, however I am missing something.
On the php file, I save into mysql, and I get from the database a field to send it back through the $back variable.
After this, I callback this and echo the $back I got from the DB.
In client side I get undefined . What am I missing here?
function showPopup(data) {
setTimeout(function () {
alert(data);
}, 1000);
}
function group(){
$.getJSON("http://domain.comhandler.php?type=group&callback=i&cookie="+ y, showPopup());
}
server side
echo $callback . "(" . json_encode($back) . ")";
Your not calling your call back correctly you can use
$.getJSON("http://domain.comhandler.php?type=group&callback=i&cookie="+ y, showPopup);
note I have removed the ()
or
$.getJSON("http://domain.comhandler.php?type=group&callback=i&cookie="+ y, function(data){ showPopup(data); } );
I'm trying to achieve the following:
when you click on H1, JQuery GETs info for certain key from the server and sends it back to user, where jquery is showing prompt with this info. PHP in server.php
$link = mysql_connect("mysql.hostinger.com.ua", "_my_login_", "_my_password_") or die("NOOO!");
mysql_select_db("u994953720_db");
$key;
if(isset($_GET['Key'])) {
$key = $_GET['Key'];
$selected = mysql_query("SELECT * FROM `Table` WHERE `Key`='".$key."'", $link);
$selected_row = mysql_fetch_array($selected);
if($selected_row!=null){
$response = array(
"result" => $selected_row['Value']
);
echo json_encode($response);
exit;
}else{
$response = array(
"result" => "Nope."
);
echo json_encode($response);
exit;
}
}
jQuery in the main page:
$('h1').on('click', function () {
$.ajax({
type: 'GET',
url: '/server/server.php',
data: {
'Key': 'Roman'
},
success: function(data) {
alert(data.result);
},
dataType: 'json'
});
});
But I don't have any effect. Could you guys show me how to fix my mistakes?
P.S.Working not working example
P.S.I am only starting learning PHP, so there can be some really stupid mistakes.
UPDATE: I've done everything like you guys said (I don't care about safety yet), but it still doesn't work. In the console there is the following message:
XHR finished loading: GET "http://site0.hol.es/server/server.php?Key=Roman".
When I include error method to ajax:
error: function(requestObject, error, errorThrown) {
alert("request objqect: " + requestObject + " . Error: " + error + " . Error thrown: " + errorThrown);
}
, there is an alert: parsing error, unexpected token <
UPDATE 1: I've understood, that my while page is being writed to json result, like here, but I don't have any other echo-s, how can it happen?
UPDATE: I've figured out, that PHP was sending the whole page what it was placed in, so, I simply removed that) But thank you for your comments about safety, I'll correct it
By looking at your site I can see that you are returning HTML + JSON. Try throwing an exit after your echo:
echo json_encode($response);
exit;
Also - you are not handling a no data state at all. You should be do something like:
if(isset($_GET['Key'])) {
// your valid request code
} else {
echo json_encode(array('result' => false, 'reason' => "You must send a Key"));
}
Furthermore you can debug you php code by hitting the endpoint directly and var_dumping/debugging the code that is run there. For starters, what is the output of $selected_row = mysql_fetch_array($selected); when you go to http://site0.hol.es/server/server.php?Key=Roman
Finally - just little warning, as others have mentioned. You are wide open to SQL injection attacks. Look into using PDO -
What PDO is:
http://php.net/manual/en/book.pdo.php
Why to use it:
http://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059
How to use it: http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers
Heres the issue. I have an an ajax function that is just checking if an email that a user inputs is already used.
The php script that it uses either sends back "true" or "false" strings depending on the result. When i get the response text back, or the "data" variable in the below function, and see if its == to "true" it never passes and always evaluates to false.
This is odd, because when I have printed out the data variable on
screen it shows as "true" when it should, but its just not being shown
as equal to "true" in the if statement. No idea what is happening
here.
AJAX FUNCTION:
function check_email() {
var email = document.sign_up_form.email_first.value;
document.getElementById("email1").innerHTML = ' <img src="loading.gif" width="15">';
$.ajax({
type: "GET",
url: "java_check_email.php",
data: "email="+email,
success: function(data){
if(data == "true"){
document.getElementById("email1").innerHTML = ' <img src="check.png" width="15">';
document.getElementById("email4").innerHTML = '';
}
else {
document.getElementById("email1").innerHTML = ' <img src="xmark.png" width="15">';
document.getElementById("email4").innerHTML = 'Email is already in use<br>';
}
}
});
}
UPDATE:
PHP script looks like this
<?php
include('functions.php');
$email = $_GET['email'];
$query_check = "removed for obvious reasons...";
$result_check = mysql_query($query_check);
if(mysql_num_rows($result_check) == 0){
echo 'true';
}
else{
echo 'false';
}
?>
Also, after calling console.log(data) when the ajax response is received i got a value of "true" in the js console.....
For debugging, try
if (data.replace(/\s+/g, '') == "true") {
...my money is on whitespace outside the <?php ?> tags. Note that if this solves the problem it should not considered the solution - the real solution is to remove the additional whitespace from the PHP script.
The < of the opening <?php tag should be the very first character in the file. For example:
This empty line will be output directly
<?php
^^^^ This whitespace will be output directly
Note also that the closing ?> tag is often unnecessary (as it seems to be in this case) and omitting it completely can help avoid problems like this.
If you want to return a boolean to JS you should simply echo 1 or 0, so you can just do this in the receiving Javascript:
if (data) {
I know this is old but I've had the exact same problem and couldn't fix it. I am realy sure it wasn't a white-space issue but I was able to solve it in a different way.
Maybe it's not the best way (I still want to know why it doesnt work in the usual way), but what I did was echo a 0 (for false) and a 1 (for true)
Then I parsed the data to an Integer, so my code looks like this:
function(data){
var result = parseInt(data);
if (result === 1){
$('#loginresult').html('OK');
} else {
$('#loginresult').html('NOT OK');
}
I hope I can help anyone with this workaround (but a good solution would be better)
All,
I have an AJAX function, that calls a PHP URL through html data type. I cannot use other datatypes for my AJAX requests due to server constraints. I am trying to print a message and also handle scenarios based on the return code. The following code doesn't seem to work. Can you advise?
Here's a simple AJAX call:
$.ajax({
type: "POST",
url: "validateUser.php",
dataType: html,
success: function(msg, errorCode){
if(errorCode == 10)
{
callAFunction();
}
else if(errorCode == 20)
{
callSomething();
}
else
{
doSomethingElse();
}
}
});
PHP CODE:
---------
<?php
function validateUser()
{
$username = 'xyz';
if (!empty($username) && strlen($username)>5)
{
echo 'User Validated';
return 10;
}
else if (empty($username))
{
echo 'Improper Username';
return 20;
}
else if (strlen($username)<5)
{
echo 'Username length should be atleast 5 characters';
return 30;
}
exit;
}
?>
Thanks
Your PHP is a just a function. It is not being called.
Also, you are not sending any data to your PHP file.
what you can do is print them in div something like this.
<div class="errorcode">30</div><div class="errormessage">Username length should be atleast 5 characters</div>
and then in your success function in ajax you can use jquery to parse the response text and use selectors like $(".errorcode").html() and $(".errormessage").html() and get the response. this makes things easy
also looks like you are not posting anything
Remove exit; at the end of validateUser(). It causes the execution of the entire script to stop immediately.
Since this is the last line of validateUser(), there is no need to add return.
Documentation: exit, return
Good day. I am having the following code snippet in init.php.
<?php
include_once("config.php");
include_once(__SITE_PATH . 'view/' . $_REQUEST['page'] . EXT);
$loginobj = new $_REQUEST['page']($_REQUEST['billingentitynuber']);
$text = $loginobj->$_REQUEST['content']();
echo $text;
?>
In Jquery I am having the function Jquery_event.js
$("#entertoapp").click(function()
{
alert($("#btval").val());
$.ajax({
type: "POST",
url: "init.php?page=processing&content=enterintoapplication&btval=" + $("#btval").val(),
success: function(msg) {
alert(msg);
if(msg==1)
window.location.href='index.php?page=processing&content=mycontent';
}
});
});
In processing.php I am having
<?php
class processing
{
public function enterintoapplication()
{
global $billingentityname;
$_SESSION['btval'] = $billingentityname;
echo $billingentityname;
}
}
?>
My problem is I am getting all the parameters in the init.php. But when I call a function I need to get in the processing.php in the enterintoapplication function (i.e. I am expecting btval in the enterintoapplication function). How can I achieve this? I tried to get $_REQUEST['btval'] within the function. But I didn't get.
Try assigning the values to variables, for example this works for PHP 4:
class processing
{
function enterintoapplication()
{
echo "hello";
}
}
$className="processing";
$functionName="enterintoapplication";
$loginobj=new $className();
$text=$loginobj->$functionName();
echo $text;
Paste it here to verify it works: http://writecodeonline.com/php/
Pls,pay attention to "$functionName", here it keeps the "$".
Nevertheless, for security reasons, you should be attentive to what people can do if they change the value "page".
I don't understand your problem correctly, but with some general information, you should get out of this.
$_REQUEST is a superglobal, that means that variable will always be accessible from everywhere within your script. If your problem is you can't find the btval variable that was in your URL, you are doing something else wrong. If your url=http://someUrl/test.php?btval=banana you should always get banana if you evaluate $_REQUEST['btval']. $_SESSION is another superglobal to access the PHP session, and has nothing to do with URL variables.
My guess:
Try changing
$_SESSION['btval'] = $billingentityname;
into
$billingentityname = $_REQUEST['btval'];
In that case, your real mistake was that you've put the two variables in this assignment in the incorrect order. $a = $b means: put the contents of $b into $a.