JavaScript alerts that JSON.parse object is undefined - javascript

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).

Related

laravel ajax unexpected end of json input

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.

How to properly get form data with JQuery and formData

I am trying to upload some form data using ajax and php but for some reason my data is not being catch or passed.
Here is what I have:
form.html ( basic form with 3 text inputs and 1 file)
<form class="form" id="superform" action="nada.php" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="tituloQuiz">Resultado:</label>
<input type="text" class="form-control resultado" id="titulo" name="titulo" placeholder="Ex: Paris">
</div>
<div class="form-group">
<label for="desc">Descrição do Site:</label>
<textarea class="form-control" id="desc" name="descricao" placeholder="Ex:"></textarea>
</div>
<div class="form-group">
<label for="desc">OG FB DESC:</label>
<textarea class="form-control" id="facedes" name="descricao" placeholder="facebook description"></textarea>
</div>
<div class="form-group">
<label for="imggrande">Imagem</label>
<input type="file" id="imggrande" name="imgres">
<p class="help-block">Imagem usada na página de resultado e Facebook 600 x 400.</p>
</div>
<button type="button" class="btn btn-primary btn-lg addres">Adicionar Resultado</button>
<button type="button" class="btn btn-danger btn-lg">Próxima Etapa</button>
</form>
And here is the JS that makes the ajax call:
myjs.js
$("document").ready(function(){
$('.row').on('click','.addres',function(){
console.log('Click Detectado');
var formulario = $('#superform');
var formData = new FormData(formulario);
$.ajax({
type: "POST",
url: "addres.php",
data: formData,
async: false,
success: function(data) {
console.log('Funcionou');
},
error: function(data) {
console.log('Erro no formulario');
},
cache: false,
contetType: false,
processData: false
});
});
});
Nothing is being passed and the POST call is empty (See screenshots below).
**addres.php**
<?php
var_dump($_FILES);
var_dump($_POST);
?>
$.ajax({
url: 'address.php',
type: 'POST',
data: new FormData($('#superform')[0]), // The form with the file inputs.
processData: false, // Using FormData, no need to process data.
contentType:false
}).done(function(){
console.log("Success: Files sent!");
}).fail(function(){
console.log("An error occurred, the files couldn't be sent!");
});
When one sets the contentType option to false, it forces jQuery not to add a Content-Type header, otherwise, the boundary string will be missing from it. Also, when submitting files via multi-part/form one must leave the processData flag set to false, otherwise, jQuery will try to convert your FormData into a string, which will fail.
read from php using
$_FILES['file-0']
(There is only one file, file-0, unless you specified the multiple attribute on your file input, in which case, the numbers will increment with each file.)
Additional info:
See for yourself the difference of how your formData is passed to your php page by using console.log().
var formData = new FormData($('#superform')[0]);
console.log(formData);
var formDataSerialized = $('#superform').serialize();
console.log(formDataSerialized);
Hope this helps.
extra information read this upload files asynchronously
Note : formData doesn't work in IE 9
You can use .serializeArray() to get the data in array format and then convert it into an object. like this:
function getFormData(formId) {
let formData = {};
let inputs = $('#'+formId).serializeArray();
$.each(inputs, function (i, input) {
formData[input.name] = input.value;
});
return formData;
}

AJAX cannot return Json data

I'm trying to post a piece of Json data to AJAX and get a "upvote_message" in return. However, the "upvote_message" is returned as undefined.
Code:
<div class="media">
<div class="media-body">
<p align="right">
<span href="javascript:;" rel="1" class="upvote">Text to be replaced</span>
</p>
</div>
</div>
JS:
<script type="text/javascript">
$(function(){
$('.media .media-body .upvote').click(function(){
var this_a = $(this);
var comment_id = $(this).closest('span').attr('rel');
$.ajax({
type:"POST",
url: base_url + "/upvote",
data:{comment_id : comment_id},
dataType: "json",
success: function(data,status){
if(data.state == 'succ')
{
this_a.html(upvote_msg);
}
else
{
this_a.html(upvote_msg);
}
}
});
});
});
</script>
PHP
public function upvote (){
$comment_id = $this->input->post('comment_id');
if($comment_id==5){
echo json_encode(array('state' => 'succ','upvote_msg'=>'haha'));
}
else{
echo json_encode(array('state' => 'fail','upvote_msg'=>'bam'));
}
exit();
}
}
The PHP and AJAX's write-into part works fine. Data is also registered in database.
The issue is that the 'upvote_msg' is shown as "undefined" when being returned to the Javascript.
How to fix this? Many thanks,
upvote_msg is a property of the data object so it should be data.upvote_msg
To get upvote_msg value you have to use
data.upvote_msg or data["upvote_msg"]

