Ajax returns with PHP - php

Alright so I am trying to put this thing together, but I do not understand what is the problem with this code. I am basically trying to return false in case name exists in the database, but no matter what ajax will just pass it as a "success"
Here is the code:
Running the
function checkName(username) {
$.ajax({
url:"assembly/handler.php",
type:"POST",
data:{func:"run_namecheck", user_name:username},
success:function(data){
return true;
},
error:function(data) {
return false;
}
});
}
The code is executed perfectly and it actually passed all the things it needs, and the PHP function does get called.
PHP function bellow.
public function nameExists($name) {
$handler = new sql();
$sql = $handler->connect();
$sql->real_escape_string($name);
$name_final = ucfirst($name);
$result = $sql->query("SELECT ime FROM users WHERE ime='".$name_final."'");
if($result->num_rows != 0) return true;
else {
$handler->log_write($name, "login_fail","NULL");
return false;
}
$sql->close();
return false;
}
Now the problem is success and the error. No matter what it will always be success. It doesn't like pay attention at when I return FALSE from the PHP at all and such.

AJAX calls are literally just an HTTP request, like any other HTTP request. You're not directly "executing" PHP code when you make an ajax call, you're doing an HTTP request to the server, which (eventually) executes a PHP script on your behalf.
That means any return from the PHP code are completely invisible to Javascript.
Only OUTPUT from PHP will ever be seen by Javascript, which means you need to echo that data, not return it.
And note that any HTTP response from PHP is also literally plain text. Any output you perform in PHP will be converted to text, which means that boolean false you're trying return will be converted to the string equivalent of a boolean false - an invisible zero-length string.

"error" condition in your js code is only for bed requests, like 500, 404 etc.
return a json { error: true } or something like with and use it in your js
success:function(data){
if(data.error) {
// do...
}
},

As far as I can see your code, you're returning nothing to client. You shall return some data that represents the boolean value about the user existence. For instance:
// PHP server-side
if( nameExists( $name)) echo "T";
else echo "F";
that will return value can then be captured by the data parameter in your AJAX function for success and be tested about the server answer.
// Javascript in client
success:function(data){
if( data === "T") return true;
else return false;
},
Hope I can help!

instead of return from php you need:
echo "True" or "false"
to on javascript side:
function checkName(username) {
$.ajax({
url:"assembly/handler.php",
type:"POST",
data:{func:"run_namecheck", user_name:username},
success:function(data){
if(data=='true'){
alert("success process");
}else{
alert("fail process");
};
},
error:function(data) {
console.log("error Ajax");
}
});
}

