Im trying to learn to use ajax at the moment, but unfortunately I cannot get it to success.
$('.engineering-services').live('click', function() {
$.ajax({
url: 'index.php?route=information/information/homepage_info',
type: 'post',
data: {info_description : 'test'},
dataType: 'json',
success: function(json){
alert('pass');
},
error: function(json) {
alert('fail');
}
});
});
Here is the php function...
public function homepage_info() {
$json = array();
if (isset($this->request->post['info_description'])) {
echo $this->request->post['info_description'];
echo '<br /> test2';
}
$this->response->setOutput(json_encode($json));
}
However this always makes a fail alert instead of a pass one.
Am I missing something obvious here?
EDIT: Its finding the function ok, as in the console it is giving the correct response,
i.e.
test
test2
Thank you
If your dataType is set to json, anything returned that is not JSON will cause the ajax call to error out. Try sending some json back to the script... {"test":"abc"} or similar. I see a couple of calls to echo in your code, for example.
Not just this, but any PHP error/warning/notice printed to the browser will break calls.
Hint: you can generate valid JSON from PHP variables using json_encode().
You cannot combine an existing query string with data. Something like this should work (or at least be syntactically valid):
$.ajax({
url: 'index.php',
type: 'post',
data: {information:'information/information/homepage_info',info_description:'test'},
dataType: 'json',
success:function(json){
alert('pass');
},
error:function(json) {
alert('fail');
}
});
Also as was mentioned, anything that is not json will potentially cause an error, so you not echo those html components ... if anything, you print them.
Also, as a side note your dataType should be done server side with a header('Content-type: application/json'); declaration in index.php rather than in your jQuery script. Its guaranteed to be recognized as json that way, and also less Javascript code.
Related
I have ajax that calls a php file called "fetch_quarter_limit.php" from template file.
$.ajax({
type: 'POST',
url: 'fetch_quarter_limit.php',
data: {
leavefrom: from,
leaveto: to,
empid: emp
},
success: function(data) {
var quarter_limit = data['myVar'];
alert(quarter_limit);
}
});
In my .php file i have tried to return the session data as an array.
Fetched the required data, stored in session and formed an array.
$_SESSION['quarter_limit_mend'] = $quarterLimit;
$returnVal = array('myVar' => $_SESSION['quarter_limit_mend']);
echo $returnVal;
As shown in above ajax code part, i tried to fetch it, but all i am getting is "undefined" when i output the variable using alert.
Please help.
Ajax code updated, p2 :
Adding dataType is making code not to work.
$.ajax({
type: 'POST',
url: 'fetch_quarter_limit.php',
dataType: 'json',
data: {
leavefrom: from,
leaveto: to,
empid: emp
},
success: function(data) {
alert(data);
}
});
As #Tim mentioned i have added custom json encode function to my .php file.
It returns as expected {"myVar": 2}
echo array_to_json($returnVal);
This is returned from php file.
But not able to access in ajax code.
You're using echo on an array, which is not possible. As described in the PHP manual
echo outputs one or more strings.
Usually you'd use json_encode() on your array and then output it to the screen. But as you've commented you are using php < 5. First of all, if possible, you should consider to upgrade to PHP > 7, as this not only improves performance, it also improves security.
If you can't upgrade to a PHP version above PHP 5, then you can use workarounds. On this question there is already an answer for the workaround, and the workaround can be found on the PHP manual itself.
You should be able to use the returned JSON data.
Reply for after your edit
So you have your data as JSON now, but JS will still see it as a string. In your success function you still have to parse it.
success: function(data) {
jsonData = JSON.parse(data);
alert(jsonData.myVar);
}
I do have to add too that it is very insecure to continue using php < 7.3 (as of today, 24-02-2021)
Hmm I have a little problem with that :
$.ajax({
type: 'POST',
data: {
name : 'aatrox'
},
dataType: "json",
async:false,
url: 'appliserv/testsendajax.php',
success: function(data){
console.log(data);
alert('good');
},
error: function(data){
console.log(data);
alert(fail);
}
});
the text in the alert is always fail ....
in my serv :
$text = $_POST['name'];
echo $text;
and I don't understand that. Thanks (sry if my english isn't good)
Your server-side script output plain text. So you have to change value of dataType option.
Change this:
dataType: "json"
to this:
dataType: "text"
Quite likely you're getting a parse error. This is because your ajax request is expecting JSON but you're are returning a plain string. Either return JSON from your PHP script or change the dataType to text:
dataType: "text",
Also be sure to change alert(fail); to:
alert('fail');
String literals must be delimited or variables have to be initialized before they are used.
You already got your answer, I just want to add that using
async: false
is a bad practice when dealing with ajax calls, it freezes your browser while waiting for the response.
If it's possible you should try to avoid this behavior and use
instead the ajax callbacks properly; however if you really want to block the UI you can try to use something like http://malsup.com/jquery/block/
Okay I think I am going mad because I have done this a million times before and now I can't make it work. I am doing an ajax post to a PHP script with some simple JSON and then returning the JSON from my PHP, however it is currently showing $_POST as an empty array.
Here is my js:
$.ajax({
type: "POST",
url: "/account/book-promo.php",
data: '{"firstName":"Peter" , "lastName":"Jones"}',
success: function(response) {
console.log(response);
}
});
And my PHP:
<?php
var_dump($_POST);
exit;
Firebug shows that my request is using POST as it is supposed to and my data is being sent as JSON yet I am getting a response of:
array(0) {
}
The only thing I can think is that there is some kind of server settings that are preventing this from working, however I cant think why there would be. Maybe I have missed a bracket or something, it is driving me mad!
Any and all suggestions welcome!
send it like if you want to send it as json.
data: { data : '{"firstName":"Peter" , "lastName":"Jones"}' },
and if you want to send it as POST just remove quotes '
data: {"firstName":"Peter" , "lastName":"Jones"},
You have to do this:
$.ajax({
type: "POST",
dataType: "json", // <---------------its required if response is json
url: "/account/book-promo.php",
data: {"firstName":"Peter" , "lastName":"Jones"}, //<---instead of string send the object this way
success: function(response) {
console.log(response);
}
});
You said in your post retuning the JSON from my PHP:
so you need to use dataType:"json" and the data you are sending to your php should be sent as object (which is usually to be pair of key and values separated by : like {key:value}) as of your code you are sending a string.
I have an AJAX request (using JQuery) that calls a PHP script which does some database business. The request code is as follows:
$.ajax({
url: "script.php",
data: { value: value
},
type: 'post',
success: function(output){
alert(output);
}
});
However, I wanted to see if there was a way to also (in addition to the unchanged output string) return a status. It can be as simple as an integer. The point is I want to disable a button (with Javascript) if the PHP script for any reason fails to connect to mySQL, but I still want the PHP scripts output exactly as it would be.
I tried the error option:
...
success: function(output){
alert(output);
},
error: function(output){
// do something
}
but I do not know how to make PHP display an error and continue on the rest of the script. Again, I don't want to tamper at all with the output string.
In pseudo-code, I'm looking for something like this:
$.ajax({
url: "script.php",
data: { value: value
},
type: 'post',
success: function(output){
if(output.status == 0){
alert(output);
}else{
// do something else
}
}
});
Is anything of the sort possible? Thanks for any and all help!
I usually return data from the server in JSON format. This way I can return as many different types of data as may be needed by the success function in javascript.
basically in PHP you would do something like
$response = new stdClass();
$response->error = 'Could not connect to Mysql';
$response->message = 'Some other text';
echo json_encode($response);
in JQuery, the ajax() method would automatically detect that the response is json and parse it into a javascript object, so you could access like this
if (typeof response.error !== undefined) alert(response.error);
for more on that look at dataType argument for the ajax() method in the jQuery documentation.
Yes. You can use HTTP status codes:
header('HTTP/1.1 500 Internal Server Error');
And use jQuery's statusCode property for jQuery.ajax():
$.ajax({
// stuff
statusCode: {
500: function(data) {
alert('Something went wrong!');
}
}
});
If your needs extend beyond what HTTP can offer, you can just return a status code within your data and process it in the success function, switching on data.status.
If I haven't misunderstood your question...
What I usually do is set the datatype of the AJAX call to 'xml' and output an xml from my PHP script. So I get multiple values in result. I usually make these attribute values.
<result status="success" something="etc" />
// vs.
<result status="failure" error="1" />
// consider 1 as the DB error
With this approach you might need to use the # tags in some PHP functions to prevent outputting the default errors.
Why doesn't var_dump work here, the ajax call is successful, but there is nothing printed, not even a string literal print from the PHP.
My controller
function check_links() {
$matches = $this->input->get('matchesJSON');
var_dump($matches);
//$this->load->view('publish_links_view');
}
Ajax call
$.ajax({
type: 'GET',
dataType: 'json',
cache: false,
data: 'matchesJSON='+matchesJSON,
url: 'publishlinks/check_links',
success:
function(response) {
}
})
I assume you're expecting it to var_dump to the browser.
Ajax happens "behind the scenes", so it wouldn't output to your browser, you'd have it in your success handler's response argument.
if you want to test it just hit the url directly with your browser.
http://ciroot/index.php/publishlinks/check_links?matchesJSON=test%20text
Also, you can monitor all of your AJAX requests / responses with the Browser extension Firebug, very useful in situations like this.
it seems to be a problem with your ajax call, not with codeigniter
start with removing dataType: 'json' - jQuery will find type of content itself as it's not json
and you need to output response in your function:
function(response) { window.alert(response) }