PHP function not returning any data to JQuery ajax method - ajax

I am using jquery's ajax method to post some data to the server and get back the response. Though the server side php code is returning a json encoded string/array, the response is coming back as null.
Could someone point out the mistake that I am making. Below if my jquery ajax method using which I am hitting the postData.php page.
$.ajax({
url:'postData.php',
type:'POST',
data:data,
dataType: "json",
success: function(response){
console.log(response);
}
});
The content in postData.php is pretty straight forward as I am still developing it.
$data = array();
//inside postData.php
$data['test']=1;
return json_encode($data);
It should return a json string, but it is returning null. I also tried echoing a string just after $data array declaration, it does echo it in the firebug, but the response is when I do a console.log on the success callback, it comes back as null.

For getting the result back in your ajax function, you must echo it, not return, like:
$data = array();
$data['test']=1;
echo json_encode($data);

Is that all that is in postData.php? You need to write it out to the buffer (echo json_encode($data);) at some point.

Like morgar pointed it out, you should echo the data back and not use return.
$data = array();
$data['test']=1;
echo json_encode($data); //echo instead of return
At the same time, in your ajax on success function, you should access the response like an array.
**Incorrect**
console.log(response); //--> would return an error
**Should Be**
console.log(response[0]); //--> read the returned first array element

Related

Ajax data not being sent to controller function (CodeIgniter)

I have an anchor tag and would like its data-id to be sent to a function in the controller which would in turn retrieved data from the database through the model.
However the data is not getting past the controller. The ajax response is showing that the data was sent but controller shows otherwise.
Here is my ajax code:
$(document).on("click",".learn-more",function(){
var sub_item_id = $(this).data("id");
$.ajax({
url:"<?php echo base_url();?>Designs/business_cards",
type:"POST",
data:{sub_item_id:sub_item_id},
success:function(data){
console.log(data);
},
error: function(error){
throw new Error('Did not work');
}
})
});
I had set datatype:"json" but the data was not being sent so I removed the datatype and it worked,the ajax part that is.Or atleast the response showed that data was sent.
My controller code is:
function business_cards(){
$id = $this->input->post('sub_item_id');
$data['quantity'] = $this->subproduct_model->get_quantities($id);
$this->load->view('category/business-cards',$data);
}
My model code is:
public function get_quantities($sub_item_id){
$this->db->select('quantities');
$this->db->where('id',$sub_item_id);
$query = $this->db->get('sub_products');
return $query->result_array();
}
HTML Code which includes the anchor tag
<?php foreach ($results as $object):?>
View Prices
<?php endforeach?>
The data-id is displaying the correct value as per the iteration.
When I check the result array of the model code it is an empty array showing that the $sub_item_id was not passed in the controller. What could be the problem?
I just copied your code and I was able to get the value in the controller.
In your controller function do var_dump($id). Then in your developer tools (F12) check the console. Since you have console.log(data) that var_dump should be in the console. It won't show on the screen.
Some other things to check:
Does your db have records with that ID? Could your db result array be empty because it actually should be?
Are you sure that the data-id actually has a value when you click the tag?
it is not passed to the controller because you forgot to put a parameter inside the function of your controller.
Note: you cannot use input post because you're not using form.
function business_cards($id){ //put a parameter here, serve as container of your passed variable from **ajax**
//$id = $this->input->post('sub_item_id');
$data['quantity'] = $this->subproduct_model->get_quantities($id); //pass the id to your model
$this->load->view('category/business-cards',$data);
}
change your ajax code to this..
$(document).on("click",".learn-more",function(){
var sub_item_id = $(this).data("id");
$.ajax({
url:"<?php echo base_url('Designs/business_cards/"+sub_item_id+"');?>", //pass the id here
type:"POST",
success:function(data){
console.log(data);
},
error: function(error){
throw new Error('Did not work');
}
})
});

getting a response data in ajax using codeigniter