The data transferred between the client and the server is always text. You need to make sure that the client and server know how the client should deserialize the text. So you might return one of four things:
HTML (if it's going to populate page elements)
JSON (if you want a lightweight, fast way to send data to the client)
XML (if you want a heavier-weight, fast way to send data to the client)
Plain text (for whatever you want, really)
What the client does will depend on what Content-Type header you use in your PHP page.
so, use a header in PHP, for eg:
header('Content-Type', 'application/json');
...and the return this text from it:
{"success": true}
or
{"success": false}
I hope it will help.

Related

JQuery AJAX if-else not working

The return data for this one as I investigated is "authenticated" which means the if statement should take effect. However, to reasons I know not it goes directly to the else part of the statement making the data false even if it's true. Like "authenticated"=="authenticated". It ignores the if part and I don't know why.
function login_admin_user() {
username = $("#ad-username").val();
password = $("#ad-password").val();
$("#button-login").val("Logging in...");
$.post("ajax-login.php", {
username: username,
password: password
}, function (data) {
if (data == "authenticated") {
/* Execute if authenticated */
$("#box-login-confirmed").fadeIn("slow", function () {
$("#button-login").val("Login");
})
.delay(1000)
.fadeOut(400, function () {
window.location = "home.php";
});
} else {
/* Execute if invalid login */
$("#box-login-error").fadeIn("slow", function () {
$("#button-login").val("Login");
$("#ad-password").val("");
})
.delay(3000)
.fadeOut(400);
}
});
}
"authenciated"!="authenticated". You are missing a 't'. Also probably your response may contain spaces. So check what is coming in the response.And its better to trim your response before doing the checking. You can use jquery trim function to remove spaces.
Try like
if($.trim(data) == "authenticated"){
//Some code
}
else{
//Some code
}
Why the response contain spaces. You can find the answers here
Space Before Ajax Response (jQuery, PHP)
strange thing, ajax response includes whitespace
Trailing spaces in Ajax response
I have encountered that problem as well. Using $.trim() from the response data would help strange whitespaces to be altered.
The default return type of the $.post method is HTML. So, if you set the return type as JSON and in your PHP file you return a JSON ENCODED value as "authenticated" .. that might work

$.post json request doesn't return any result

Well, another try:
this is all the jquery code i'm using maybe i made something wrong in the code before $.post(); i call the following function with the onclick of the same form...
function setLogin()
{
$('#login-form').submit(function(e) {
e.preventDefault();
//passing form field to vars
var formUsername=$("#login-form #username").val();
var formPassword=$("#login-form #password").val();
//checks on fields lenght
if((formUsername.length<6))
{
$("#ajax-output").html("<div class='error'>Attenzione username troppo breve!</div>");
}
else if((formPassword.length<6))
{
$("#ajax-output").html("<div class='error'>Attenzione password troppo breve!</div>");
}
else
{
$.post(
//the url
'?module=login',
//data got from login form
{
"username": formUsername,
"password": formPassword,
},
//response
function(data){
$("#ajax-output").html(data.reply)
},
//type
"json"
);
}
});
}
i tried with only this code in php file and it still doesn't return anything...
function Login()
{
//just to try
echo json_encode(array('reply'=>'foo'));
}
it still doesn't work...
Are you sure the post is being run in the first place?
Use Firebug! (or chrome's built-in developer tools)
You can use firebug to pick apart every bit of a web page.
It has a "net" tab that shows every request that is made by the browser, including AJAX requests, and their results, headers and contents.
Use it to see if your requests is really being made, and what the result is. Then take it from there.
Make sure that you're setting a header for the content type when responding - the browser may not attempt to use the JSON if it doesn't know it's receiving JSON.
function Login()
{
header('Content-Type: application/json');
echo json_encode(array('reply'=>'foo'));
}

Cross Domain AJAX (getJSON) with long polling?

I was wondering if it's possible to long poll using $.getJSON and what the proper front and back end logic would be.
I've come up with this so far but haven't tested it yet since I'm pretty sure there is wrong and/or missing logic.
Here is the JS:
function lpOnComplete(data) {
console.log(data);
if (!data.success) {
lpStart();
}
else {
alert("Works!");
}
};
function lpStart() {
$.getJSON("http://path.to.my.URL.php?jsoncall=?", function(data) {
// What happens when no data is returned
// This is more than likely since there
// is no fall back in the PHP.
lpOnComplete(data);
});
};
PHP:
$time = time();
while((time() - $time) < 30) {
// only returns data when it's new.
$data = checkCode();
// What would be the proper way to break out
// and send back $data['success'] = false
// so the JS loop can continue?
if(!empty($data)) {
echo $_GET["jsoncall"] . "(" . json_encode($data) . ")";
break;
}
usleep(25000);
}
From what you've got there, the Javascript is going to make multiple requests to the server and each one is going to spin up that infinite loop, and never go anywhere. I'd suggest something like: js:
$.getJSON("http://my.site/startAsyncWork.php", null, function(data){
waitUntilServerDone(data.token, function(response){
alert("done");
});
});
function waitUntilServerDone(token, doneCallback){
$.getJSON("http://my.site/checkIfWorkIsDone.php", {"token": token}, function(response){
if(response.isDone){
doneCallback(response);
}
else{
setTimeout(function(){
waitUntilServerDone(token, doneCallback);
}, 1000);
}
});
}
I don't know php, so I'm not going to write sample code for that side, but basically, startAsycWork.php makes up a random token that associates to the request. Then it spawns a thread that does all the work needed, and returns the token back to the response.
When the worker thread is done, it writes the results of the work out to a file like token.dat (or puts it in a cache or whatever).
checkIfWorkIsDone.php checks for the existence of token.dat, and returns false if it doesn't exist, or returns the contents if it does.

How can I "read" a response from the php file I call here using ajax?

I am very new to ajax and jquery, but I came across a code on the web which I am manipulating to suit my needs.
The only problem is that I want to be able to respond to the ajax from PHP.
This ajax POSTS to a php page (email.php).
How can I make the email.php reply back if the message is sent or if message-limit is exceeded (I limit the nr of messages sent per each user)?
In other words, I want ajax to take a 1 or 0 from the php code, and for example:
if(response==1){ alert("message sent"); } else { alert("Limit exceeded"); }
Here is the last part of the code: (If you need the full code just let me know)
var data_string = $('form#ajax_form').serialize();
$.ajax({
type: "POST",
url: "email.php",
data: data_string,
success: function() {
$('form#ajax_form').slideUp('slow').before('');
$('#success').html('<h3>Success</h3>Your email is has been sent.');
}//end success function
}) //end ajax call
return false;
})
Thanks
The success function of an $.ajax call receives a parameter, usually called data though that's up to you, containing the response, so:
success: function(data) {
// Use the data
}
(It also receives a couple of other parameters if you want them; more in the docs.)
The data parameter's type will vary depending on the content type of the response your PHP page sends. If it sends HTML, data will be a string containing the HTML markup; if your page sends JSON, the data parameter will be the decoded JSON object; if it's XML, data will be an XML document instance.
You can use 1 or 0 if you like (if you do, I'd probably set the content type to "text/plain"), so:
success: function(data) {
if (data === "1") {
// success
}
else if (data === "0") {
// failure
}
else {
// App error, expected "0" or "1"
}
}
...but when I'm responding to Ajax requests, nine times out of ten I send JSON back (so I set the Content-Type header to application/json), because then if I'm using a library like jQuery that understands JSON, I'll get back a nice orderly object that's easy to work with. I'm not a PHP guy, but I believe you'd set the content type via setContentType and use json_encode to encode the data to send back.
In your case, I'd probably reply with:
{"success": "true"}
or
{"success": "false", "errMessage": "You reached the limit."}
so that the server-side code can dictate what error message I show the user. Then your success function would look like this:
success: function(data) {
var msg;
if (typeof data !== "object") {
// Strange, we should have gotten back an object
msg = "Application error";
}
else if (!data.success) {
// `success` is false or missing, grab the error message
// or a fallback if it's missing
msg = data.errMessage || "Request failed, no error given";
}
if (msg) {
// Show the message -- you can use `alert` or whatever
}
}
You must pass an argument to your "success" function.
success: function(data)
{
if(data == '1')
{
$('form#ajax_form').slideUp('slow').before('');
$('#success').html('<h3>Success</h3>Your email is has been sent.');
}
}
And in your php file, you should just echo the response you need
if(mail())
{
echo '1';
}
else
{
echo '0';
}
Anything you echo or return in the php file will be sent back to you jquery post. You should check out this page http://api.jquery.com/jQuery.post/ and think about using JSON formatted variables to return so like if you had this in your email script:
echo '{ "reposonse": "1" }';
This pass a variable called response with a value of 1 back to you jquery script. You could then use an if statement how you described.
just have email.php echo a 0 or 1, and then grab the data in the success event of the ajax object as follows...
$.ajax({
url: 'email.php',
success: function(data) {
if (data=="1"){
...
}else{
...
}
}
});
what you do is, you let your ajax file (email.php) print a 1 if successful and a 0 if not (or whatever else you want)
Then, in your success function, you do something like this:
function(data) {
$('form#ajax_form').slideUp('slow').before('');
if(data==1){ alert("message sent"); } else { alert("Limit exceeded"); }
$('#success').html('<h3>Success</h3>Your email is has been sent.');
}
So you capture the response in the data var of the function. If you a bigger variety in your output, you can set you dataType to "json" and have your php file print a json_encoded string so that you can access your different variables in your response via for example data.success etc.
PHP can only return to AJAX calls, by its output. An AJAX call to a PHP page is essentially the same as a browser requesting for the page.
If your PHP file was something like,
<?php
echo "1";
?>
You would receive the "1" in your JavaScript success callback,
that is,
success: function(data) {
// here data is "1"
}
As an added note, usually AJAX responses are usually done in JSON format. Therefore, you should format your PHP replies in JSON notation.

Getting json on Ajax response callback

I am trying to create a little ajax chat system (just for the heck of it) and I am using prototype.js to handle the ajax part.
One thing I have read in the help is that if you return json data, the callback function will fill that json data in the second parameter.
So in my php file that gets called I have:
header('Content-type: application/json');
if (($response = $acs_ajch_sql->postmsg($acs_ajch_msg,$acs_ajch_username,$acs_ajch_channel,$acs_ajch_ts_client)) === true)
echo json_encode(array('lastid' => $acs_ajch_sql->msgid));
else
echo json_encode(array('error' => $response));
On the ajax request I have:
onSuccess: function (response,json) {
alert(response.responseText);
alert(json);
}
The alert of the response.responseText gives me {"lastid": 8 } but the json gives me null.
Anyone know how I can make this work?
This is the correct syntax for retrieving JSON with Prototype
onSuccess: function(response){
var json = response.responseText.evalJSON();
}
There is a property of Response: Response.responseJSON which is filled with a JSON objects only if the backend returns Content-Type: application/json, i.e. if you do something like this in your backend code:
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode($answer));
//this is within a Codeigniter controller
in this case Response.responseJSON != undefined which you can check on the receiving end, in your onSuccess(t) handler:
onSuccess:function(t) {
if (t.responseJSON != undefined)
{
// backend sent some JSON content (maybe with error messages?)
}
else
{
// backend sent some text/html, let's say content for my target DIV
}
}
I am not really answering the question about the second parameter of the handler, but if it does exist, for sure Prototype will only provide it in case of proper content type of the response.
This comes from Prototype official :
Evaluating a JavaScript response
Sometimes the application is designed
to send JavaScript code as a response.
If the content type of the response
matches the MIME type of JavaScript
then this is true and Prototype will
automatically eval() returned code.
You don't need to handle the response
explicitly if you don't need to.
Alternatively, if the response holds a
X-JSON header, its content will be
parsed, saved as an object and sent to
the callbacks as the second argument:
new Ajax.Request('/some_url', {
method:'get', onSuccess:
function(transport, json){
alert(json ? Object.inspect(json) : "no JSON object");
}
});
Use this functionality when you want to fetch non-trivial
data with Ajax but want to avoid the
overhead of parsing XML responses.
JSON is much faster (and lighter) than
XML.
You could also just skip the framework. Here's a cross-browser compatible way to do ajax, used in a comments widget:
//fetches comments from the server
CommentWidget.prototype.getComments = function() {
var commentURL = this.getCommentsURL + this.obj.type + '/' + this.obj.id;
this.asyncRequest('GET', commentURL, null);
}
//initiates an XHR request
CommentWidget.prototype.asyncRequest = function(method, uri, form) {
var o = createXhrObject()
if(!o) { return null; }
o.open(method, uri, true);
o.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
var self = this;
o.onreadystatechange = function () {self.callback(o)};
if (form) {
o.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
o.send(makePostData(form));
} else {
o.send('');
}
}
//after a comment is posted, this rewrites the comments on the page
CommentWidget.prototype.callback = function(o) {
if (o.readyState != 4) { return }
//turns the JSON string into a JavaScript object.
var response_obj = eval('(' + o.responseText + ')');
this.comments = response_obj.comments;
this.refresh()
}
I open-sourced this code here http://www.trailbehind.com/comment_widget

Categories