laravel ajax unexpected end of json input - javascript

Hello guys i am desperate i am not getting completly this syntax / concept of Ajax.
I have 2 forms on my page. Based on the value of the hidden field a certain logic in my controller will be executed. Its simple actually -- i thought. I am trying to pass an array from my ajax to my controller and then passing it back to my view. I know it doesnt make much sense. But i am trying to understand how that works. The first logic gets executed but the other one gets me this error:
jqXHR is : [object Object] textStatus is : parsererror errorThrown is : SyntaxError: Unexpected end of JSON input
Why is that ? Can you guys please give me an advice.
Update
I tried not to put the whole code and just reduce it to the main question. But since it caused confusion of the rootcause i will show the whole code of the parts which might be relevant. I edited the question to the below.
BLADE
<center>
<div class="col-md-12">
<h3>xlsx, xls, ods, csv to Text</h3>
<form id="xlsForm" enctype="multipart/form-data">
#csrf
<input type="file" name="excelfile" />
<input name ="loadSubmit" id="loadSubmit" type="submit"/>
<input type ="hidden" name="load" value="0">
</form>
</div>
</center>
<div class ="row">
<div class ="col-md-3">
<div class="container mt-5">
<h2 id="words" class="mb-4">Skills found</h2>
</div>
<form id="xlsFormUpdate" enctype="multipart/form-data">
<input type ="hidden" name="load" value="1">
<div id="inner">
</div>
<input name ="updateSubmit" id="updateSubmit" type="submit"/>
</form>
</div>
<div class ="col-md-9">
#include('layouts.partials.datatable')
</div>
</div>
Controller:
if ($request->input('load') == '0') {
//some code -- this works fine
return response()->json($data); //This data can be send - no problem
} elseif (($request->input('load') == '1')) {
$data = $request->post('checkbox_array');
return response->json($data); // i tried json_encode too .. not working.
}
Jquery code
$(document).ready(function(){
$('#xlsForm').submit(function uploadFile(event){
event.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: "{{route('ExcelToArray')}}",
method: 'POST',
data: new FormData(this),
dataType: 'JSON',
contentType: false,
cache: false,
processData: false,
success:function (response) {
$("#inner").empty();
$.each(response,function(index,value){
$("#inner").append
('<div class="row">' +
'<div class="col-xs-2">'+
'<input type="checkbox" class="'+value+'" value="'+value+'" name="checkbox[]" checked > <label style="font-weight: bold" for="skillChoice_'+index+'">'+value+' </label>' +
'</div>'+
'<div class="col-xs-1">'+
'<input class="'+value+'" type="number" name="weight[]" min="1" max="3" value="1"> '+
'</div>'+
'</div>');
});
}
});
});
$('#xlsFormUpdate').submit(function uploadFile(event) {
event.preventDefault();
var checkbox_array = [];
$('input[type=checkbox]').each(function (index,value) {
if (this.checked)
{
checkbox_array.push(1);
}
else {
checkbox_array.push(0);
}
});
let checkbox_s = JSON.stringify(checkbox_array)
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: "{{route('ExcelToArray')}}",
method: "POST",
data: {checkbox_array:checkbox_s},
dataType: 'JSON',
contentType: false,
cache: false,
processData: false,
success: function (response) {
alert('The Response is ' + response);
},
error: function (jqXHR, textStatus, errorThrown) {
alert('jqXHR is : ' + jqXHR
+ 'textStatus is : ' + textStatus
+ ' errorThrown is : ' + errorThrown);
},
})
});
});

When using ajax submit event to send data to controller, the data in the field data: {checkbox_array:checkbox_s}, will be send to the controller. Since the input field load was never sent, the elseif (($request->input('load') == '1')) clause was never true and the controller was never going into that section and was never returning the right response. The data had to be changed like this var my_datas JSON.stringify({mydata:checkbox_array, load: "1"}); and then in ajax the data could be send like data:my_datas. In controller the field load can then be processed.

Related

jquery AJAX Post not working Codeigniter