Hi i have this data which i want that only a certain div will refresh using ajax. How will i able to pass the json_encode to the ajax what will load the data on a certain div using codeigniter.
Heres my controller below
$this->data['getNumberOfMessages'] = $this->mm->getNumberOfMessages($this->data['id']);
$this->data['countNumber'] = $this->data['getNumberOfMessages'];
$responseOnject = new stdClass();
$responseOnject->status = 'ok';
$responseOnject->StatusMessages=$this->data['countNumber'];
$this->output->set_output(json_encode($responseOnject));
this line of code here
$this->output->set_output(json_encode($response));
outputs this one
{"status":"ok","StatusMessages":20}
and i want that to pass through my ajax in my code below
$(document).ready(function(){
var id =$(this).data("messageid");
$.ajax({
type: "get",
url: $(this).data("href"),
success: function(data){
alert(data.StatusMessages);
console.log(data.StatusMessages);
$("#" + id + ' span.badge').html(data.StatusMessages);
}
});
});
and target on my certain div so that it will automatically refresh
below is my code
<tr>
<th>
<a href="#" id="<?php echo $id; ?>" data-messageid="<?php echo $id; ?>" data-href="<?php echo base_url().'profile'?>" title="messages">
<span class="badge"><?php echo $countNumber; ?></span>
message(s)</a>
</th>
</tr>
when i tried to alert(data.StatusMessages);it return undefined.
can someone pls help me figured this thing out? ive been stuck in this.. my code really works but i want to be ajax, only certain div refresh without refershing my entire page.
Any help is muchly appreciated.
You need to decode the response JSON first in order to be able to access it as a JS object. This is how it's done in JS:
JSON.parse(JSONStringHere);
So, your success callback should be:
success: function(data){
data = JSON.parse(data); // this is what decodes JSON
alert(data.StatusMessages);
console.log(data.StatusMessages);
$("#" + id + ' span.badge').html(data.StatusMessages);
}
As I said in the comments, you're not calling the right URL with AJAX (although you said you do and that it returns that JSON string; if so, the code above would work). This doesn't look like it would give you a URL:
$(document).ready(function(){
var id =$(this).data("messageid");
$.ajax({
type: "get",
url: $(this).data("href"), // <---- what is the value of this?
Once you fix that, your code will work.
For JSON data your controller should have the following line to output
UPDATE
Just noticed your problem is that codeigniter is outputting html along side your ajax response.
To Make this go away, Your code in the controller should be like this:
$this->output
->set_content_type('application/json', 'utf-8')
->set_output(json_encode($responseOnject))
->_display();
exit;
This would force the output library to display & the exit to stop displaying anything else.
If you do not set the application/json content type, your response won't be treated as JSON And you'd have to use JSON.parse in your javascript code to convert it to json which is a bad practice.

Cakephp - Proper way to return AJAX Success response?

I have been using the trick below to return success response with AJAX:
//In controller
echo 'success';
//In Javascript
if(response == 'success'){
//redirect
window.location.href = '/users/profile/';
}
It works fine on localhost. But in web server, I got the error below everytime I want to redirect the page after success:
Cannot modify header information - headers already sent by (output started at ...
So yeah, I know it is caused by the echo before redirecting.
So, Is there proper way to return the success response? No need to be a message, just true or false is enough.
[EDIT]
By using exit('success'), it works fine, but is this the best way?
Thanks.
It is better to redirect from javascript.
//In controller
echo 'success'; exit;
//In Javascript
if(response == 'success'){
window.location = 'your-controller-action';
}
EDIT
You may have space before/after php Opening/Closing tags in controller and models. Remove all the closing tags from all controllers and models and any whitespace before opening tags. Then check the result.

jQuery .ajax 'success' function never runs

I am trying to use jQuery for the first time, and my POST function using .ajax is giving me grief.
The POST is successful; my PHP page runs the MySQL query correctly and the newly created user ID is returned. The only problem is that instead of running the 'success' function; it simply loads the PHP page that I called, which simply echoes the user ID.
Here's the jQuery function:
function register() {
$.ajax({
type: "POST",
url: 'sendRegistration.php',
data: dataString,
datatype: 'html',
success: function(response){alert(response);},
complete: function(response,textStatus){console.log(textStatus);},
error: function(response){alert(response);}
});
}
... and the PHP return stuff:
// Create a new send & recieve object to store and retrieve the data
$sender = new sendRecieve();
$custId = $sender->submitUser($userVars);
if ($custId != 0) {
echo $custId;
} else {
echo "Database connection problems...";
}
The database object is created, and then the php page from the 'url' parameter loads, displaying the id that the $sender->submitUser() function returns.
Ideally, I would like it to never display the 'sendRegistration.php' page, but run another js function.
I'm sure there's a simple solution, but I've not been able to find it after hours of searching.
Thanks for your help.
You are likely handling this from a form. If you don't prevent the default form submittal process of the browser, the page will redirect to the action url of the form. If there is no action in form, the current page will reload, which is most likely what is happening in your case.
To prevent this use either of the following methods
$('form').submit(function(event){
/* this method before AJAX code*/
event.preventDefault()
/* OR*/
/* this method after all other code in handler*/
return false;
})
The same methods apply if you are sending the AJAX from a click handler on the form submit button
how are you calling the register() function? It could be the form is being submitted traditionally, you might need to prevent the default action(standard form submit).

My ajax request isn't working

I have an <ul id="keuze_lijst"> , an input field with id #sykje and an button with class .search .
Now when i press the button i would like to clear the UL and repopulate it with data, for this i currently got this .js file.
$(document).ready(function() {
$(".search").click(function(){
var searchValue = $("#sykje").val();
$("#keuze_lijst").empty();
$.ajax({
url: 'http://www.autive.nl/frysk/simulator/sim.php?action=getSongs&search='+searchValue,
data: "",
dataType: 'json',
success: function(rows) {
for(var i in rows){
var row = rows[i];
var id = row[1];
var titel = row[2];
var artiest = row[9];
$("#keuze_lijst").append("<li class='mag_droppen'>"+
"<div class='song_left'>"+
"<div class='titel'>"+titel+"</div>"+
"<div class='artiest'>"+artiest+"</div>"+
"</div><!-- .song_left -->"+
"</li>");
}
}
});
});
});
When i remove the ajax command and put something like $("#keuze_lijst").html("hello"); it works fine. But the ajax command isn't working. Though the var searchValue does his work. (ajax uses the correct url). And when i enter that url the page echoes an fine json with multiple rows.
But in my page the ajax script isn't adding the <li>.
What am i doing wrong?
edit: added an jsfiddle -> http://jsfiddle.net/TVvKb/1/
.html() totally replaces the HTML. So at the end, your "#keuze_list will contain </li>.
Just execute one html() command after you build your html into a string var or something.
From a quick glance, I can say that the problem might be with your use of the html() function. This actually replaces the entire html content.
You might want to try using append() or prepend().
Possible Problems:
You are running into a Same Origin Problem. Per default you can only make Ajax-Requests to your own domain. If you need to make cross-domain calls use JSONP or CORS.
Use the html() only once, and hand over your complete string, otherwise you will override your previous html all the time.
You are not landing in the success handler due to an error (e.g. invalid JSON).
Not sure, but I think if you insert a string in the .append() and other jQuery methods, it parses to (valid) HTML first. That means that unclosed tags are closed, making your HTML invalid.
$('<div />'); // parses to <div></div>
So, I assume that your DOM ends up like this this:
$('ul').append('<li>').append('foo').append('</li>'); // <ul><li></li>foo</li></ul>
Please, just format your string first. You don't want jQuery to parse every input.
var str = '<li>';
str += 'foo';
str += '</li>';
$('ul').html(str);
For cross-domain AJAX requests (without JSONP):
proxy.php
header('Content-Type: application/json');
if(empty($_GET['search'])) exit;
$url = 'http://www.autive.nl/frysk/simulator/sim.php?action=getSongs&search=' . $_GET['search'];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_exec($ch);
curl_close($ch);
Javascript
$.getJSON({
url: 'proxy.php&search='+searchValue,
success: callback
});

Resources