Is it possible to receive ajax response without PHP echo - php

php
<?php echo "registered successfully" ?>
Js
success : function (response) {
alert(response);
}
The above could would print hello upon success and I want to redirect the user only if a condition is true.
I could use if (response == registered successfully) {then redirect}
But what if I don't want to echo anything and just redirect the user, could i use something like return "yes"; and use that in success function's if condition. Is there something else I can use instead of echo ?

Yes, you can return an empty string. In the JavaScript side, check that response.status is 200 (indicating a successful response).
You could also have PHP return a 204 No Content response:
http_response_code(204)
return;

I usually just kill or echo echo ("1"); when the code executed successfully on my ajax handler page.
success : function (response) {
if (repsonse.trim() == "1"){
alert(response);
}
}

You can just redirect with js after the ajax function, if you don't need to get anything from php
$.ajax({...});
window.location.replace(anyurl);

Related

Check with jquery if result/echo from PHP starts with "abc"

I am using jquery and ajax to submit forms without page reloading and then depending on the result (whether it is a success or an error) I print the message in two different divs. Since success and error in ajax only checks the client/server connection I echo some stuff from PHP when query succeeds and depending on that I condition what to do with the message. Jquery/ajax part looks like that (normally I use two different divs, but to simplify the example I will use alerts):
success: function (result) {
if (result == 'success') {
alert("Success!");
} else {
alert("There was an error.");
}
},
This works perfectly, but I would like to improve its usability.
Now the question is: can I use in if (result == part something like str.match? For example if there were some problems running the query I would echo in php echo "Error: >error description here<"; Could I then somehow use str.match(/^Error/) in my if condition and echo the entire message?
Don't use string matching for this task. Use HTTP response codes - that's what they're there for! The http_response_code function in PHP is designed for this exact purpose:
<?php
if ( /* error condition */ ) {
http_response_code(400); // "Bad request" response code
echo 'Invalid parameters';
}
else {
echo 'Success'; // response code is 200 (OK) by default
}
Then you can use jQuery's done and fail callbacks to handle the two cases separately:
$.ajax(url, params)
.done(function(response) { alert('all good: ' + response); })
.fail(function(response) { alert('error: ' + response); })
To check if the message starts with Error: you can use indexOf:
if (result.indexOf('Error:') === 0) {
// Starts with `Error:`
}
indexOf will return the index starting from 0 where Error: is found in the result string.
Reference: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf
The indexOf() method returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex. Returns -1 if the value is not found.
to answer the 'improve' part of your question i would do some JSON.
php:
//Your code here and create an associative array like so:
if($errors){
$data(
'results'=>'errors',
'message'=>'it failed'
);
}else{
$data(
'results'=>'success',
'message'=>'it worked'
);
}
echo json_encode($data);
and then your js would be somthing like:
success: function (result) {
if (result.results == 'success') {
alert(result.message);
} else if (result.results == 'errors' {
alert(result.message);
}
},
related : http://www.dyn-web.com/tutorials/php-js/json/array.php#assoc

Ajax does not return specific data from php

This ajax code posts the variables and displays $('#data').html(data); which is been eco-ed in php.-which works
$.post('login.php',{username:username,password:password},
function(data)
{
$('#data').html(data);
if (data=='login'){
alert("sucess");
}
});
However the problem lies on the next line which does not work:
if (data == 'login') {
alert("sucess");
}
This code is supposed to show a dialog box if the data == login
I have looked through different tutorials and this code is supposed to be working but its doesn't for some reason.
Thanks!
You can simply put JSON data Type and use json array as response..
$.post('login.php',{username:username,password:password},
function(data)
{
if (data.status=='login'){
$('#data').html(data.status);
alert("sucess");
} else{
alert('not login');
}
}, 'json');
And in your PHP
<?php
#.. put any code before that response because after it you must put exit.
# No other data except it must be sent! Else you will break it..
echo json_encode(array('status'=>'login'));
exit();
data holds the return result of the response of login.php.
In your case it probaly returns html, like <h1> welcome user x</h1> (I don't know what your code returns so it is an exampe).
If that is the case, you code should check if that is valid. I suggest using JSON. Your login.php checks the login data. If the login attempt is valid you return login: true; And redirect the user.
When in valid just return the data errors and show them with jquery.
Use this code, if your response fails you will get proper alert.
var jqxhr = $.post("login.php", {username : username, password : password}, function(data) {
alert("success" + data);
console.log(data);
},'text')
.done(function() { alert("second success"); })
.fail(function() { alert("error"); })
.always(function() { alert("finished"); });
else you will get alerted by "succes" and your data.
More information how to use this function you can find on http://api.jquery.com/jQuery.post/
To be sure it works. Put in login.php
<?php
echo 'ajax works';
exit;
?>
You use old functions that will be removed. Use PDO or other engine.
Your code is not secure. SQL Injections are possible.

How can I echo a message and return a code to AJAX from PHP

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

Ajax request sent fine but i didnt get the response

I make an AJAX request like this
$.ajax({ type: "POST",url: "<?php echo site_url('home/view_most'); ?>",async: true,data: "view=most_booked", success: function(data)
{
if(data != 0)
{
$("#view_most").html(data);
}
else
alert("Error");
}
});
In controller i get through
public function view_most()
{
$view_most = $this->input->post("view");
}
The response that ajax request is what server echoes so you must echo some value to get the response and handle the response in your success function. In your case does not echo anything thats why you are not getting any response. For example:
public function view_most()
{
$view_most = $this->input->post("view");
echo '0';
}
Try this and you will get 0 as response.
not too familiar with the php codeigniter platform but I think you are not returning any data and that is why you dont see any data.. I am guessing you need to do something like the following at the end of your action code.
$this->load->view(viewName);
Thus your action code should be
public function view_most()
{
$view_most = $this->input->post("view");
$this->load->view($view_most);
}
Here is a quick introduction of AJAX on codeigniter: http://mrforbes.com/blog/2009/01/a-quick-code-igniter-and-jquery-ajax-tutorial/

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.

Categories