[object Object]parsererrorSyntaxError: Unexpected token < in JSON at position 0 - javascript

I am insert the data in mysql database using ajax on submitting this error will appaer .I am making this
in codeigniter framework. I am new bie to ajax.I am not able to figure out where am going wrong .Here is my code
$('#btnSave').text('saving...'); //change button text
$('#btnSave').attr('disabled', true); //set button disable
var url;
// if (save_method == 'add') {
url = "http://[::1]/sms/sms/forms/1";
// } else {
// url = "";
//// }
var radio=$('#radio').val();
var st_id=$('#st_id').val();
var branch_type=$('#branch_type').val();
bname=$('#bname').val();
bcode=$('#bcode').val();
baddress=$('#baddress').val();
var bcity=$('#bcity').val();
var zcode=$('#zcode').val();
var bstates=$('#bstates').val();
var bcountry=$('#bcountry').val();
var bpno=$('#bpno').val();
var bemail=$('#bemail').val();
var bweb=$('#bweb').val();
var Latitude=$('#Latitude').val();
var Longtitude=$('#Longtitude').val();
var noted=$('#noted').val();
var addedby=$('#addedby').val();
// ajax adding data to database
$.ajax({
type: 'ajax',
data: {st_id: st_id, branch_type: branch_type, bname: bname, bcode: bcode, baddress: baddress,
bcity: bcity, zcode: zcode, bstates: bstates, bcountry: bcountry, bpno: bpno, bemail: bemail,
bweb: bweb, Latitude: Latitude, Longtitude: Longtitude, noted: noted, addedby: addedby},
url: url,
method: 'post',
asysc: false,
dataType: 'json',
success: function (data) {
if (data.status) //if success close modal and reload ajax table
{
}
else {
}
$('#btnSave').text('Add Record'); //change button text
$('#btnSave').attr('disabled', false); //set button enable
},
error: function (jqXHR, textStatus, errorThrown) {
alert(jqXHR + textStatus + errorThrown);
$('#btnSave').text('Add Record'); //change button text
$('#btnSave').attr('disabled', false); //set button enable
//
}
});
my php code
$submit['sys_t_id']=$this->input->post('st_id');
$submit['t_id']=$this->input->post('branch_type');
$submit['name']=$this->input->post('bname');
$submit['code']=$this->input->post('bcode');
$submit['address']=$this->input->post('baddress');
$submit['city']=$this->input->post('bcity');
$submit['zip']=$this->input->post('zcode');
$submit['state']=$this->input->post('bstates');
$submit['country']=$this->input->post('bcountry');
$submit['contact_no']=$this->input->post('bpno');
$submit['email']=$this->input->post('bemail');
$submit['web']=$this->input->post('bweb');
$submit['latitude']=$this->input->post('Latitude');
$submit['longitude']=$this->input->post('Longtitude');
$submit['note']=$this->input->post('noted');
$submit['addedby']=$this->input->post('addedby');
$submit['addedon']=date('Y-m-d:H-m-s');
$insert = $this->Smsmodal->insert('branch_info',$submit);
echo json_encode(array("status" => TRUE));

I think you have server error! Use console.log(data) in you success function for see server output.

Related

Ajax form doesn't submits data to php on first click but submits on second click

