This is what am trying to achieve, I have a function in controller that generates a random password and returns the same, on button click I want to capture the generated password and display it in the view (password field). Here is the jquery/ajax call:
$(document).ready(function(){
$("#generate_password").click(function(){
$.ajax({
type: "GET",
dataType: 'text',
url: "http://127.0.0.1/public/admin/content/manufacturers/generate_password",
async:false,
success: function(resp){
alert(resp); //this alerts BLANK
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
});
});
Controller function:
public function generate_password($length = 9)
{
return $password_str;
}
Is this the correct way to call controller method?
Why am I getting blank value on alert, even though when printed in php am getting correct value?
Coz it's in the admin area can that be the reason, don't think so but is there any interference because of tokens?
In most cases, it is going to work okay, however you can use json format(and just json_encode/json_decode will finish the job for you), not sending via GET method and some other modifications.
Are you sure that the url is correct, if you open it in your browser, what happens?
You have to echo the variable in your function in place of return. Because return returns the value to the caller whereas echo sends something to the browser. JavaScript will only understand data which is sent to the browser. So, edit your function code as follows:
public function generate_password($length = 9)
{
echo $password_str;
}
On the other hand you should be doing this over HTTPS rather than HTTP as mentioned by #rodamn
Well strange but changing the url from:
url: "http://127.0.0.1/public/admin/content/manufacturers/generate_password",
to this:
url: "generate_password",
did the trick and everything is working fine now :)
Thanks everyone for their valuable inputs.
Related
Hey guys I am building an application in which I send input value from a text box via AJAX to a controller function and then return what I send back to the user (I am developing an instant search, this is a first step).
The AJAX links to the method fine however I am having problems returning the information. I receive no error messages, the problem is that the return string is BLANK.
I receive [you wrote ] rather than [you wrote WHATEVER I IN PUTTED ]
Any help greatly appreciated.
view_index.php
function search(){
var term = document.getElementById("mainsearch").value;
$.ajax({
type: "POST",
url: "<?php echo base_url('index.php/site/search/')?>",
data: term,
cache: false,
success: function(html){
alert("you wrote " + html);
}
});
controller_site.php
function search(){
$gotcha = $this->input->post('term');
return $gotcha;
}
The data: parameter accept a key : value json to pass to the POST, as the json array key will be your $_POST key
Try with this:
$.ajax({
type: "POST",
url: "<?php echo base_url('index.php/site/search/')?>",
data: {'term': term }
cache: false,
success: function(html){
alert("you wrote " + html);
}
});
You didn't send your data correctly, so PHP has nothing to process, and you end up sending back nothing:
data: term,
POST/GET requests MUST be in key=value format, and you're sending only the value portion. Try
data: {foo: term},
and then
$gotcha = $this->input->post('foo');
You need to change return to echo as AJAX response works on whatever echo from called function.
So, you can code like :
function search(){
$gotcha = $this->input->post('term');
echo $gotcha;
}
or
function search(){
echo = $this->input->post('term');
}
The responseText property returns the response as a string, and you can use it accordingly
It is generally a bad idea to return HTML from your controllers. Instead try to just manage data server-side wise and do all the frontend on the client side.
Now, for the error:
The success callback takes 3 parameters
You need to pass key-value pair in the data argument of the .ajax call
Make sure you handle errors on your controller appropriately because if something goes wrong you'll get an html document as a response from CodeIgniter and you'll spend a lot of time debugging javascript to find out that the error was actually server-side
1 the callback:
Your success callback function should look like this:
function (data, status, response) {
}
Where:
data is whatever you are echoing from your controller's method. You'll probably want JSON.
status Will tell you if the HTTP response message (e.g. "Not Found" is the status for a 404 code, "success" for a 200 code)
response is the jquery wrapped XmlHttpRequest object that gives you a handful information of the transaction, for example response.responseText would give you whatever you outputed from PHP, response.responseJSON would give you a JSON object if you echoed a json encoded object, etc.
Why should you care? Because those extra parameters will let you decide if something went wrong on your backend so you can handle the situation client-side not leaving the user wondering if you app just don't work. Worse, giving the infamous red cross on the status bar of the browser.
If you set the dataType parameter of the jQuery.ajax function then you can explicitly tell jQuery what kind of data you are expecting to be retrieved from the server on data parameter from your callback.
2 the sent data
As said, you need to either pass value-pairs or a URL encoded string. If you intend to use GET then you can pass the URL encoded string, but that means you have to have arguments on your CI function like:
function search($term)
And then CI automatically routes the incoming parameters. But since you want to do POST then you'll want to effectively get the values with $this->input->post("name")
If you have your input inside a form, or several fields that you need to send, then its easier to just serialize the form:
$.ajax("url", {
type : 'POST',
data : $('#form').serialize(),
dataType : 'json',
success : function(data, status, response) {} error : function(response, status error) {}});
3 handle errors
If you are relying on AJAX then make sure that you return some sort of error or warning so you can catch it client side:
function search() {
$term = $this->input->post("term")
if($term == FALSE) {
//return a 404 so that you can catch .error on jquery
} else {
echo $term;
}
}
Do a research on RESTFul apps. It'll help you a lot understanding that. this is a good starting point and although your question was not exactly related to this, it is a good practice to have separate layers on your application so that you just consume data from your backend, handle situations and then just react accordingly on the frontend, that is, you just use javascript to either send, receive and list data. If you are using CI or any other MVC framework then you should not really be generating HTML on your controllers, thats what the views are for.
I am using $.ajax to get a JSON response from a php script. if i log the data variable from the $.ajax success function it outputs a properly formatted JSON object, however when I try to access properties of the data var it's undefined. here is the php the is being sent back:
echo json_encode(array("status"=>true, "success"=>"Login Success", "message"=>"You have been logged in successfully."));
and here is my ajax call:
$.ajax({
type: "POST",
data: {
login: true,
username: $('#login-username').val(),
password: $('#login-password').val()
},
async: false,
url: "./php/client-login.php",
success: function (data) {
console.log(data.status);
if (data.status) {
console.log(data.success);
displayModal(data.success, data.message, "./js/login-modal-code.js");
} else if (!data.status) {
displayModal(data.error, data.message, "./js/login-modal-code.js");
}
},
error: function (jqXHR, status, responseText) {
console.log(status);
}
});
if i add the dataType: "json" option to the $.ajax call I get a parse error and if i try to do $.parseJSON(data); to access the data in the data var I get and unexpected token error. I'm not really sure what I'm doing wrong, I've used this setup before and it always has worked before but for some reason it isn't now. anyone see where i've gone wrong?
EDIT: forgot to mention here is the response from the php script:
{"status":true,"success":"Login Success","message":"You have been logged in successfully."}
EDIT 2: Here is a screen of my console. the top .length call is the json that was logged from console.log(data) and the bottom one is from the response in chrome dev tools network tab for the response from the php script. they line up perfectly yet the second is showing a length of 93, how can i fix this?
I was reading on jQuery Docs and found that "dataType: jsonp" does not work with sync request, and you're making this kind of request since you have async: false. Turning it on may solve your problem.
Also, give a look at the docs.
Good luck!
So I figured out a workaround for this problem, first I did JSON.stringify on the data followed by JSON.parse and lastly $.parseJSON() to get a javascript object to work with. Not sure why there are 2 invisible characters being added between when it leaves the php script and reaches the $.ajax call so if anyone knows why let me know
I've got an AJAX script in my index.php of my CI application. I am just trying to return a simple string at this point for my testing. I'm using the following code for this:
<script>
$(document).ready(function() {
$.ajax({
type: 'POST',
url: 'index.php/loader/opc_client',
dataType: 'json',
cache: false,
success: function(data) {
console.log(data);
$('#opc-results').html(data.test);
}
});
});
</script>
The url in this call is a standalone file with it's own controller. When I access this file directly in the browser it's loaded normally and returns expected results. Following is my PHP code:
<?php echo json_encode("test"); ?>
I can see the post results in Firebug after the function is fired but the Firebug window just displays "an empty string" under the POST in console view.
Any clues? I'm not understand this...
UPDATE: If I console.log('success') in the success parameter of the AJAX call, it logs it properly so for some reason data is empty
you shouldn't just json_encode a string although technically php can deal with a string as an array but I guess in this case things get weird. Just wrap it in an array, and when youre done testing you'll probably be better off using key value pairs as it makes thing on the client side easier to deal with, ie obj.property.
try echo json_encode(arrray('test'));
In this script, using php's return will not work, whereas echo will. Thing is, if I use echo, and someone where to access the page directly, they would be able to see the output without the formatting.
<script type="text/javascript">
$(function() {
$('.callAppend').click(function() {
$.ajax({
type: 'GET',
url: 'recent.php',
dataType:'HTML',
cache:false,
success: function(data){
console.log(data);
//}
},
});
return false;
});
});
</script>
This the php script
<?php
$feedback = 'Hello this is the php page';
return $feedback; //Use echo, and all works fine.
?>
return is used for returning a value from a function to another piece of PHP code.
jQuery is not part of the execution of the PHP code on the server, so it has no idea what is really going on server side. jQuery is waiting for the rendered server response, which is what echo provides.
This SO answer provides a solution to only allow an AJAX script to be called by that type of request:
Prevent Direct Access To File Called By ajax Function
Even though it is checking for 'XMLHttpRequest', someone could make this type of request from something else other than you weboage.
When you use AJAX to load a URL, you're loading the raw output of that URL. Echo produces output but return doesn't. You'll need to do some reason on the subject of OOP to understand what the purpose of return is.
Echo is the correct way to send output.
I am trying to use an ajax 'POST' call through the jquery $.ajax function to send data to a php file. For some reason the callback is a success but the data is not getting to the php file. Here is an example of the code:
In JS file:
$.ajax({ type: "POST",
url: "setData.php",
data: "myPOSTvar=myData"
success: function(){ alert("Data Saved"); }
});
In php file:
$var = $_POST['myPOSTvar']
...
$var ends up with a default value instead of the data it is sent.
Any ideas?
Sorry about the syntax errors...at work right now and don't have my code in front of me...the syntax is all correct in the actual script, just typed to quick when posting here...
Try this and see if you get any info.
$.post("setData.php", { myPOSTvar: "myData" },
function(data){
alert("Data saved");
});
I doubt it's a success, the url should be a string : url: "setData.php" .
I really doubt that piece of JS code is working as it should. POST and setData.php should be enclosed with quotes. Right now you should get some errors because "POST" variable is not defined and then because you're accessing a "php" property on a non existent object "setData".