I am currently learning jquery AJAX, i am trying to change my standar php post to AJAX but not working, it's still prosses with php, not AJAX. Not even in the console show anything. Can anyone check my code ?
I am using Codeigniter. And you can asume the php part is working fine ..
HTML :
<form action="<?=base_url()?>operator_pt/unggah/unggah_semua" id="unggahsemua" method="POST" name="unggahsemua" role="form">
<?php foreach($data as $rod)
$tahun = $rod->id_smt;
$jurusan = $rod->id_sms;
?>
<div id="form-tahun" class="form-group">
<input type="hidden" class="form-control" id="tahun" name="tahun" value="<?php echo $tahun;?>">
</div>
<div id="form-jurusan" class="form-group">
<input type="hidden" class="form-control" id="jurusan" name="jurusan" value="<?php echo $jurusan;?>">
</div>
Sedang Mengunggah :
<div id="statmhs"> </div>
<div id="statidmhs"> </div>
<div id="statdsnpt"> </div>
<i class="fa fa-circle-o-notch fa-spin" style="font-size:24px"></i>
JS :
$(document).ready(function() {
$('#unggahsemua').submit(function(event) {
$('.form-group').removeClass('has-error');
$('.help-block').remove();
var formData = {
'tahun' : $('input[name=tahun]').val(),
'jurusan' : $('input[name=jurusan]').val(),
};
// process the form
$.ajax({
type : 'POST',
url : '<?=base_url()?>operator_pt/unggah/unggah_semua', // the url where we want to POST
data : formData,
dataType : 'json',
encode : true
})
.done(function(data) {
console.log(data);
$('#statmhs').append('<div class="help-block">' + data.infounggahmhs + '</div>');
$('#statidmhs').append('<div class="help-block">' + data.infounggahidmhs + '</div>');
$('#statdsnpt').append('<div class="help-block">' + data.infounggahdsnpt + '</div>');
.fail(function(data) {
console.log(data);
});
event.preventDefault();
});
});
You have errors in your Javascript code..
You missed the closing brackets before the .fail method. Also you had an extra comma after the last entry of your formData object
Try changing to this:
$(document).ready(function () {
$('#unggahsemua').submit(function (event) {
$('.form-group').removeClass('has-error');
$('.help-block').remove();
var formData = {
'tahun': $('input[name=tahun]').val(),
'jurusan': $('input[name=jurusan]').val()
};
// process the form
$.ajax({
type: 'POST',
url: '<?=base_url()?>operator_pt/unggah/unggah_semua', // the url where we want to POST
data: formData,
dataType: 'json',
encode: true
})
.done(function (data) {
console.log(data);
$('#statmhs').append('<div class="help-block">' + data.infounggahmhs + '</div>');
$('#statidmhs').append('<div class="help-block">' + data.infounggahidmhs + '</div>');
$('#statdsnpt').append('<div class="help-block">' + data.infounggahdsnpt + '</div>');
})
.fail(function (data) {
console.log(data);
});
event.preventDefault();
});
});
You have to stop default execution of form submit as you have to do it with ajax.
$(document).ready(function () {
$('#unggahsemua').submit(function (event) {
event.preventDefault() //<------- Add this line
$('.form-group').removeClass('has-error');
$('.help-block').remove();
var formData = {
'tahun': $('input[name=tahun]').val(),
'jurusan': $('input[name=jurusan]').val()
};
// process the form
$.ajax({
type: 'POST',
url: '<?=base_url()?>operator_pt/unggah/unggah_semua', // the url where we want to POST
data: formData,
dataType: 'json',
encode: true
})
.done(function (data) {
console.log(data);
$('#statmhs').append('<div class="help-block">' + data.infounggahmhs + '</div>');
$('#statidmhs').append('<div class="help-block">' + data.infounggahidmhs + '</div>');
$('#statdsnpt').append('<div class="help-block">' + data.infounggahdsnpt + '</div>');
})
.fail(function (data) {
console.log(data);
});
});
});
if you use form action="" method="POST" name="" role="form", make sure in config.php change $config['csrf_protection'] = TRUE; to FALSE.
But, if you want to set it TRUE you must use form_open()

ajax form submits blank description to only first ids

I have below code for submitting the form with ajax but only first instances out of 5 comment box are being submitted for balance I am getting discription=" and also being inserted to the wrong id. here is my code and live example. I want to allow users to comment on any items
http://way2enjoy.com/app/jokestest-991-1.php
$output .='<div id="'.$idd.'" align="left" class="messagelove_box" ><div class="content_box_1">
<div class="content_box_2z"><sup class="joke_icon"></sup></div>
<div class="content_box_3_title"></div>
<div class="content_box_3_text">'.nl2br($cont).'</div>
<script type="text/javascript">
var ajaxSubmit = function(formEl) {
var url = $(formEl).attr(\'action\');
var comment=document.getElementById("jokes_comment").value;
var joke_id=document.getElementById("joke_id_hidden'. $idd.'").value;
$.ajax({
url: url,
data:{
\'action\':\'addComment\',
\'comment\':comment,
\'joke_id\':joke_id
},
dataType: \'json\',
type:\'POST\',
success: function(result) {
console.log(result);
$.ajax({
url: url,
data:{
\'action\':\'getLastComment\',
\'joke_id\':joke_id
},
dataType: \'json\',
type:\'POST\',
success: function(result) {
$(\'#jokes_comment\').val("");
console.log(result[0].description);
$("#header ul").append(\'<li>\'+result[0].description+\'</li>\');
},
error: function(){
alert(\'failure\');
}
});
},
error: function(){
alert(\'failure\');
}
});
return false;
}
</script>
<div id="header" class="content_box_31_text"><ul id="commentlist" class="justList">'.$contpp.'</ul></div>
<form method="post" action="check/process2.php" class="button-1" onSubmit="return ajaxSubmit(this);"><input type="hidden" value="'. $idd.'" id="joke_id_hidden'. $idd.'"><input type="text" id="jokes_comment" value="" name="jokes_comment">
<input type="submit" value="comment"></form>
</div></div>
';
The code posted doesn't tell the full story, but looking at the URL mentioned does. The snippet you've posted is being repeated over and over again, identically in the page. That means that each definition of the ajaxSubmit function overwrites the previous one, and that you have multiple input elements all with the same id. No wonder the page is confused as to what to do. You only need one submit function, if it's written properly it can handle all the different comment inputs. And your comment inputs can't have the same id each time, but they can have the same CSS class, and since they are all within the form, when we submit a specific form, we know the context we are working in, and jQuery can automatically find all the fields in the form for us, without us having to write code to access them all individually.
So..with that design in mind, define your javascript like this, and make sure it only gets rendered once in your entire page output. I've re-written it slightly to take advantage of the easier syntax provided by jQuery.
$(".comment-form").submit(function(event) {
event.preventDefault(); //prevent the default postback behaviour
var form = $(this);
var jokeID = form.find(".joke_id").val();
$.ajax({
url: form.attr("action"),
type: "POST",
dataType: "json",
data: $(this).serialize(), //automatically finds all the form fields and puts the data in postback-friendly format
success: function(result) {
//I'm not convinced you need this second ajax call - can't you just write the contents of the input box directly into the list? But I'll leave it here in case you want it
$.ajax({
url: form.attr("action"),
type: "POST",
dataType: "json",
data:{
"action":"getLastComment",
"joke_id": jokeID
},
success: function(result) {
form.find(".jokes_comment").val("");
$("#header-" + jokeID + " ul").append("<li>" + result[0].description + "</li>");
},
error: function (jQXHR, textStatus, errorThrown) { //this is the correct definition of the error function as per jQuery docs
alert("An error occurred while contacting the server: " + jQXHR.status + " " + jQXHR.responseText + ".");
}
});
},
error: function (jQXHR, textStatus, errorThrown) { //this is the correct definition of the error function as per jQuery docs
alert("An error occurred while contacting the server: " + jQXHR.status + " " + jQXHR.responseText + ".");
}
});
});
Secondly, make the PHP that generates the comment markup for each joke look like this:
<div id="header-'.$idd.'" class="content_box_31_text">
<ul id="commentlist" class="justList">'.$contpp.'</ul>
</div>
<form method="post" action="check/process2.php" class="button-1 comment-form">
<input type="hidden" value="'. $idd.'" name="joke_id"/>
<input type="hidden" value="addComment" name="action" />
<input type="text" class="jokes_comment" value="" name="comment" />
<input type="submit" value="comment">
</form>

why AJAX redirects to the new page in PHP

I have a form:
<form class="searchForm">
<div class="box_style_1">
<h4><?= Yii::t("common", "Age"); ?></h4>
<?
echo '<b class="badge">3</b> ' . Slider::widget([
'name'=>'age',
'value'=>'250,650',
'sliderColor'=>Slider::TYPE_GREY,
'pluginOptions'=>[
'min'=>3,
'max'=>21,
'step'=>1,
'range'=>true
],
]) . ' <b class="badge">21</b>';
?>
<br /><br />
<input type="submit" value="Search" class="searchByAge"/>
<br /><br />
</div>
</form>
And want to show the result in console.log:
$('.searchByAge').on('click', function(e){
e.preventDefault();
var range = $('.form-control').val();
var min = range.split(',')[0];
var max = range.split(',')[1];
//alert(min+' '+max);
$.ajax({
type: 'POST',
url: '/age/'+min+'/'+max,
data: $('.searchForm').serialize(),
success: function (data) {
console.log(data);
},
error: function(jqXHR, textStatus, errorMessage) {
console.log(errorMessage); // Optional
}
});
})
and that's my AJAX code. But when I click on Search button it redirects me to the new page and nothing in the console log. I do not know what is wrong in my code.
I return a JSON from the '/age/min_age/max_age' page, but the result shows in the new page.
How can I fix this problem?
change code to below. change input type submit to button
<input type="button" value="Search" class="searchByAge"/>
also wrap your code in $(document).ready();
Make sure to add jQuery library from correct path.
$(document).ready(function(){
$('.searchByAge').on('click', function(e){
e.preventDefault();
var range = $('.form-control').val();
var min = range.split(',')[0];
var max = range.split(',')[1];
//alert(min+' '+max);
$.ajax({
type: 'POST',
url: '/age/'+min+'/'+max,
data: $('.searchForm').serialize(),
success: function (data) {
console.log(data);
},
error: function(jqXHR, textStatus, errorMessage) {
console.log(errorMessage); // Optional
}
});
});
});
replace your code
$('.searchByAge').on('click', function(e){
e.preventDefault();
with this
$('form.searchForm').on('submit', function(e){
e.preventDefault();
on first code you are preventing your click event instead of submit event thats why form is still submitting

JavaScript alerts that JSON.parse object is undefined

I just wrote an script to get results from PHP file in json format, but after parsing it using JSON.parse or even jQuery, the object is empty and undefined! Note that the PHP returns the json string and works correctly. Here is the sample result:
{"status":"success","data":{"link":"http://example.com/file.pdf","size":"1 MB"}}
or
{"status":"failure","data":{"error":"some error occured!"}}
Here is a sample of my code:
<script>
jQuery(document).ready(function (){
jQuery('#form').submit(function(event){
jQuery('#loading').show();
var formData = {
id : jQuery('#id').val()
};
jQuery.ajax({
type: 'POST',
url: 'script.php',
data : formData,
datatype: 'json',
cache: false
})
.done(function(response){
jQuery('#loading').hide();
var obj = JSON && JSON.parse(response) || jQuery.parseJSON(response);
alert(obj.result); // here says undefined and also the below if/else doesn't work
if(obj.status == 'success'){
jQuery('#result').html('<span style="color: green;">' + obj.data.link + '</span>');
}
else if(obj.status == 'failure'){
jQuery('#result').html('<span style="color: red;">' + obj.data.error + '</span>');
}
});
event.preventDefault();
});
});
</script>
<div>
<form action="script.php" method="POST" id="form">
<p>
<label for="id">ID:</label>
<input type="text" name="id" id="id">
</p>
<p>
<button type="submit">submit</button>
</p>
</form>
</div>
<div id="loading" style="display: none;"><img src="loading.gif" alt="loading..."></div>
<div id="result"></div>
And I'd previously attached jQuery v1.10.x to the file.
Even though you misspelled the dataType attribute, jQuery will make a guess at the response type and parse it for you. There's no reason to call JSON.parse() (or jQuery.parseJSON).

Knockout Json Mapping Issue

Hi I have a View Which Contains a ADDBasicDetailsForm (This JSP view is rendered using spring MVC)
BasicDetailView.jsp
<div data-bind="if: profileDto.basicDetailsDTO">
<div class="basicDetails">
Contact No :
<b data-bind="value: profileDto.basicDetailsDTO.contactNo"> </b>
contactMailId :
<b data-bind="value: profileDto.basicDetailsDTO.contactMailId"> </b>
</div>
</div>
<form id="BasicDetailsform" method="POST">
<fieldset class="contactMailId">
<input id="contactMailId"
type="text" placeholder="Mail Id" maxlength="32"
name="contactMailId"></input>
</fieldset>
<fieldset class="contactNo name">
<input id="contactNo"
type="text" placeholder="contactNo" maxlength="32" name="contactNo"></input>
</fieldset>
<fieldset class="buttons">
<button class="saveactionbutton" type="submit">SAVE</button>
</fieldset>
</form>
</div>
Inially contact no and conatct mail ID is not shown in UI. It should be shown when i submit the form and i am using knockout for automatic UI referesh.But It is not working
BasicDetails.js
function BasicViewModel() {
var self = this;
}
var viewModel = new BasicViewModel();
$(document).ready(function(){
$("#BasicDetailsform").submit(function(e)
{
var form = $(this);
e.preventDefault(); //STOP default action
var input = '{';
input += '"contactMailId":"'+$('#contactMailId').val()+'",';
input += '"contactNo":"'+$('#contactNo').val()+'"';
input += '}';
alert(input);
$.ajax({
type: "POST",
dataType: "json",
url : "addBasicDetails",
contentType: "application/json; charset=utf-8",
data: input,
dataFilter: function (response) {
return response;
},
async:false,
success: (function(data, textStatus, jqXHR) {
alert("ajax Success");
form.hide();
data = ko.toJSON(data);
alert("JSON Data in Alert"+data );
ko.mapping.fromJSON(data, {}, self);
ko.applyBindings(viewModel);
}),
error : function(data,textStatus,error){
alert("ajax failure");
}
});
});
});
My JSON response from server
{
"basicDetailDTO":{
"contactNo":"86878",
"contactMailId":
"rahuljain#gmail.com"
}
}
After the Form submission details are not getting reflected in my jsp view .
Please let me know where is the issue in my code.

Categories