I have a form that submits through ajax. At first click it sends the request to php but doesnt send post variables and however when i submit form for second or third time it submits the form and gets the success response. The ajax request doesn't fail on first click it just doesnt send data to php.When i check the network tab request fields show up there on the first click and have correct values but doesnt reach php. Here is my code
jQuery("#bidding-form").on('submit', function(e) {
var request_english_level = jQuery('#request_english_level').val();
var job_title = jQuery('#job_title').val();
var request_type = jQuery('#request_type').val();
var estimated_hours = jQuery('#estimated_hours').val();
var designation = jQuery('#designation').val();
var service_type = jQuery('#service_type').val();
var budget = jQuery("#budget").val();
var user_id = jQuery('#user_id').val();
var locations = jQuery('#location').val();
var payment_terms = jQuery('#payment_terms').val();
var application_no = jQuery('#application_no').val();
var deadline_apply = jQuery('#deadline_apply').val();
var close_date = jQuery('#close_date').val();
var delivery_deadline = jQuery('#delivery_deadline').val();
var experience = jQuery('#consultant_experience').val();
var description = jQuery('#request_description').val();
var formdata = new FormData();
var length = jQuery(".attachment")[0].files.length;
for (i = 0; i < length; i++) {
formdata.append('file[]', jQuery(".attachment")[0].files[i]);
}
formdata.append('action', 'save_bid_info');
var checked_skills = []
jQuery("input[name='request_skills[]']:checked").each(function() {
//checked_skills.push(parseInt(jQuery(this).val()));
formdata.append('request_skills[]', parseInt(jQuery(this).val()));
});
var languages = []
jQuery("input[name='languages[]']:checked").each(function() {
//languages.push(parseInt(jQuery(this).val()));
formdata.append('languages[]', parseInt(jQuery(this).val()));
});
formdata.append('designation', designation);
// formdata.append('request_skills', checked_skills);
formdata.append('request_type', request_type);
formdata.append('estimated_hours', estimated_hours);
formdata.append('service_type', service_type);
formdata.append('delivery_deadline', delivery_deadline);
formdata.append('job_title', job_title);
formdata.append('locations', locations);
formdata.append('request_type', request_type);
formdata.append('payment_terms', payment_terms);
formdata.append('application_no', application_no);
formdata.append('deadline_apply', deadline_apply);
formdata.append('close_date', close_date);
formdata.append('experience', experience);
formdata.append('description', description);
formdata.append('budget', budget);
// formdata.append('languages', languages);
formdata.append('request_english_level', request_english_level);
e.preventDefault();
jQuery.ajax({
url: ajax_url,
type: 'post',
dataType: 'json',
contentType: false,
cache: false,
processData: false,
data: formdata,
beforeSend: function() {
jQuery(".loader").show();
},
complete: function(data) {
jQuery('.loader').hide();
}
})
.done(function(response, textStatus, jqXHR) {
if (response.success == true) {
jQuery(".ajax-processor").hide();
} else {
jQuery(".ajax-processor").find('p').html(response.msg);
}
})
.fail(function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
})
});
// PHP CODE
if(isset($_POST['budget']) && !empty($_POST['budget']))
{
// on second click this is executed
}
else
{
// on first click this is executed
}

Codeigniter & Ajax - Condition statement in javascript

Im quiet confused with this code. Im reading this code of ajax which inserts the data automatically. but what im confused is this line if(result=='12') then trigger ajax what does 12 means why it should be 12 then conditioned to before ajax. Apparently im still learning ajax thanks. P.S this is working well btw im just confused with the code
here is the full code of the create function javascript / ajax
$('#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 result = '';
if(empoyeeName.val()==''){
empoyeeName.parent().parent().addClass('has-error');
}else{
empoyeeName.parent().parent().removeClass('has-error');
result +='1'; //ALSO THIS NUMBER 1 WHY SHOULD IT BE 1?
}
if(address.val()==''){
address.parent().parent().addClass('has-error');
}else{
address.parent().parent().removeClass('has-error');
result +='2'; //ALSO THIS NUMBER 2 WHY SHOULD IT BE 2?
}
if(result=='12'){ //HERE IS WHAT IM CONFUSED
$.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('Employee '+type+' successfully').fadeIn().delay(4000).fadeOut('slow');
showAllEmployee();
}else{
alert('Error');
}
},
error: function(){
alert('Could not add data');
}
});
}
});
As I have explained in my commentaries, and since you wanted an example. This is how I will proceed in order to avoid checking for result == '12':
$('#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 formValid = true;
if (empoyeeName.val() == '')
{
empoyeeName.parent().parent().addClass('has-error');
formValid = false;
}
else
{
empoyeeName.parent().parent().removeClass('has-error');
}
if (address.val() == '')
{
address.parent().parent().addClass('has-error');
formValid = false;
}
else
{
address.parent().parent().removeClass('has-error');
}
// If form is not valid, return here.
if (!formValid)
return;
// Otherwise, do the ajax call...
$.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();
var type = '';
if (response.type=='add')
type = 'added';
else if (response.type=='update')
type ="updated";
$('.alert-success').html('Employee ' + type + 'successfully')
.fadeIn().delay(4000).fadeOut('slow');
showAllEmployee();
}
else
{
alert('Error');
}
},
error: function()
{
alert('Could not add data');
}
});
});
It's just checking existence of values and appending string to it.
if(empoyeeName.val()=='')
This check empty name and add error if name is empty. else it concat 1 to result.
if(address.val()=='')
This check empty address and add error if address is empty. else it concat 2 to result.
So if both of them are non empty that means result will be 12 and than only you make ajax call else show error.

500 Internal server error when save proccess using ajax

