trouble with json response from php in jQuery.ajax call - php

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

Related

Getting response from Codeigniter controller method using AJAX/JQuery

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.

How to see variable that is echoed from php file - jquery ajax

I'm trying to get echoed variable from php and display on the console. I'm using jquery to send data and I know the backend php file script is working fine. Since I want to see the progress and the backend php script echo out the iteration number while the script is running, I'm trying to see how I can get the echoed variable with jquery and display on the console.
I've tried success, onloading but it doesn't seem to work. Any help would be very appreciated. Thank you!
EDIT
$.ajax({
url: location,
type: 'POST',
data:{
iteration:"10",
readsize:"200",
slimdepth:"3",
sourcedirectory:source,
packagepath:MP
},
dataType:'json',
success: function (response) {
console.log("SUCCESS!");
console.log(response);
},
onInteractive:function (response) {
console.log(response.responseText);
},
complete:function (response) {
console.log(response.responseText);
},
error: function (response) {
console.log("Failure!");
console.log(response.responseText);
}
});
So this is how I send the data and backend php script gets the parameters without problems and it runs. Now I can't see anything until php is done running and then it echo everything. In the backend php script, I have iteration number that I want to check and that is the problem since I can't check while it is running but only it is done running.
From what I could understand from your question probably this is what you are looking for.
You are sending data to PHP file with jQuery post or send:
$.post(file.php, {post}, function(data){
});
If you want to log returned data from php in console you must use console.log() function:
$.post(file, {post}, function(data){
console.log(data)
});
and now data will be logged into browser console.

Sending multiple variables in ajax

I have the following ajax request:
var value = $.ajax({
type: "POST",
url: "url.php",
data: { $(someform).serialize(), something: test_number },
cache: false,
async: true
}).success(function(data){
alert("success!");
}).error(function() {
console.log("FAILED");
});
But it is logging FAILED although the url is right. What happens is that the page refreshes the page and the php query isn't done. I guess there are no errors within the url... any idea on why this happens?
You are kind of mixing methods to send your POST data. You can't serialize a query strong and then also append additional data to it using javascript object construct. You will likely need to manually append the last data element to the query string like this:
data: $(someform).serialize() + '&something=' + encodeURIComponent(test_number),
Of course there could still be a problem on the server-side script which is causing a non-200 HTTP response code (and triggering error handler). You just need to fix this first, and if you still have a problem, debug the server-side issue.

ajax call on CodeIgniter page returns result "an empty string"

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'));

Jquery ajax error - Requests adding GET var

My ajax function has stopped working all of a sudden.
function get_file_info()
{
$.ajax({
type: "GET",
url: "http://localhost/includes/get_file_info.php",
dataType: "json",
jsonp: false,
jsonpCallback: "callbackName",
success: function(data) {
return data;
}
});
}
I did some debugging and found that the ajax request is going to
http://localhost/includes/get_file_info.php?_=1297356964250
I am just would like to know what it is and can be used for, also how to remove so the ajax request is like below so it works again.
http://localhost/includes/get_file_info.php
Many Thanks
If you add:
cache: true,
to your call it will remove the timestamp which is there to always call a different URL's so the browser doesn't cache the result. This is standard for calls except for datatypes script and jsonp.
As others have stated though, it would be good to change the server side to stop turning away anything with GET's, maybe check if the get is a _ and only numeric, if not then turn it away...
The "_=1297356964250" query string is jQuery's method of preventing the URL being cached and returning an old result. Adding this ensures that you're retrieving a new response every time.
This is not the cause of your request breaking down. It must be from another issue. Have you tried logging your response and seeing what it returns?
success: function(data) {
console.log(data);
}

Categories