i'm using ajax in my codeigniter project but whenever i send data i get error and the response will be 'Undefined'.
i built the simplest code i've ever imagine but nothing works.
would you please tell me where is the wrong ??
<script type="text/javascript">
$(document).ready(function() {
var content = "test";
var datastring = 'content='+ content;
jQuery.ajax({
type:"POST",
url:"<?php echo site_url('test/test'); ?>",
data: datastring,
dataType: "html",
async: false,
success: function(data) { alert("succsess"); },
error: function(ts) { alert(ts.responseText); },
onComplete: function(data) {alert(data); }
});
});
</script>
and my codeigniter code is :
function test() {
echo $this->input->post('content');
}
ErrorText is the last parameter of error callback.
error: function(xhr, status, errorText) {
alert(errorText);
}
You should use complete in the place of oncomplete. The re-written code will be
<script type="text/javascript">
$(document).ready(function() {
var content = "test";
var datastring = 'content='+ content;
jQuery.ajax({
type:"POST",
url:"<?php echo site_url('test/test'); ?>",
data: datastring,
dataType: "html",
async: false,
success: function(data) { alert("succsess"); },
error: function(ts) { alert(ts.responseText); },
complete: function(data) {alert(data); }
});
});
</script>
Related
I am facing on problem, I have made a CRUD code with AJAX for my CI page, it is working fine on XAMPP server but when I uploaded it to Live Server (Godaddy), it's not fetching data from database and showing 405 Method not Allowed error.
http://www.fenxteksolutions.com/admin/metalinks
Here is my Code.
<script>
$(function(){
showAllEmployee();
//Add New
$('#btnAdd').click(function(){
$('#myModal').modal('show');
$('#myModal').find('.modal-title').text('Add New Meta Detail');
$('#myForm').attr('action', '<?php echo base_url() ?>admin/addEmployee');
});
$('#btnSave').click(function(){
var url = $('#myForm').attr('action');
var data = $('#myForm').serialize();
//validate form
var empoyeeName = $('input[name=txtEmployeeName]');
var address = $('textarea[name=txtAddress]');
var meta_tag = $('input[name=txtMetaTag]');
var meta_desc = $('input[name=txtMetaDesc]');
var result = '';
if(empoyeeName.val()==''){
empoyeeName.parent().parent().addClass('has-error');
}else{
empoyeeName.parent().parent().removeClass('has-error');
result +='1';
}
if(address.val()==''){
address.parent().parent().addClass('has-error');
}else{
address.parent().parent().removeClass('has-error');
result +='2';
}
if(meta_tag.val()==''){
meta_tag.parent().parent().addClass('has-error');
}else{
meta_tag.parent().parent().removeClass('has-error');
result +='3';
}
if(meta_desc.val()==''){
meta_desc.parent().parent().addClass('has-error');
}else{
meta_desc.parent().parent().removeClass('has-error');
result +='4';
}
if(result=='1234'){
$.ajax({
type: 'ajax',
method: 'post',
url: url,
data: data,
async: false,
dataType: 'json',
success: function(response){
if(response.success){
$('#myModal').modal('hide');
$('#myForm')[0].reset();
if(response.type=='add'){
var type = 'added'
}else if(response.type=='update'){
var type ="updated"
}
$('.alert-success').html('News '+type+' successfully').fadeIn().delay(4000).fadeOut('slow');
showAllEmployee();
}else{
alert('Error');
}
},
error: function(){
alert('Could not add data');
}
});
}
});
//edit
$('#showdata').on('click', '.item-edit', function(){
var id = $(this).attr('data');
$('#myModal').modal('show');
$('#myModal').find('.modal-title').text('Edit Employee');
$('#myForm').attr('action', '<?php echo base_url() ?>admin/updateEmployee');
$.ajax({
type: 'ajax',
method: 'get',
url: '<?php echo base_url() ?>admin/editEmployee',
data: {id: id},
async: false,
dataType: 'json',
success: function(data){
$('input[name=txtEmployeeName]').val(data.page);
$('textarea[name=txtAddress]').val(data.title);
$('input[name=txtMetaTag]').val(data.meta_tag);
$('input[name=txtMetaDesc]').val(data.meta_desc);
$('input[name=txtId]').val(data.id);
},
error: function(){
alert('Could not Edit Data');
}
});
});
//delete-
$('#showdata').on('click', '.item-delete', function(){
var id = $(this).attr('data');
$('#deleteModal').modal('show');
//prevent previous handler - unbind()
$('#btnDelete').unbind().click(function(){
$.ajax({
type: 'ajax',
method: 'get',
async: false,
url: '<?php echo base_url() ?>admin/deleteEmployee',
data:{id:id},
dataType: 'json',
success: function(response){
if(response.success){
$('#deleteModal').modal('hide');
$('.alert-success').html('Employee Deleted successfully').fadeIn().delay(4000).fadeOut('slow');
showAllEmployee();
}else{
alert('Error');
}
},
error: function(){
alert('Error deleting');
}
});
});
});
//function
function showAllEmployee(){
$.ajax({
type: 'ajax',
url: '<?php echo base_url() ?>admin/showAllEmployee',
async: false,
dataType: 'json',
success: function(data){
var html = '';
var i;
for(i=0; i<data.length; i++){
html +='<tr class="odd gradeX">'+
// '<td>'+data[i].id+'</td>'+
'<td>'+data[i].page+'</td>'+
'<td>'+data[i].title+'</td>'+
'<td>'+data[i].meta_tag+'</td>'+
'<td>'+data[i].meta_desc+'</td>'+
'<td>'+
'Edit'+
'</td>'+
'<td>'+
'Delete'+
'</td>'+
'</tr>';
}
$('#showdata').html(html);
},
error: function(){
alert('Could not get Data from Database');
}
});
}
});
</script>
This code is working very well in XAMPP Server and giving all data from database and all functions are working very well, but on hosting it is not fetching data and when I inspect the page in console it gave 405 method not allowed error.
Your error is in type parameter in ajax. Remove it or set it to GET. It is actually request method
$.ajax({
type: 'GET',
url: '<?php echo base_url() ?>admin/showAllEmployee',
async: false,
dataType: 'json',
success: function(data){
.......................
I have a simple code but is not working. I want to create a more complex function but I just need the basic structure.
HTML
<span class="cleanreport">Delete Record</span>
Javascript:
$( ".cleanreport" ).click(function() {
var token = "test";
$.ajax({
data: {"data": token},
type: "post",
url: "clean.php",
success: function (data) {
console.log(data);
$('.test').html(data);
}
});
});
PHP clean.php
$data = $_POST['data'];
echo $data;
What I am doing wrong?
This should work for you:
var token = "test";
$.ajax({
type: 'POST',
url: "clean.php",
data: {id: token},
dataType: "json",
success: function(response) {
// some debug could be here
},
error: function(a,b,c) {
// some debug could be here
}
});
If not, please debug success and error parameters using console.log().
Based on jquery documentation setting type is an alias for method so this could not be a problem in you case for sure.
$( ".cleanreport" ).click(function() {
var token = "test";
$.post('clean.php",
{
data: token
},
function (data,status) {
//console.log(data);
$('.test').html(data);
});
});
{"query":[{"uID":"U0016","name":"saman","nic":"911350521V","email":"saman#gmail.com","username":"saman","address":"colombo","telephone":"0342270443","type":"FREE"}],"field":["uID","name","nic","email","username","address","telephone","type"],"result":[{"uID":"U0014","name":"hafim","nic":"911350521V","email":"managerdulux#gmail.com","username":"fiham","password":"5dca0dc7c1fd78b5c90abbb0db69aed7","address":"colombo","telephone":"0342270443","type":"ADMIN"},{"uID":"U0018","name":"fast","nic":"911350521V","email":"pasdulanjaya#gmail.com","username":"fast","password":"31d4541b8e926a24f0c9b835b68cfdf3","address":"colombo","telephone":"0342270443","type":"ADMIN"},{"uID":"U0019","name":"hafima","nic":"911350521V","email":"fihamzuher#gmail.com","username":"hafim","password":"8f49a4ca3aeffd575ba8c25276ff061f","address":"colombo","telephone":"0342270443","type":"ADMIN"}],"userid":[{"uID":"U0013"},{"uID":"U0016"},{"uID":"U0020"},{"uID":"U0021"},{"uID":"U0024"},{"uID":"U0025"}],"adminid":[{"uID":"U0014"},{"uID":"U0018"},{"uID":"U0019"}],"updatefield":["name","nic","address","telephone"]}
this is my json object and i need to get the "query" data to my table how to do this
this is my ajax call
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script> function makesearchCall(){
$.ajax({
type: "post",
url: "<?php echo site_url(); ?>/controller_d/login/admin_search_user",
cache: false,
data: $('#docContainer1').serialize(),
success: function(json){
try{
var obj = jQuery.parseJSON(json);
}catch(e) {
alert('Exception while request..');
} },
error: function(){
alert('Error while request..');
} }); }
</script>
loop throught obj.query and get the values using . operator
try this
$.ajax({
type: "post",
url: "<?php echo site_url(); ?>/controller_d/login/admin_search_user",
cache: false,
data: $('#docContainer1').serialize(),
dataType:"JSON", //<----here
success: function(json){
var str= "<table><tr>";
$.each(json.query,function(i,v){
alert(v.uID); //gives U0016
alert(v.name); //gives saman
str+="<td>"+v.uID+"</td>";
str+="<td>"+v.name+"</td>";
})
str+="</tr></table">;
$("body").append(str);
}
I have a html link with a value inside like this.
<a data-toggle='modal' data-id='1' href='#myModal' class='marker' title='Edit'>Link</a>
I have a Js script that trigger a php that I want to send the value data-id
<script>
$(document).on("click", ".marker", function () {
var myBookId = $(this).data('id');
$.ajax({
type: "post",
url: "update.php", //
data: myBookId,
success: function(msg) {
$("#thanks").html(msg)
},
error: function() {
alert("failure");
}
});
});
</script>
And in my php I have this
if (isset($_POST['myBookId'])) {
$emp_id = strip_tags($_POST['myBookId']);
echo $emp_id;
But something is wrong the value is not pass.
Your problem is on the params of the AJAX call. Try this way:
data: { myBookId: myBookId },
try
$('.marker')click(function(){
var myBookId = $().attr('data-id');
$.ajax({
type: "post",
url: "update.php", //
data: myBookId,
success: function(msg){
$("#thanks").html(msg)
},
error: function(){
alert("failure");
}
});
return false;
});
I want to send the data via ajax to other page. I have isolated the problem. This is the code.
Thank you all for your help..But no effect..
updated code
It worked...
<script>
$(document).ready(function(){
$(".edit").click(function(event) {
event.preventDefault(); //<--- to prevent the default behaviour
var box = 1233;
var size=123;
var itemname=123;
var potency=123;
var quantity=12333;
var dataString ={
'box' :box,
'size':size ,
'itemname':itemname,
'potency':potency,
'quantity':quantity
};
$.ajax({
url: "dd.php",
type: "post",
data: dataString,
success: function(data) {
alert(data);
},
error: function(data) {
alert(data);
}
});
});
});
</script>
So I click the link,it navigates, to dd.php which has
<?php
echo json_encode(array('itemcode'=>$_POST['itemname']));
echo $_POST['itemname'];
?>
I get Object Object as alert. What am doing wrong? Pls throw some light here..thanks you..
$(document).ready(function(){
$(".edit").click(function(event) {
event.preventDefault();
var data = {"box":1233,
"size":565,
"itemname":565,
"potency":876,
"quantity":234};
$.ajax({
url: "dd.php",
type: "post",
data: data,
dataType: "json",
success: function(data) {
if(console){
console.log(data);
}
},
error: function(data) {
if(console){
console.log(data);
}
}
});
});
});
few things to consider... you can post data as object..which is clean and easier to use
$(".edit").click(function(event) {
event.preventDefault(); //<--- to prevent the default behaviour
var box = 1233;
....
var dataString ={'box':box,'size':size,'itemname':itemname,'potency':potency,'quantity':quantity};
$.ajax({
url: "dd.php",
type: "post",
data: dataString,
dataType: "json", //<--- here this means the response is expected as JSON from the server
success: function(data) {
alert(data.itemcode); //<--here alert itemcode
},
error: function(data) {
alert(data);
}
});
so you need to send the response as json in PHP
<?php
echo json_encode(array('itemcode'=>$_POST['itemname']))
?>
Here you are using querystring as sent in GET request.
If you want to send the data in same form, you can use this with GET request type:
$.ajax({
url: "dd.php"+dataString,
type: "get",
dataType: "json",
success: function(data) {
console.log(data);
alert(data.itemcode);
},
error: function(data) {
alert(data);
}
});
Or for POST request,you will have to put data in json object form, So you can use :
var dataString ={
'box' :box,
'size':size ,
'itemname':itemname,
'potency':potency,
'quantity':quantity
};
$.ajax({
url: "dd.php",
type: "post",
data: dataString,
dataType: "json",
success: function(data) {
console.log(data);
alert(data.itemcode);
},
error: function(data) {
alert(data);
}
});
});
And put echo in your php code :
<?php
echo json_encode(array('itemcode'=>$_POST['itemname']))
?>
Javascript alert shows [Object object] for object. You can see response using console.log or can use that key with alert.
For more information, refer jQuery.ajax()