AJAX pass data to PHP

I've been searching this forum, but I had no good result. I have this HTML:
<form method="post" id="postform">
<input type="text" name="message" id="message" placeholder='Say "Hello!"' class="mymessage" maxlength="255"/>
<br />
<input id="submit" type="button" value="Send"/>
</form>
PHP:
<?php
include ('connect.php');
session_start();
if (isset($_POST['message'])){
mysql_query("INSERT INTO messages VALUES ('','".$_POST['message']."','".$_SESSION['user']."')");
}
?>
And jQuery:
$('#submit').click(
function(){
var message = $('#message').val();
$.ajax({
url: post.php,
type:'POST',
data: {"message":message}
});
});
I need to pass #message content to PHP without refreshig the page. This is what I've made, but it's not working.
Check your syntax:
Wrap url with quotes '
Remove single quotes around 'message' variable
$.ajax({
url: 'post.php',
type: 'POST',
data: {message : message}
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
See the first example of $.ajax() at the bottom of its documentation page.
I need to pass #message content to PHP without refreshig the page.
Handle form submit instead:
$("#postform").submit(function(){
var message = $('#message').val();
$.ajax({
url: 'post.php',
type:'POST',
data: {message:message}
}).done(function( data) {
// handle response from the server in case of success.
});
return false; //to prevent submitting and refreshing the page.
});

JSON response opens as a file, but I can't access it with JavaScript

In the code below I make a POST request to a servlet that replies in this way:
response.setContentType("application/json");
json = "{success:true,sessionUid:\""+sessionUid+"\"}";
response.getWriter().write(json);
So Firefox opens it like a file and I can see it's ok. Here you have the JSON:
{success:true,sessionUid:"D07WC15R7LFRFRGPF4P5"}
The problem is that I can't inspect the JSON object. It seems not to exist inside my callback function (also using Firebug). Take a look to the code and alerts.
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#loginForm").submit(function(response){
alert("response="+response); //output: "response=[object Object]"
var obj = jQuery.parseJSON(response);
alert("obj.sessionUid="+obj.sessionUid); //doesn't work, Firebug says "obj is null"
if (response.success == true){ //never true
document.location.href = 'http://localhost:8080/QuoteroClient/logged.jsp';
}else{
alert("Something went wrong in the login process.");
}
return false;
});
});
</script>
</head>
<body>
<form id="loginForm" action="http://localhost:8080/QuoteroClient/Main?servlet=Security" method="post">
<fieldset><legend>Login to Quotero:</legend>
<label>Action:</label><input type="text" name="action" value="login"/><br />
<label>Username:</label><input type="text" name="login-quotero" value="admin"/><br />
<label>Password:</label><input type="text" name="password-quotero" value="admin" /><br />
<label>Domain:</label><input type="text" name="combo-domain" value="Quotero" /><br />
</fieldset>
<input type="submit" value="Submit" />
</form>
</body>
</html>
EDIT: I also tried to do the same with an AJAX request, wothout success:
$("#ajaxSubmit").click(function () {
$.ajax({
type: "GET", //GET or POST is the same for this servlet
url: "http://localhost:8080/QuoteroClient/Main?servlet=Security&action=login&login-quotero=admin&password-quotero=admin&combo-domain=Quotero",
dataType: "json",
success: function (response) {
alert("response=" + response);
var obj = jQuery.parseJSON("" + response);
alert("obj.sessionUid=" + obj.sessionUid);
if (response.success == true) {
document.location.href = contextPath + 'http://localhost:8080/QuoteroClient/logged.jsp';
} else {
alert("Something went wrong in the login process.");
}
}
});
return false;
});
This is not valid JSON:
{success:true,sessionUid:"D07WC15R7LFRFRGPF4P5"}
This is valid JSON:
{"success":true,"sessionUid":"D07WC15R7LFRFRGPF4P5"}
In JSON the keys must always be quoted. See DEMO.
I think you have mixed up ajax with submit. submit is just simply an event, when form is submitted do the following. then you can
$("#loginForm").submit(function(){
var post_data = $(this).serialize();
$.ajax({
url: '',//url of the php file that handles the forms
type: 'GET',
dataType:'json',
data:post_data,//this are the query strings, e.g. ?q=blabla&s=blabla
success:function (data){//if page was 200 or successfully loaded
alert(data.sessionUid);
// do what ever you wish with the data here
},
error: function (){
alert('Page failed to load');
}
})
return false;
});

Categories