Getting JSON Error while calling multiple function - javascript

Getting JSON Error while calling multiple function
Error - Uncaught SyntaxError: Unexpected token ' in JSON at position 0
I am calling multiple function in jquery but it is giving error i have tried so much way but the error get changed but it not working what should i do.
HTML
<div id="div1">
<input type="submit"onclick='Function1()'>
<input type="text" value="Text1" id="input1">
<input type="text" value="Text2" id="input2">
</div>
<div id='div2'></div>
jQuery
function Function1(){
var input1 = $("#input1").val();
var input2 = $("#input2").val();
var datajson = { "input1" : input1, "input2" : input2 };
var data = "'"+JSON.stringify(datajson)+"'";
Post_Funtion('testpost.php',data,'$("#div2").html(html);')
}
function Post_Funtion(URl,DATA,FUNCTION){
var url = encodeURIComponent(URl);
var data = JSON.parse(DATA);
$.ajax({
type: "POST",
url: url,
data: data,
cache: false,
success: function(html) {
eval(FUNCTION);
}
});
}

You are trying to JSON.stringify() the post data incorrectly, then turning around and parsing it back to pass to the ajax options.
This whole step is needless. Pass the object through as is and jQuery will take care of it from there
function Function1(){
var input1 = $("#input1").val();
var input2 = $("#input2").val();
var data = { "input1" : input1, "input2" : input2 };
Post_Funtion('testpost.php',data,'$("#div2").html(html);')
}
function Post_Funtion(URl,DATA,FUNCTION){
var url = encodeURIComponent(URl);
$.ajax({
data: DATA,
/* other options the same */
....
}

You are trying to call JSON.parse on a string that looks like this:
'{"input1": input1, "input2": input2}'
That is not well-formed JSON. The outer quotes should be dropped. Try this code:
function Function1(){
var input1 = $("#input1").val();
var input2 = $("#input2").val();
var datajson = { "input1" : input1, "input2" : input2 };
var data = JSON.stringify(datajson) // Removed quotes from JSON
Post_Funtion('testpost.php',data,'$("#div2").html(html);')
}
function Post_Funtion(URl,DATA,FUNCTION){
var url = encodeURIComponent(URl);
var data = JSON.parse(DATA);
$.ajax({
type: "POST",
url: url,
data: data,
cache: false,
success: function(html) {
eval(FUNCTION);
}
});
}

"'"+JSON.stringify(datajson)+"'"; - remove quotes
var data = JSON.stringify(datajson);
Can't see the reason of stringifying and parsing the object back in this case. Try the following:
function Function1(){
var input1 = $("#input1").val();
var input2 = $("#input2").val();
var data = { "input1" : input1, "input2" : input2 };
function cb(response){
$("#div2").html(response);
}
Post_Funtion('testpost.php',data, cb)
}
function Post_Funtion(URl,DATA,FUNCTION){
var url = encodeURIComponent(URl);
console.log(DATA);
$.ajax({
type: "POST",
url: url,
data: DATA,
cache: false,
success: FUNCTION
});
}
PS don't use eval, Why is using the JavaScript eval function a bad idea?

Related

JQuery does not fetch and parse json from url

I have been developing an app to connect with an API I recently built for testing (It is working fine) but I deem to be getting an unknown error with my code. I am a newbie trying out jQuery. This is my code:
$(document).ready(function(){
$.ajax({
url: 'api.lynmerc-enterprise.com/requests',
async: false,
type: 'GET',
//dataType: 'json',
success: function(data){
console.log(data);
var data2 = jQuery.parseJSON(data);
console.log(data2);
//assign parsed JSON to variables
var apiStatus = data2.status;
var apiMessage= data2.message;
var apiData = data2.data;
var data3 = $.parseJSON(apiData);
//Here we get Requester info and material JSON
console.log(data3);
var materials = data3.material;
var data4 = $.parseJSON(materials);
console.log(data4);
//loop through the data and assign needed info to table
$.each(data3, function(i,row){
var dateRequested = data3.date;
var projectCode = data3.p_code;
var requestNumber = data3.rq_no;
var materialName = data4.name;
var purpose = data4.purpose;
var quantity = data4.quantity;
var cost = data4.cost;
var total = data4.total;
$("table.table").append("<tr><td>"+dateRequested+"</td><td>"+projectCode+"</td><td>"+requestNumber+"</td><td>"+materialName+"</td><td>"+purpose+"</td><td>"+quantity+"</td><td>"+cost+"</td><td>"+total+"</td></tr>");
});
},
//error: function(){console.log('Error Encountered')},
beforeSend: setHeader()
});
});
//set required headers
function setHeader(xhr){
xhr.setRequestHeader('Api-Key','ZHhjZmIyMHdnazVtdWw=');
xhr.setRequestHeader('Content-Type','application/json')
}
The code is supposed to connect to the API with the Api-Key as a header then fetch Json of format
{
'status':success,
'data':'[{
"p_code":,"requester_id":,
"date":,"rq_no":,
"id":, "materials":[{
"name":,
"purpose":,
"cost":,
"quantity":,
"status":,
"rq_no":,"id":,
"total":},
...
]}
.....
]'
... The data is to be assigned to variables then appended to the main HTML table
I finally had it working perfectly:
<script type="text/javascript">
function fetchJson(){
$(document).ready(function(){
$.ajax({
url: 'http://api.lynmerc-enterprise.com/requests',
headers: {
'Api-Key':'ZHhjZmIyMHdnazVtdWw='
//'Content-Type':'application/json'
},
//async: false, //return value as variable not to make an async success callback
type: 'GET',
dataType: 'json',
success: function(data){
console.log(data);
//var data2 = JSON.parse(data.data);
var data2 = data.data;
var data2Array = [];
$.each(data2, function(idx, data2){
console.log(data2.p_code);
console.log(data2.date);
console.log(data2.rq_no);
var userfo = data2.user;
console.log(userfo.fullname);
console.log(userfo.project_site);
var material = data2.materials;
var dateRequested = data2.date;
var requestNumber = data2.rq_no;
var requester = userfo.fullname;
var projectSite = userfo.project_site;
$.each(material, function(idx, material){
console.log(material.name);
console.log(material.purpose);
console.log(material.quantity);
console.log(material.cost);
console.log(material.total);
console.log(material.status);
var materialName = material.name;
var purpose = material.purpose;
var quantity = material.quantity;
var cost = material.cost;
var total = material.total;
var requestStatus = material.status;
/*$('#dateRequested').append(dateRequested);
$('#requestNumber').append(requestNumber);
$('#requester').append(requester);
$('#projectSite').append(projectSite);
$('#materialName').append(materialName);
$('#purpose').append(purpose);
$('#quantity').append(quantity);
$('#cost').append(cost);
$('#total').append(total);
$('#requestStatus').append(requestStatus); */
var table = $("#requestsTable");
table.append("<tr><td>"+dateRequested+
"</td><td>"+requester+
"</td><td>"+projectSite+
"</td><td>"+requestNumber+
"</td><td>"+materialName+
"</td><td>"+purpose+
"</td><td>"+quantity+
"</td><td>"+cost+
"</td><td>"+total+"</td></tr>");
});
});
},
error: function(){console.log('Error Encountered')},
//beforeSend: setHeader()
});
});
/* var request;
function setHeader(request){
request.setRequestHeader('Api-Key','ZHhjZmIyMHdnazVtdWw=');
request.setRequestHeader('Content-Type','application/json')
}*/
}
</script>
When using dataType:'json' in the code, we dont parse the json again as jQuery does all that so when we try to parse again it returns an error. Then for it to be appended to html we use $(selector).append where the selector is the element id. In this case when appending to table, we append to so it will be $(#tableBodyId).append("what to append");

Only add data to ajax call if it isnt a null value

I have this div
<div class='additional_comments'>
<input type="text" id='additional_comments_box', maxlength="200"/>
</div>
Which will only sometimes appear on the page if jinja renders it with an if statement.
This is the javascript i have to send an ajax request:
$(document).ready(function() {
var button = $("#send");
$(button).click(function() {
var vals = [];
$("#answers :input").each(function(index) {
vals.push($(this).val());
});
vals = JSON.stringify(vals);
console.log(vals);
var comment = $('#additional_comments_box').val();
var url = window.location.pathname;
$.ajax({
method: "POST",
url: url,
data: {
'vals': vals,
'comment': comment,
},
dataType: 'json',
success: function (data) {
location.href = data.url;//<--Redirect on success
}
});
});
});
As you can see i get the comments div, and I want to add it to data in my ajax request, however if it doesnt exist, how do I stop it being added.
Thanks
You can use .length property to check elements exists based on it populate the object.
//Define object
var data = {};
//Populate vals
data.vals = $("#answers :input").each(function (index) {
return $(this).val();
});
//Check element exists
var cbox = $('#additional_comments_box');
if (cbox.length){
//Define comment
data.comment = cbox.val();
}
$.ajax({
data: JSON.stringify(data)
});

Affecting two text boxes with single ajax whisperer

I'm trying to fill two text boxes with a single ajax whisperer. I got the following code:
HTML:
<input type="text" name="ICZ" id="ICZ">
<input type="text" name="ODB" id="ODB">
respond.php:
<?php
require_once("../inc/dbconnect.php");
$return_arr = array();
$term=iconv('UTF-8' ,'WINDOWS-1250',$_GET["term"]);
$SQL="some sql";
$RS=sqlsrv_query($Conn,$SQL);
while($row=sqlsrv_fetch_array($RS)) {
$id_lekar=iconv('WINDOWS-1250', 'UTF-8',$row["ID_LEKAR"]);
$jmeno=iconv('WINDOWS-1250', 'UTF-8',$row["JMENO"]);
$odborn=iconv('WINDOWS-1250', 'UTF-8',$row["ODBORN"]);
$row_array['value'] = $id_lekar;
$row_array['value1'] = $odborn;
$row_array['label'] = $id_lekar." - ".$jmeno." - ".$odborn;
array_push($return_arr,$row_array);
}
sqlsrv_close($Conn);
echo json_encode($return_arr);
?>
and jQuery:
$(function() {$('#ICZ').autocomplete({
source: 'respond.php',
minLength:5
});
});
This works but only affect one input field. I would like to fill both so I extend SQL query and extend respond.php with $row_array['value1']. Then I try to redone jQuery:
$(function() {$('#ICZ').autocomplete({
minLength: 5,
source: function(request, response){
$.ajax({
url: "respond.php",
type: "GET",
dataType: "json",
data: {term: request.term},
success:function(response){
var len = response.lenght;
if (len > 0){
var icz = response[0]['value'];
var odb = response[0]['value1'];
document.getElementById('ICZ').value = icz;
document.getElementById('ODB').value = odb;
}
}
});
}
});
});
But this just doesn't do much, no errors in console, I can see the GET request going on when I fill the field with 5 and more characters, but no response. When I try access respond.php?term=XXXXX I'm getting same response in both ways.
use JSON.parse
$.ajax({
url: "respond.php",
type: "GET",
dataType: "json",
data: {term: request.term},
success:function(response){
var response=JSON.parse(response); // parse json to object
var len = response.length;
if (len > 0){
var icz = response[0].value;
var odb = response[0].value1; //access values like this
document.getElementById('ICZ').value = icz;
document.getElementById('ODB').value = odb;
}
}
});
Look if you need to parse json. Print response in console and check if you need to parse it.
Var result =JSON.parse(response);

jQuery Ajax GET request not working correctly

I'm trying to call an AJAX query and have had lots of trouble recently.
Im trying to call a api that I have custom made myself, it displays this when the url api/reverse/test - tset (is just uses a php function to reverse the text given in the slug3.
That function works fine, just wanted to give some back on what gets requested.
reverse.php - HTML File
<textarea id="input"></textarea>
<div id="output">
</div>
index.js - All of my jQuery and AJAX
$(document).ready(function(){
var $input = $('#input');
var $output = $('#output');
$input.on('keyup', function(){
var text = $input.val();
var url = 'http://coder.jekoder.com/api/?area=reverse&text='+text;
$.ajax({
type: 'GET',
url: url,
dataType: 'text',
success: function(data) { var output = data; },
error: alert('fail')
}) // End of AJAX
$output.html = output;
});
});
api.php - PHP file being called
<?php
$area = $_GET['area'];
if ($area == 'reverse') {
if (isset($_GET['text']) ) $text = $_GET['text'];
else $text = 'Hello';
echo strrev($text);
}
It's then supposed to take the output variable and display that in a div but that's not the main thing that matters.
error removed - was trying to see if it fixed it
There are several issue I found:
Jquery:
var text = $('#input').val(); // if you are getting value from any inputbox - get value using .val() function
var url = 'http://localhost/test.php?data='+text; // pass data like this ?data='+text
// AJAX START
$.ajax({
type: 'GET',
url: url,
dataType: 'text',
async: true,
success: function(data) { var output = data; alert(output)},
error: function(data) { alert('fail') }
});
In php you ca get data like this:
echo $_GET['data'];
exit;
Try this. Scope of variable output is within the success call and you are using it outside the ajax call.
$(document).ready(function()
{
var $input = $('#input');
var $output = $('#output');
$input.on('keyup', function()
{
var text = $input.val();
var url = 'http://coder.jekoder.com/api/?area=reverse&text='+text;
$.ajax({
type: 'GET',
url: url,
dataType: 'text',
success: function(data) { var output = data; $output.html = output;},
error: alert('fail')
}) // End of AJAX
});
});

Form convert to wrong json format

I have a login form and I want to send a Post which contains a json.
Here is what I've done so far.
<form id="myForm">
Login
<input id="login" type="text" name="login" value=""/>
Password
<input id="password" type="password" name="password" value=""/>
<button type="submit" >Login</button>
</form>
and my js file
$("#myForm").submit(function(event) {
var frm = $("#myForm");
var data = JSON.stringify(frm);
event.preventDefault();
$.ajax({
url: "/register/",
data: data,
type: "POST",
contentType: "application/json"
});
});
Here is jsfiddle https://jsfiddle.net/p143s6tp/
I expected json to look like this :
{
"login" : "some_value",
"password" : "some_value"
}
but I got this :
{"0":{"0":{},"1":{},"2":{}},"length":1,"context":{"location":{}},"selector":"#myForm"}
I read some topics where people use .serializeArray() , but as a result I got array of single objects
You are stringifying the form jQuery object returned by the selector $("#myForm");.
.serializeArray() would yield the output in the following format (name,value pairs),
[{"name":"login","value":"test"},{"name":"password","value":"test"}]
You can modify the output returned by .serializeArray().
var frm = $("#myForm");
var formData = frm.serializeArray();
var data = {};
$.map(formData, function (obj,i) {
data[obj['name']] = obj['value'];
});
Applying JSON.stringify() will yield:
{"login":"test","password":"test"}
Updated Fiddle
The simplest way:
JS
var login = $('#login').val();
var password = $('#password').val();
$("#myForm").submit(function(event) {
$.ajax({
url: "/register/",
data: {'login':login,'password':password},
type: "POST",
success: function(data) {
alert(data);
}
});
});
PHP
$login = $_POST['login'];
$password = $_POST['password'];
echo 'login:' . $login . ' - password: ' . $password;
$("#myForm").submit(function(event) {
var frm = $("#myForm");
var data = frm.serialize();
event.preventDefault();
$.ajax({
url: "/register/",
data: JSON.stringify(data),
type: "POST",
contentType: "application/json"
});
});
As yourself noted, you have to use .serializeArray(). It returns array of names and values which you can convert to desired format using Array's methods.
Something like this:
var data = {};
frm.serializeArray().forEach(function(el) {
data[el.name] = el.value;
});
var json = JSON.stringify(data);

Categories