I want to ask why my codeigniter when add data become error 500 internal server when the save proccess. I dont know anything about this problem please help me all.
This is ajax code in view
function save()
{
$('#btnSave').text('menyimpan...'); //change button text
$('#btnSave').attr('disabled',true); //set button disable
var url;
if(save_method == 'add') {
url = "<?php echo site_url('edulibs/ajax_add')?>";
} else {
url = "<?php echo site_url('edulibs/ajax_update')?>";
}
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function(data)
{
if(data.status) //if success close modal and reload ajax table
{
$('#modal_form').modal('hide');
reload_table();
}
else
{
for (var i = 0; i < data.inputerror.length; i++)
{
$('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-error'); //select parent twice to select div form-group class and add has-error class
$('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]); //select span help-block class set text error string
}
}
$('#btnSave').text('Simpan'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('menambahkan / update data error');
$('#btnSave').text('Simpan'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
}
});
}
And this is my controller
public function ajax_add()
{
$this->_validate();
$data = array(
'nama' => $this->input->post('nama'),
'nim' => $this->input->post('nim'),
'pembimbing1' => $this->input->post('pembimbing1'),
'pembimbing2' => $this->input->post('pembimbing2'),
'subyek' => $this->input->post('subyek'),
'judul' => $this->input->post('judul'),
'tanggal' => $this->input->post('tanggal'),
'tautan' => $this->input->post('tautan'),
);
$insert = $this->edulibs->save($data);
echo json_encode(array("status" => TRUE));
}
In order to use site_url() load url helper in your controller first.like this..
$this->load->helper('url');
OR load helper in application/config/autoload.php
And in success function of your ajax use JSON.parse() to parse your json response into object.Like this
success: function(response)
{
var data = JSON.parse(response);//OR var data = eval(response);
if(data.status) //if success close modal and reload ajax table
{
//code here
}
else
{
//code here
}

How to achieve the same behaviour in Ajax

$usrname = $this->session->userdata('username');
$password = $this->session->userdata('password');
$data = array('userName'=>urlencode($usrname),'password'=>urlencode($password));
$data_string = json_encode($data);
$datanew = "loginemployee=". $data_string;
$method = 'post';
$format = 'application/json';
$this->rest->format($format);
$login_url = $this->login_url;
//print_r($login_url);
//exit;
$result = $this->rest->{$method}($login_url, $datanew);
Can anybody please assist me with this. This is actually a PHP script to login into a website, I need to achieve the same on my Cordova app which uses only HTML and JQuery, so please provide me info on how to do this.
$(document).ready(function(){
$('form#loginForm').submit(function() { // loginForm is submitted
var username = $('#username').attr('value'); // get username
var password = $('#password').attr('value'); // get password
alert(username);
var UserData= {"userName":username , "password":password};
var jsonString=JSON.stringify(UserData);
var datanew = "loginemployee=". $jsonString;
if(jsonString)
{
alert("encoded"+jsonString);
}
if (username && password) { // values are not empty
$.ajax({
type: "POST",
url: "http:// i know URL", // URL
contentType: "application/json; charset=utf-8",
dataType: "json",
// send username and password as parameters
data: datanew, // script call was *not* successful
error: function (XMLHttpRequest, textStatus, errorThrown) {
$('div#loginResult').text("responseText: " + XMLHttpRequest.responseText + ", textStatus: " + textStatus + ", `enter code here`errorThrown: " + errorThrown);
$('div#loginResult').addClass("error");
}, // error
// script call was successful
// data contains the JSON values returned by the Perl script
success: function (data) {
alert("success");
if (data.error) { // script returned error
$('div#loginResult').text("data.error: " + data.error);
$('div#loginResult').addClass("error");
} // if
else { // login was successful
alert(data);
console.log(data);
$('form#loginForm').hide();
$("#loginResult").append('all good');
} //else
} // success
}); // ajax/ if
} // if
else {
$('div#loginResult').text("enter username and password");
$('div#loginResult').addClass("error");
} // else
$('div#loginResult').fadeIn();
return false;
});
});
You have done some mistakes in code and I listed those thing below.
Don't use $('#username').attr('value'). Instead of use $('#username').val(). Because $('#username').attr('value') return the value of the element while the html created. But $('#username').val() will return the current value. Same as change $('#password').attr('value') to $('#password').val(). For more information check this post.
Concatenation operator in javascript is + not .. And also u added a variable like $jsonString.
In your Server php code, if your using $_POST['loginemployee'] to retrieve the post values means don't use contentType: "application/json; charset=utf-8",. Because it will use the entire content including key as invalid json like loginemployee={"userName":"cloud","password":"cloudnine"}. If you need like that means u need to use file_get_contents('php://input') to retrieve the post content. But better don't use contentType in ajax. So you can able to easily get the post content using $_POST['loginemployee'].
And also if the reply is json means use dataType in ajax, else dont use that. For more information about contentType and dataType check this post.
So, I updated the code. Check and reply back if there is any issues. Hope it will work as your wish.
$(document).ready(function(){
$('form#loginForm').submit(function() { // loginForm is submitted
var username = $('#username').val(); // get username
var password = $('#password').val(); // get password
alert(username);
var UserData= {"userName":username , "password":password};
var jsonString=JSON.stringify(UserData);
var datanew = "loginemployee="+ jsonString;
if(jsonString)
{
alert("encoded"+jsonString);
}
if (username && password) { // values are not empty
console.log(datanew);
$.ajax({
type: "POST",
url: "http://url_to_post", // URL
// contentType: "application/json; charset=utf-8",
// If reply is json means uncomment the below line.
// dataType: "json",
// send username and password as parameters
crossDomain : true,
data: datanew, // script call was *not* successful
error: function (XMLHttpRequest, textStatus, errorThrown) {
$('div#loginResult').text("responseText: " + XMLHttpRequest.responseText + ", textStatus: " + textStatus + ", `enter code here`errorThrown: " + errorThrown);
$('div#loginResult').addClass("error");
}, // error
// script call was successful
// data contains the JSON values returned by the Perl script
success: function (data) {
alert("success");
if (data.error) { // script returned error
$('div#loginResult').text("data.error: " + data.error);
$('div#loginResult').addClass("error");
} // if
else { // login was successful
console.log(data);
$('form#loginForm').hide();
$("#loginResult").append('all good');
} //else
} // success
}); // ajax/ if
} // if
else {
$('div#loginResult').text("enter username and password");
$('div#loginResult').addClass("error");
} // else
$('div#loginResult').fadeIn();
return false;
});
});

Get ajax success and hide form while loading?

I am trying to do an ajax registration, the following works good, it gets the data from a php function I wrote somewhere else and the registration and messages for both error and success work. But I am basically looking at:
hiding the form once the submit button is pressed
display a rotating icon,
then if success get a success message and no form
otherwise display an error.
Code:
var ajaxurl = '<?php echo admin_url('admin-ajax.php') ?>';
jQuery('#register-me').on('click',function(){
var action = 'register_action';
var username = jQuery("#st-username").val();
var mail_id = jQuery("#st-email").val();
var firname = jQuery("#st-fname").val();
var lasname = jQuery("#st-lname").val();
var passwrd = jQuery("#st-psw").val();
var ajaxdata = {
action: 'register_action',
username: username,
mail_id: mail_id,
firname: firname,
lasname: lasname,
passwrd: passwrd,
}
jQuery.post( ajaxurl, ajaxdata, function(res){
jQuery("#error-message").html(res);
});
Add id="myform" to the form element, then:
$("#myform").hide();
About the icon. When you click the button you could make the icon visible and when succeed or error then hide again.
jQuery('#register-me').on('click',function(){
$("#myform").hide();
jQuery('#loadingmessage').show();
var action = 'register_action';
var username = jQuery("#st-username").val();
var mail_id = jQuery("#st-email").val();
var firname = jQuery("#st-fname").val();
var lasname = jQuery("#st-lname").val();
var passwrd = jQuery("#st-psw").val();
var ajaxdata = {
action: 'register_action',
username: username,
mail_id: mail_id,
firname: firname,
lasname: lasname,
passwrd: passwrd,
}
jQuery.post( ajaxurl, ajaxdata, function(res){
$('#loadingmessage').hide(); // hide the loading message
$("#myform").show();
jQuery("#error-message").html(res);
});
});
An id to the form, and add a div with an image, give it an id and hide it with css.
You could use the deferred options here:
jQuery('#register-me').on('click', function () {
var action = 'register_action';
var username = jQuery("#st-username").val();
var mail_id = jQuery("#st-email").val();
var firname = jQuery("#st-fname").val();
var lasname = jQuery("#st-lname").val();
var passwrd = jQuery("#st-psw").val();
var ajaxdata = {
action: 'register_action',
username: username,
mail_id: mail_id,
firname: firname,
lasname: lasname,
passwrd: passwrd
};
jQuery.post(ajaxurl, ajaxdata)
.beforeSend(function (data, textSttus, jqxhr) {
$('#myform').hide();
alert('Show the spinner');
$('#spinner').show();
})
.done(function (data, jqxhr, settings ) {
alert("success");
})
.fail(function (event, jqxhr, settings, exception) {
alert("oops, fail");
$('#myform').show();
})
.always(function (event, jqxhr, settings ) {
alert('hide the spinner please');
$('#spinner').hide();
});
});

Categories