I'm doing an ajax call to my controller, but the alert in my success isn't displaying and I'm not getting errors in console. I don't know how to proceed now.
Controller - rate
function graph($userid, $courseid){
$i_am_admin = $this->logged_in->logged_as_admin();
if($this->session->userdata('id') == $userid || $i_am_admin ){
$this->load->model('rate_model');
$graph_data = array();
if($query = $this->rate_model->graphRate($userid, $courseid)){
$data['rate'] = $query;
}
$data['graph_json'] = json_encode($query);
$data['content'] = 'rate_graph_view';
$this->load->view('templates/template', $data);
return json_encode($query);
}
}
Script.js
$('.profileimg').click(function(){
$.ajax({
url: url, // url = http://localhost/herexamen/project/rate/graph/6/4
type:'POST',
dataType: 'json',
success: function(output_string){
alert(output_string);
alert("yes");
} // End of success function of ajax form
}); // End of ajax call
});
You aren't checking if the ajax call failed
The appended code isn't the solution, by any means, but can shed light on your problems. Notice I added the error section to the ajax request.
What is the result of this call?
$('.profileimg').click(function(){
$.ajax({
url: url,
type:'POST',
dataType: 'json',
success: function(output_string){
alert(output_string);
alert("yes");
},
error: function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
}
}); // End of ajax call
});
While making ajax calls you are supposed to echo the content or response to send and you are using return try this
echo json_encode($query);
Why view is loaded when you are making json and only
function graph($userid, $courseid){
$i_am_admin = $this->logged_in->logged_as_admin();
if($this->session->userdata('id') == $userid || $i_am_admin ){
$this->load->model('rate_model');
$graph_data = array();
if($query = $this->rate_model->graphRate($userid, $courseid)){
$data['rate'] = $query;
}
$data['graph_json'] = json_encode($query);
$data['content'] = 'rate_graph_view';
$data['viewloaded']= $this->load->view('templates/template', $data,true);
echo json_encode($data);
die();
}
}
There is a third optional parameter lets you change the behavior of
the function so that it returns data as a string rather than sending
it to your browser. This can be useful if you want to process the data
in some way. If you set the parameter to true (boolean) it will return
data. The default behavior is false, which sends it to your browser.
Remember to assign it to a variable if you want the data returned
CI Views
Related
Current Page is Add.phtml..when click saves button, it should be redirected to index.phtml..the URL for index page already inside a controller.
but I can't make it..can anyone point me which part is wrong?
JS inside add.phtml
function addMembAndAppDetail(){
var m_register = 0;
if($('input[name="register"]').is(':checked'))
{
m_register = 1;
}
var m_active = 0;
if($('input[name="status"]').is(':checked'))
{
m_active = 1;
}
$.ajax({
url: '/membership/membership-setup/ajax-add-multiple/',
type: 'POST',
async : false,
data: {
'm_owner' : $('#m_owner').val(),
},
dataType: 'json',
success: function(response){
window.location.href = response.url;
}
});
}
Inside Controller
public function ajaxAddMultipleAction(){
$auth = Zend_Auth::getInstance();
$data = array(
'm_owner' => $this->_getParam('m_owner', null)
);
$membershipDb = new Membership_Model_DbTable_TblMembership();
$membershipDb->addData($data);
$this->_helper->flashMessenger->addMessage(array('success' => "Record saved"));
$url = $this->_redirect($this->baseUrl . '/membership/membership-setup/index');
echo json_encode(array('msg'=>"Success.", 'url'=>$url, 'status'=>true));
}
You just returning the url but you never used it. if your url is valid then you can change your success method to redirect the client
success: function(response){
window.location.href = response.url
}
Edit
I tested out your ajax call and it looks like that if you remove dataType: 'json' it works perfectly. I don't know why it cause the issue but after removing it it should work.
anyways dataType default value is Intelligent Guess so it will guess the data type automatically for you
I have checked around, but can't seem to figure out how this is done.
I would like to send form data to PHP to have it processed and inserted into a database (this is working).
Then I would like to send a variable ($selected_moid) back from PHP to a JavaScript function (the same one if possible) so that it can be used again.
function submit_data() {
"use strict";
$.post('insert.php', $('#formName').formSerialize());
$.get('add_host.cgi?moid='.$selected_moid.');
}
Here is my latest attempt, but still getting errors:
PHP:
$get_moid = "
SELECT ID FROM nagios.view_all_monitored_objects
WHERE CoID='$company'
AND MoTypeID='$type'
AND MoName='$name'
AND DNS='$name.$selected_shortname.mon'
AND IP='$ip'
";
while($MonitoredObjectID = mysql_fetch_row($get_moid)){
//Sets MonitoredObjectID for added/edited device.
$Response = $MonitoredObjectID;
if ($logon_choice = '1') {
$Response = $Response'&'$logon_id;
$Response = $Response'&'$logon_pwd;
}
}
echo json_encode($response);
JS:
function submit_data(action, formName) {
"use strict";
$.ajax({
cache: false,
type: 'POST',
url: 'library/plugins/' + action + '.php',
data: $('#' + formName).serialize(),
success: function (response) {
// PROCESS DATA HERE
var resp = $.parseJSON(response);
$.get('/nagios/cgi-bin/add_host.cgi', {moid: resp });
alert('success!');
},
error: function (response) {
//PROCESS HERE FOR FAILURE
alert('failure 'response);
}
});
}
I am going out on a limb on this since your question is not 100% clear. First of all, Javascript AJAX calls are asynchronous, meaning both the $.get and $.post will be call almost simultaneously.
If you are trying to get the response from one and using it in a second call, then you need to nest them in the success function. Since you are using jQuery, take a look at their API to see the arguments your AJAX call can handle (http://api.jquery.com/jQuery.post/)
$.post('insert.php', $('#formName').formSerialize(),function(data){
$.get('add_host.cgi?moid='+data);
});
In your PHP script, after you have updated the database and everything, just echo the data want. Javascript will take the text and put it in the data variable in the success function.
You need to use a callback function to get the returned value.
function submit_data(action, formName) {
"use strict";
$.post('insert.php', $('#' + formName).formSerialize(), function (selected_moid) {
$.get('add_host.cgi', {moid: selected_moid });
});
}
$("ID OF THE SUBMIT BUTTON").click(function() {
$.ajax({
cache: false,
type: 'POST',
url: 'FILE IN HERE FOR PROCESSING',
data: $("ID HERE OF THE FORM").serialize(),
success: function(data) {
// PROCESS DATA HERE
},
error: function(data) {
//PROCESS HERE FOR FAILURE
}
});
return false; //This stops the Button from Actually Preforming
});
Now for the Php
<?php
start_session(); <-- This will make it share the same Session Princables
//error check and soforth use $_POST[] to get everything
$Response = array('success'=>true, 'VAR'=>'DATA'); <--- Success
$Response = array('success'=>false, 'VAR'=>'DATA'); <--- fails
echo json_encode($Response);
?>
I forgot to Mention, this is using JavaScript/jQuery, and ajax to do this.
Example of this as a Function
Var Form_Data = THIS IS THE DATA OF THE FORM;
function YOUR FUNCTION HERE(VARS HERE) {
$.ajax({
cache: false,
type: 'POST',
url: 'FILE IN HERE FOR PROCESSING',
data:Form_Data.serialize(),
success: function(data) {
// PROCESS DATA HERE
},
error: function(data) {
//PROCESS HERE FOR FAILURE
}
});
}
Now you could use this as the Button Click which would also function :3
here is it my code i call ajax by jquery $.ajax
js
$("#form-login").submit(function(){
var email = $("#menu_username");
$.ajax({
type: "post",
url: "register_cmd.php",
data: {email:email},
dataType: "json",
cache:false,
success:function(data){
if(data.c == "ok"){
window.location.reload();
} else {
alert(data);
}
return false;
}
})
});
register_cmd.php
<?PHP
include 'system/library/main.php';
$main = new mainQuery();
$chk_email = $main->checkEmail($email);
?>
main.php
function checkEmail($email){
$result = "function here";
return $result;
}
then it return 500 internal server error i don't know why
I just had this problem myself, even though i couldn't find the reason for it in my case, when changing from POST to GET, the problem 500 error disappeared!
because GET method sends the encoded user information appended to the page request.
type:'POST'
to
type:'GET'
I doing little changes in your codes. Just try this
var email = $("#menu_username").val(); // if you want to take the value from email field
$.ajax({
type: "POST",
url: "register_cmd.php",
data: {email:email},
dataType: "json",
cache:false,
success:function(data){
if(data.result == "ok"){
window.location.reload();
} else {
alert(data.result);
}
return false;
}
});
AND change the codes in register_cmd.php as follows
<?PHP
include 'system/library/main.php';
$main = new mainQuery();
$chk_email['result'] = $main->checkEmail($email);
print_r(json_encode($chk_email)); // if you are using json, you should use json_encode before it returns.
?>
the function in main.php need's a class arround it
class mainQuery {
public function checkEmail($email){
$result = "function here";
return $result;
}
}
otherwise you cannot instance new mainQUery;
also on top of everything to debug set
error_reporting(E_ALL);
ini_set('display_errors', true);
500 are serverside errors and have nothing to do with ajax.
probably this line:
var email = $("#menu_username");
might have to be
var email = $("#menu_username").text();
//or
var email = $("#menu_username").val();
It doesn't matter if it's a POST or GET request.
I am learning Cakephp and I've been trying to delete multiple (checked) record using checkbox, but still not success. here's my jQuery :
var ids = [];
$(':checkbox:checked').each(function(index){
ids[index] = $(this).val();;
alert(ids[index]);
});
//alert(ids);
var formData = $(this).parents('form').serialize();
$.ajax({
type: "POST",
url: "tickets/multi_delete",
data:"id="+ids,
success: function() {
alert('Record has been delete');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest);
alert(textStatus);
alert(errorThrown);
}
});
and here is code in controller :
function multi_delete() {
$delrec=$_GET['id'];
//debuger::dump($del_rec);
foreach ($delrec as $id) {
$sql="DELETE FROM tickets where id=".$id;
$this->Ticket->query($sql);
};
}
anybody will help me please. thank
you could try a .join(',') on the array of IDs and then an explode() on the server side to get the array of IDs passed to the script.
e.g.
var idStr = ids.join(',');
pass it (idStr) to the ajax call
$.ajax({
type: "POST",
url: "tickets/multi_delete",
data: {id:idStr},
//more code cont.
on the server side:
$ids = explode(',',$_POST['ids']);
OR
check the jquery.param() function in the jquery docs. Apply and to the IDS array and then pass it to $.ajax({});
Note: You are using POST and not GET HTTP METHOD in the code you provided
use json encode and decode for serialized data transfer
Since JSON encoding is not supported in jQuery by default, download the JSON Plugin for jQuery.
Your javascript then becomes:
$.ajax({
type: "POST",
url: "tickets/multi_delete",
data: { records: $.toJSON(ids) },
success: function() {
alert('Records have been deleted.');
},
});
In the controller:
var $components = array('RequestHandler');
function multi_delete() {
if (!$this->RequestHandler->isAjax()) {
die();
}
$records = $_POST['records'];
if (version_compare(PHP_VERSION,"5.2","<")) {
require_once("./JSON.php"); //if php<5.2 need JSON class
$json = new Services_JSON();//instantiate new json object
$selectedRows = $json->decode(stripslashes($records));//decode the data from json format
} else {
$selectedRows = json_decode(stripslashes($records));//decode the data from json format
}
$this->Ticket->deleteAll(array('Ticket.id' => $selectedRows));
$total = $this->Ticket->getAffectedRows();
$success = ($total > 0) ? 'true' : 'false';
$this->set(compact('success', 'total'));
}
The RequestHandler component ensures that this is an AJAX request. This is optional.
The corresponding view:
<?php echo '({ "success": ' . $success . ', "total": ' . $total . '})'; ?>
Wish you luck!
I am trying to get the data return from a function called by a jquery ajax call. My function is located in a a php file and it looks liket his
valid_user() {
$id = $_POST('id');
if($id == 'hello'){
return true;
}
else{
return false;
}
}
and here is my ajax call
$.ajax({
type: "POST",
url: path + "valid_user",
sucess: function(msg) {
alert("Data returned: " + msg );
}
});
I have tested everthing and the function is wokring ( has been changed for this example) but I can not the return value of the function valid_id(). How do I get this? the variable msg keeps coming back empty. Thanks
From my understanding, there are several issues.
1) the method valid_user() is not been called.
2) The url doesn't look like it is correct either.
3) The "success" keyword is spelt "sucess".
4) You aren't passing any "data".
Here is an example ajax call tailored to what you may want.
$.ajax({
type: "POST",
url: "validateUser.php",
data: "id=49",
success: function(msg){
alert( "true or false: " + msg );
}
});
It looks like you misspelled sucess----but this may not be in your running code. You should check the second parameter of success:
success:function(data, textStatus)
You need to write PHP server-side code that calls the function and writes its return value to the output stream. For example:
<?php echo valid_user(); ?>
This should work - you might want to put better sanitizing on the POST value just in case.
In the PHP file:
$id = isset($_POST['id']) ? trim($_POST['id']) : '';
$return = 'false';
if($id!=''){
valid_user($id);
}
echo $return;
valid_user($id) {
if($id == 'hello'){
$return = 'true';
}
}
jQuery Call:
<script>
id = 'hello';
$.ajax({
type: "POST",
url: "validateUser.php?id="+id,
success: function(msg) {
alert("Data returned: " + msg );
}
});
</script>
Thank you for your help, I figured out the issue, the reason why it was not working was becuase my function valid_id() was returning true or false, and I needed to return echo "true"; and echo "false"; once I did this the msg variable contained the data true or false.