AJAX request error despite data is being updated successfully. "Unexpected Token <" - javascript

The question is very specific to my code written, and not able to find any solution.
I have an AJAX request that is sending some data to the server and updating the contents on the database. On firing the AJAX, the data is being updated in the database correctly, but AJAX displays error on the screen.
This is my AJAX request:
$.ajax({
type: "POST",
dataType: "json",
url: "update.php",
data: {'postData':JSON.stringify(postData)},
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
success: function(data) {
successmessage = 'Data was succesfully updated';
$("#contentID").html(successmessage);
},
error: function(data) {
successmessage = 'Error';
$("#contentID").html(successmessage);
},
});
My PHP request is this:
if(isset($_POST['postData'])){
$jsonData = json_decode($_POST['postData'],true);
$length = count($jsonData['ID']);
$ID = $jsonData['ID'];
$fieldText = $jsonData['fieldText'];
for($j=0;$j<$length;$j++) {
$langText = $fieldText[$j];
$id = (int) $ID[$j];
$update = "UPDATE mytable SET myText = '$langText'
WHERE ID = $id";
$mysqli->query($update) or die(mysql_error());
}}
On debugging, I found the error message "Unexpected Token <".
The json that is being sent to "update.php" is valid json as I have tested this before. I'm posting the code that is capturing the values and creating a json before stringify it.
var node_list = document.getElementsByTagName('input');
var c = 0;
var fieldName = [];
var fieldText = []
var ID = [];
for (var i = 0; i < node_list.length; i++) {
var node = node_list[i];
if (node.getAttribute('type') == 'text') {
fieldName[c] = node.name;
fieldText[c] = node.value;
ID[c] = node.id;
c++;
}
}
var postData = {
fieldName: fieldName,
fieldText: fieldText,
ID: ID
};
var dataString = JSON.stringify(postData);
console.log(JSON.stringify(postData));
Can someone please help.

Fixed it by changing the
dataType:"json"
to
dataType: "html"
thanks

Related

DataSet Value in Jquery C#

