PHP not sending response text from AJAX call - php

Can't work this one out for the life of me, hopefully I am not doing something stupid but why this is not working is not clear to me.
I have a basic HTML page with a JQuery script that sends the following AJAX call to a PHP script within the same directory.
JQuery:
// Sends the AJAX request
$.ajax({
type: "GET",
url: "process.php",
dataType: "json",
success: function(data) {
console.log(data);
}
});
PHP:
<!-- Ajax request handler -->
<?php
echo json_encode(array('message' => 'AJAX call received'));
exit();
?>
The AJAX call is being made successfully as after debugging it in the console it's status code is 200 and statusText 'ok'. However, I simply cannot get the returned JSON message to show up in the console as it should.
I have double checked the URL and that's fine.
This is the response I get in the console using Jeff Hatz's AJAX Debugger Chrome Extension:
Console Screenshot
Any ideas folks?

You need to remove this line from the top of your PHP:
<!-- Ajax request handler -->
As when you make a ajax call with dataType: 'json' it is not going to parse the response (at all) and then when you do a console.log(data); it is simply empty, no console log.
When you do remove that line, you should instead receive in your Network tab Response:
{"message":"AJAX call received"}
Which then in a console.log(data); you should see:
Object {message: "AJAX call received"}

Related

Controller behaviour with ajax request

I am trying to get a hold on sending data to MySql via ajax and have been watching online tutorials. In the examples, the controller method always seems to end with an echo statement which is returned to the js script. Under other circumstances, if I put an echo statement in a controller method it would be output to the view so why does this not happen after an ajax request?
ajax works with js, and the response by ajax request can only be handle through js.
Reason => after generating ajax response on server, it bounce back to client/browser, where server side language doesn't work, so you need to manage your code/logic through client side language JS in your ajax success block.
$.ajax({
url: 'content/get.php',
type: 'post', // performing a POST request
data : {
data1 : 'value' // will be accessible in $_POST['data1']
},
dataType: 'json',
success: function(data)
{
// success block
}
});

jQuery does 2 loads... and returns 500 error

For some reason my jQuery AJAX request submits the first POST successfully, but then it causes a second GET which does not submit the post data, causing a Index Undefined error. When viewing the logs with Firebug, I see it does the first POST successfully posting the data I want to submit, but then it does a second GET request pulling the entire "SecondPage.php" file without posting any data, overriding the DIV it was set to display in.
Here's the code:
$(document).on('change', '.SubmitRadioButton', function(e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'SecondPage.php',
cache: false,
data: $(this.form).serialize(),
success: function(html) {
window.alert('Successfully submitted AJAX request!');
$("#DIVinFirstPage").load("SecondPage.php");
}
});
return false;
});
What am I doing wrong?
Also - I have noticed that on this second PHP page I have to make a reference to my "Header.php" file that performs all the functions. Why is it that with this ajax request, it doesn't inherit all the rules from the page as a PHP include("File.php") does? Is there any way around this so I don't have to re-initialize and re-download all the PHP and JavaScript files? I tried include_once("File.php") in the PHP and that didn't correct it either.
jQuery load is the same thing as doing a $.get request. Is only a wrapper.
.load()
So you are basically doing a post request with some data on this part of the code
$.ajax({
type: 'post',
url: 'SecondPage.php',
cache: false,
data: $(this.form).serialize(),
success: function(html) {
window.alert('Successfully submitted AJAX request!');
And then inside the success making a get request to the same page on this line.
$("#DIVinFirstPage").load("SecondPage.php");
Then the page SecondPage.php is giving you an Index Undefined Error because SecondPage.php is expecting POST data which is not being sent in the .load call.
Since the Index Undefined is a php error, that sends the 500 error code to the browser.
So you need to either check if the variables are set using isset on SecondPage.php or make the load call another page that is not expecting any data.
Another alternative would be to have the script that handles the POST on a separate php file and then do the .load to the second page of your form.
In the success callback of the first POST request, you perform a JQuery load(). According to documentation http://api.jquery.com/load/, "It is roughly equivalent to $.get(url, data, success)".
You see your success callback function has a parameter named "html". That is the response served to your from SecondPage.php after the POST request. I imagine that contains the content you want to populate your div with.
Perhaps try:
success: function(html) {
window.alert('Successfully submitted AJAX request!');
$("#DIVinFirstPage").html(html);
}

trouble with json response from php in jQuery.ajax call

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

Ajax call always end up in error handler

I am trying to get a text value('selected crate') from the server using an ajax call. Ajax call is:
var selected_crate ='';
$.ajax({
url: OC.linkTo('crate_it', 'ajax/bagit_handler.php')+'?action=get_crate',
type: 'get',
dataType: 'text/html',
success: function(data){
selected_crate = data.responseText;
$('#crates option').filter(function(){
return $(this).attr("id") == selected_crate;
}).prop('selected', true);
},
error: function(data){
var e = data.responseText;
alert(e);
}
});
And the server side code snippet is:
case 'get_crate':
$msg = $bagit_manager->getSelectedCrate();
print $msg;
break;
I want to do something upon success but this call always end up in error handler. If there were complete handler, it would go in that handler. But I want to use both success and error handlers because I want to
Send error response if something is wrong from the server side
Do something on success in the client side
I am struggling to achieve this. Why this call always end up in error handler and how can I actually send an error response with regard to this call that would end up in error handler if any error occurs otherwise success response?
If the URL is right then try this:
dataType: "html"
See: http://api.jquery.com/jQuery.ajax/
see if in error handler data is been retrieved or not if data is been retrieved correctly it means your data-type is not matched for response in ajax call [see your server code that it must be returning some extra values in that case]
url: OC.linkTo('crate_it', 'ajax/bagit_handler.php')+'?action=get_crate',
in place of this try directly url like
url: www.yoursite.com/ajax/bagit_handler.php?action=get_crate
i think it will help you to get Sucess.

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

Categories