I have one page in which, URL contains Querystring Value.
QSecID=164&QTempId=55&QSecName=New%20Temp%20Bt
When the page loads them and tries to get the value it works fine.
$(document).ready(function() {
function getUrlParameter(name) {
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
var results = regex.exec(location.search);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};
var urlName = getUrlParameter('QSecName');
alert(urlName);
getImageData(urlName); //Pass Query String Value to Function
});
Now I am passing this value to C#, ASPX.CS page and try to fetch the data based on QSecName.
But i got error. Here is my Jquery function.
function getImageData(name) {
// alert(nextDay);
$.ajax({
type: "POST",
url: "Section.aspx/GetImageData",
//data: '',
data: JSON.stringify({
"dataSecName": name
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
alert("Success");
alert(JSON.parse(data.d));
}
});
}
My C# Page returns the DataSet in Jquery.
[WebMethod()]
public static string GetImageData(string dataSecName)
//public static string GetRole()
{
clsSection objSectNew = new clsSection();
DataSet DS = new DataSet();
DS = objSectNew.GetImageDataByJQ(dataSecName);
return JsonConvert.SerializeObject(DS);
}
Edit Code 1
Here is my SQL Statement Which is get executed when i run the page and
DS = objSectNew.GetImageDataByJQ(dataSecName);
this method pass the query string value in to execute the Stored Procedure.
select mhp.ImageName,mhp.HotSpotID,imgdetail.XCordinate,imgdetail.YCordinate
from tbl_SOAPDetailsInfo e inner join M_ImageHotSpot mhp on e.ImgHotSpotName=mhp.ImgHotSpotNameByUser
inner join M_ImageHotSpotDetail imgdetail on mhp.HotSpotID=imgdetail.HotspotIDFK where e.SOAP_D_Name='New Temp Bt'
I want to use my XCordinate, YCordinate and ImageName to display image using jquery. but Inside the alert BOX
**[object] [object]**
error display. How can i get and assign this value X AND Y value and display in DIV.
Edit Code 2
ImageName XCordinate YCordinate
$parent in angularjs.png 1146 590
$parent in angularjs.png 1216 588
$parent in angularjs.png 1188 626
$parent in angularjs.png 1162 582
$parent in angularjs.png 1193 586
The Database Value. JSON FORMAT DATA
{"d":"{\"Table\":[{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1146\",\"YCordinate\":\"590\"},{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1216\",\"YCordinate\":\"588\"},{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1188\",\"YCordinate\":\"626\"},{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1162\",\"YCordinate\":\"582\"},{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1193\",\"YCordinate\":\"586\"}]}"}
So as per your question [object] [object] is not an error. It means you cannot fetch it in a correct manner.
Though I am not sure what kind of data you are sending from your back-end code in data But you could try following way,
var data = "{\"Table\":[{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1146\",\"YCordinate\":\"590\"},{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1216\",\"YCordinate\":\"588\"},{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1188\",\"YCordinate\":\"626\"},{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1162\",\"YCordinate\":\"582\"},{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1193\",\"YCordinate\":\"586\"}]}"
var obj = JSON.parse(data);
console.log(obj.Table);
var tableObj = obj.Table
console.log(obj.Table);
var arrayLength = tableObj.length;
for (var i = 0; i < arrayLength; i++) {
console.log(tableObj[i].ImageName);
console.log(tableObj[i].XCordinate);
console.log(tableObj[i].YCordinate);
alert(tableObj[i].YCordinate);
}
So now if you replace your code with above sample your code should look like below:
function getImageData(name) {
// alert(nextDay);
$.ajax({
type: "POST",
url: "Section.aspx/GetImageData",
data: JSON.stringify({
"dataSecName": name
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var obj = JSON.parse(data);
console.log(obj.Table);
var tableObj = obj.Table
console.log(obj.Table);
var arrayLength = tableObj.length;
for (var i = 0; i < arrayLength; i++) {
console.log(tableObj[i].ImageName);
console.log(tableObj[i].XCordinate);
console.log(tableObj[i].YCordinate);
alert(tableObj[i].YCordinate);
}
});
}
Note : Try to debug in browser console you would understand object notation more details.
See the screen shot how would you do that
Hope this would help

How do I override JSON errors and prevent a blank page from loading?

How do I prevent my JSON feed from crashing and ignore errors from a database if they occur while running, also how do I change the undefined errors into a string to return as a fall back like "pending" or "not available."
I tried inputting the Try, catch, finally method. Also, the If statements conditional equal and null ones I found to change undefined into a "string"
var flight = document.getElementById("flight");
var time = document.getElementById("time");
var airline = document.getElementById("airline");
var stat = document.getElementById("status");
var cities = document.getElementById("cities");
//Loading the document
//this is for updating the url
var url = './airport-test.json';
//var url = './proxy.php';
$(document).ready(function () {
$.ajax({
type: "GET",
dataType: "json",
url: url,
async: true,
contentType: "application/json; charset=utf-8",
cache: false,
success: function (data) {
var flightString = "";
var timeString = "";
var airlineString = "";
var statString = "";
var citiesString = "";
if(data) {
try {
var a = JSON.parse(data);
console.log(a);
} catch(e) {
var errorMessage = e.name + '' + e.message;
console.log(errorMessage);
}
}
for (i= 0,l = data.length = 16; i < l; i++ ) {
code here I erased to fit this question better...
}
flight.insertAdjacentHTML('beforeend', flightString);
time.insertAdjacentHTML('beforeend', timeString);
airline.insertAdjacentHTML('beforeend', airlineString);
stat.insertAdjacentHTML('beforeend', statString);
cities.insertAdjacentHTML('beforeend', citiesString);
}});
});
I am using a raspberry pi with chromium I just want the JSON feed to still show up even when there is an error instead of a blank page. It works most of the time. Also, want to change undefined from errors into a fallback string.
Not totally sure what exactly is the problem, taking a wild guess the server is not responding properly.
Define error handler,
$.ajax({
type: "GET",
dataType: "json",
url: url,
async: true,
contentType: "application/json; charset=utf-8",
cache: false,
success: function (data) {
....
}
error: function (error) {
// handle your error here.
....
}

Adding rows to the Google Data Visualization Table

I'm trying to add different set of lat,long in the google visualization table by iterating over the Ajax get response, it looks like only the last value in the response json is added to the row,
Javascript:
$.ajax({
type: 'GET',
url: '/api/v1.0/tasks/'+document.getElementById("autocomplete").value,
dataType: 'json',
data: { 'value' : $(this).val() },
success : function(data){
for(var i=0; i<data.task.length; i++) {
var lat,long,name;
var lat = data.task[i].lat
var longi = data.task[i].longi
var name = data.task[i].markerText
alert(lat,longi,name)
var datag = new google.visualization.DataTable();
datag.addColumn('number', 'lat');
datag.addColumn('number', 'longi');
datag.addColumn('string', 'markerstr');
datag.addRows([[lat,longi,name],]);
}
})
Expected Output:
data = [[37.6153, -122.3900, 'Airport'],
[37.4422, -122.1731, 'Shopping'],]
It looks like you are rebuilding the data structure each time you iterate. It happens that your headers are the same. But in this case the whole data gets re-written on each iteration. Perhaps try something like this.
$.ajax({
type: 'GET',
url: '/api/v1.0/tasks/'+document.getElementById("autocomplete").value,
dataType: 'json',
data: { 'value' : $(this).val() },
success : function(data){
var datag = new google.visualization.DataTable();
datag.addColumn('number', 'lat');
datag.addColumn('number', 'longi');
datag.addColumn('string', 'markerstr');
var rows = []
for(var i=0; i<data.task.length; i++) {
var lat,long,name;
var lat = data.task[i].lat
var longi = data.task[i].longi
var name = data.task[i].markerText
rows.push([lat,longi,name]);
}
datag.addRows(rows);
})

Cant get ajax response to place nice with python code

Question: For some reason I can't seem to figure out why my ajax call will not return a value for success if my wo_data query comes up empty. What I want to happen is if I put a value into id_work_order and its not found in my db pop up an alert saying workorder was not found- otherwise if it is found return success which works. Any help would be greatly appreciated!
What happens is I get this if a workorder is not found in my browser console
typeerror: data[0] is undefined
if it is found I get this
success
Here is what my data looks like if the workorder is found in my response
0: object
purch_order: "1"
success: "success"
part_rev: "A"
part_number: "12345"
work_o: "W0000001"
customer_name: "TEST"
if it isn't found I get nothing back in my response
here is my views.py
def get_work(request):
if request.is_ajax():
q = request.GET.get('workorder_id', '')
wo_data = Dim_work_order.objects.filter(base_id__icontains = q )[:1]
results = []
for x in wo_data:
x_json = {}
if wo_data.exists():
x_json['success'] = 'success'
x_json['work_o'] = x.base_id
x_json['customer_name'] = x.name
x_json['part_number'] = x.part_id
x_json['part_rev'] = x.part_rev
x_json['purch_order'] = x.customer_po_ref
results.append(x_json)
else:
x_json['success'] = 'workorder_not_found'
results.append(x_json)
data = json.dumps(results)
mimetype = 'application/json'
return HttpResponse(data, mimetype)
else:
data = 'fail'
return render(request, 'app/sheet_form_create')
here is my workorder_ajax.js
$(document).ready(function () {
//$('#id_work_order').click(function () {
// getwork();
//});
$('#work_search').click(function () {
pop_other_fields();
});
//function getwork(){
// $('#id_work_order').autocomplete({
// source: "/sheet/sheet_form_create.html/get_work",
// minLenght: 2,
// });
//}
function pop_other_fields() {
var url = "/sheet/sheet_form_create.html/get_work?workorder_id=" + $('#id_work_order').val();
var work_order = document.getElementById('id_work_order').value;
$.ajax({
type: 'GET',
url: url,
dataType: 'json',
data: '',
success: function (data) {
if (data[0].success = "success") {
console.log(data[0].success);
$('#id_customer_name').val(data[0].customer_name);
$('#id_part_number').val(data[0].part_number);
$('#id_part_revision').val(data[0].part_rev);
$('#id_purchase_order').val(data[0].purch_order);
}
if (data.success = "workorder_not_found") {
alert("workorder not found :(")
}
}
});
}
});
the code here is never reached:
else:
x_json['success'] = 'workorder_not_found'
results.append(x_json)
because if if wo_data.exists(): is not true, then for x in wo_data: would never have any iterations in the first place.
Try:
def get_work(request):
if request.is_ajax():
q = request.GET.get('workorder_id', '')
wo_data = Dim_work_order.objects.filter(base_id__icontains = q )[:1]
results = []
if wo_data.exists():
for x in wo_data:
x_json = {}
x_json['success'] = 'success'
x_json['work_o'] = x.base_id
x_json['customer_name'] = x.name
x_json['part_number'] = x.part_id
x_json['part_rev'] = x.part_rev
x_json['purch_order'] = x.customer_po_ref
results.append(x_json)
else:
results.append({'success': 'workorder_not_found'})
data = json.dumps(results)
mimetype = 'application/json'
return HttpResponse(data, mimetype)

Using Javascript with php

I know this question has already been asked a few times, but I'm trying to use javascript with php. I have a file called parsing.php that parses through a xml feed and converts the metadata into JSON Object called "data". The parsing is done using ajax calls with JavaScript and JQuery.
<script src="json2.js" type="text/javascript" language="javascript"></script>
<script type="text/javascript">
$.ajax({
type: 'GET',
url: 'fakeFeed.xml',
dataType: 'xml',
async: false,
success: function(data, textStatus, jqXHR) {
function getRandom(max) {
return Math.floor(Math.random() * max);
}
function getThumbId(small) {
var num = getRandom(15);
if (num == 0) {
num = 1;
}
if (num < 10) {
num = '0' + num;
}
return num.toString();
}
var categories = new Array(); // Array for the categories
var category = {
name : '',
videos: []
};
var data1 = data;
var data = {
categories: []
};
$(data1).find('item').each(function () {
var el = $(this);
var categoryName = el.find('category').text();
var p = categories.indexOf(categoryName);
if( p == -1) {
categories.push(categoryName);
var category = {
name: categoryName,
videos: []
};
for (var j = 0; j<5; j++) {
var video = {
sources: [el.find('media\\:content, content').attr('url')],
thumb : 'images\/thumbs\/thumb' + getThumbId() + '.jpg',
title : el.find("title").text(),
subtitle : el.find("description").text(),
description: ""
}
category.videos.push(video);
}
data.categories.push(category);
}
});
window.data = JSON.stringify(data);
<script>
"<?php
$dataVar = ?> <script type=text/javascript>window.data</script><?php;?>"
"<?php
print_r($dataVar,true);
?>"
The only reason why I need to use javascript and php is because I want to use the "print_r()" function from php which allows me to return the information rather than just printing it to the screen, but unfortunately I can't get it to work. If anybody knows of other alternative or could give some advice that would be greatly appreciated.
Here is what I believe you are trying to achieve, written in PHP:
$dom = new DOMDocument();
$dom->load("fakeFeed.xml");
$data = ["categories"=>[]]; // may need to use array() instead of [] depending on PHP version
foreach($dom->getElementsByTagName('item') as $item) {
$name = trim($item->getElementsByTagName('category')->item(0)->textContent);
if( !isset($data['categories'][$name])) {
$cat = ["name"=>$name,"videos"=>[]]; // again, adjust if you're on an older version
// I'm not entirely sure what you're trying to achieve on this part.
// you seem to be getting the same video five times...
// revise your approach, comment if needed, and I can try to help
// for now, "insert code here"
$data['categories'][$name] = $cat;
}
}
// we were using the name as a key for simplicity, now just take the values
$data['categories'] = array_values($data['categories']);
// done! $data now has your data.
var_dump($data);
If you really want to use this instead of using document.log for JS:
$.ajax({
type: "POST",
url: "some_php.php",
data: JSON.stringify(data);
})
.done(function( msg ) {
document.write(msg);
});
and the some_php.php
$data = json_decode(file_get_contents('php://input'), true);
print_r($data);

Categories

Resources