Unexpected token illegal on Ajax get - javascript

I am sending dynamically generated sql through ajax
And i am getting parsererror - Error:reportDataFunction was not called - ERROR123- reportDataFunction
And i am getting this error Uncaught SyntaxError: Unexpected token ILLEGAL in google chrome console.
And this with that error:
http://MYWEBSITE/webService/myService.asmx/myServiceDB?callback=reportDataFunction&userName=dskrbic&procedureName=declare+%40result+xml+SET+%40result+%3D(SELECT+unitCode+AS+unitCode+FROM+unit+WHERE+universityCode+%3D+144+FOR+XML+path%2Croot%2CELEMENTS+XSINIL)DECLARE+%40outputValue+nvarchar(MAX)+EXECUTE+convertJSONPMulti+%40result%2C+%40outputValue+output+SET+%40outputValue+%3D%27selectView+%3A%27%2B%40outputValue+SELECT+%27%7B%27%2B+%40outputValue+%2B%27%7D%27&_=1459259972547
This is my procedure i am calling :
var procedureVal = "declare #result xml SET #result =(SELECT unitCode AS unitCode FROM unit WHERE universityCode = 144 FOR XML path,root,ELEMENTS XSINIL)DECLARE #outputValue nvarchar(MAX) EXECUTE convertJSONPMulti #result, #outputValue output SET #outputValue ='selectView :'+#outputValue SELECT '{'+ #outputValue +'}'"
This is my ajax
$.ajax({
crossDomain: true,
type: "GET",
contentType: "application/json; charset=utf-8",
async: false,
url:"URL",
data: { userName: "dskrbic", procedureName: procedureVal },
dataType: "jsonp",
jsonpCallback: "reportDataFunction",
error: function (xhr, textStatus, errorThrown) {
alert(textStatus + ' - ' + errorThrown + ' - ERROR123 - ' + "reportDataFunction")
}
});
If i paste my procedureVal directly in query in sql or if i call it directly through webService if i go to link of my webService i get result back but if i call it through ajax i get error. And this is example of what i get :
({selectView :[ {\"unitCode\":\"1\"}, {\"unitCode\":\"2\"}, {\"unitCode\":\"3\"},{\"unitCode\":\"4\"}]});
Any idea where is the problem ? Thank you for your help
EDIT :
My headers of GET
And this is what my response looks like :
reportDataFunction({selectView :[ {\"unitCode\":\"1\"}, {\"unitCode\":\"2\"}, {\"unitCode\":\"3\"} .....
From first " The response is red , i supose there is error around there ?

For some reason i wasnt able to send this part of sqlQuery
SET #outputValue ='selectView :'+#outputValue SELECT '{'+ #outputValue +'}'"
So i have split it in 3 pieces , and made procedure that has that part , and i am sending generated values to that procedure , where i put them together and execute as one

Related

Bing Maps REST - Javascript

I am a beginner with JavaScript and I am facing some issues with parsing JSON and display the data I want to.
When I run the URL manualy in browser I get a correct result back.
The JavaScript code looks like this:
request = "URL"
function CallRestService(request, callback) {
$.ajax({
url: request,
dataType: "jsonp",
jsonp: "jsonp",
success: function (r) {
callback(r);
var results = data.resourceSets;
console.log(r.message);
alert(r.statusText);
},
error: function (e) {
alert("Error" + JSON.stringify(e));
console.log("Error" + e.message);
}
});
}
When I run this code I get no error in the console but I still get an alert via the error function: "status":200,"statusText":"OK"
Why do I get this?
And thats why I cannot get my data displayed, what I am doing wrong?
EDIT
so I was able to make a working code out of it, but I still get messages from SUCCESS and ERROR at the same time and I also get my data back?!
<script>
var request = "URL";
function CallRestService(request, callback) {
$.ajax({
url: request,
dataType: "jsonp",
jsonp: "jsonp",
success: function (r) {
callback(r);
console.log("working" + r.message);
alert(r.statusText);
},
error: function (e) {
alert("Error" + e.message + JSON.stringify(e));
console.log("message: " + e.message);
console.log("readyState: " + e.readyState);
console.log("responseText: "+ e.responseText);
console.log("status: " + e.status);
}
});
}
CallRestService(request, GeocodeCallback);
function GeocodeCallback(results) {
console.log(results.resourceSets[0].resources[0].travelDurationTraffic);
document.getElementById("sec").innerHTML=Math.round((parseFloat(results.resourceSets[0].resources[0].travelDurationTraffic) / 60));
}
</script>
Assuming that you put an actually URL into the request parameter this looks fine. A 200 status means it was successful and this likely called the console from your success function. I know you said you removed it to be sure, but the page could of been cached. If you take a look at the network request you will likely see that it was successful as well. Ifs possible that an error in your success function is occurring and triggering the error function. Have you tried adding break points inside of the two functions?
Here is a blog post that shows how to access the Bing Maps REST services using jQuery and other frameworks: https://blogs.bing.com/maps/2015/03/05/accessing-the-bing-maps-rest-services-from-various-javascript-frameworks/ It looks like your code is very similar.

Error appears when post value to php by using ajax

I get an error while posting datas to php file. Codes below
$.ajax({
type: "POST",
url: url,
data: "{'konuid='" + $('#step2-id').val() + "','kategoriid='" +$('#step3-id').val() +"'}",
success: function(data){
$('#form-sorular').html(data);
},
error: function(data)
{
alert(data.d);
}
});
I checked the value in php file which is coming from ajax, and values were empty.. What is wrong with this ajax.
You are passing a JSON formatted string for the data value, but I am guessing your server code is expecting values as if you posted a form. So instead of a string that looks like this:
{'konuid='step2-id-val','kategoriid='step3-id-val'}
You should pass a string that looks like this:
konuid=step2-id-val&kategoriid=step3-id-val
But rather than concatenate the string yourself, you should set the data value to an object, and then JQuery will format the string for you:
data: {
konuid: $('#step2-id').val(),
kategoriid: $('#step3-id').val()
},
Note: JQuery will properly encode the values when it builds the string.
And since your ajax call apparently returns html, I suggest you include the dataType setting:
dataType: 'html',
Also, the signature of the error callback is:
function(jqXHR, textStatus, errorThrown)
Change the error setting to:
error: function(jqXHR, textStatus, errorThrown) {
alert('Error: ' + textStatus + ', ' + errorThrown);
alert('Response: ' + jqXHR.responseText);
}

Sends AJAX, PHP query and return JSON and AJAX do not understand with "dataType: 'json'"

I'm new here and jQuery development, I have a question, Why can not I use the dataType:'json' nor $.parseJSON to handle a return of a query from PHP to AJAX (jQuery).
reader.js
$(function(){
//Modal form which encapsulates the loading of information occurs
var modal = $('.modal');
//Encapsulates the existing list or the list elements, each element has an "edit" button
var lista = $('.lista');
lista.on('click','.actionedit',function(){
var id = $(this).attr('href');
var li = lista.find('li[class*="j_'+id+'"]');
$.ajax({
url: 'php/controller.php',
data: 'acao=consulta&editid='+id,
type: 'POST',
//contentType: 'application/json; charset=utf-8;',
dataType: "json",
error: function (xhr, ajaxOptions, thrownError) {
alert('Erro: "'+ xhr.status + '"\nMensagem: " ' + thrownError +'"');
},
beforeSend: function(){
li.css("background","#0F6") },
success: function( carga ){
//alert( carga );
alert( carga.nome );
//modal.fadeIn("slow");
//modal.find('form span[class="filebar"]').text(carga.file);
//modal.find('form input[name="titulo"]').val(carga.title);
//modal.find('form textarea').append(carga.description;
},
complete: function(){ loader.fadeOut("slow"); },
});
return false;
});
});
controller.php
<?php
require_once("conexao.php");
switch($_POST['acao']){
case 'consulta':
//Validates query, that returns a json string...
$editid = $_POST['editid'];
$qr = "SELECT * FROM mod6_uploads WHERE id = '$editid'";
$ex = mysql_query($qr);
$st = mysql_fetch_array($ex);
//Return array in json format string for testing...
$u['file'] = 'File';
$u['title'] = 'File title';
$u['description'] = 'File Description';
echo json_encode($u);
break;
default:
echo 'Error querying';
}
Thus, the alert returns me the following message:
Error: "200"
Message: "SyntaxError: JSON.parse: unexpected character"
If I comment the dataType: "json", it returns me the following warning: undefined
And if I change the alert to "alert (carga.nome)" to "alert (load)", it returns me the following:
{"name": "File", "title": "File Title", "description": "File Description"}
Also, as I said earlier, if I use the $.ParseJSON or JSON.parse not have any return, or the error or the success.
Anyone out there have come across something like this?
If anyone could help me I would be very grateful!
I'd change this line:
data: 'acao=consulta&editid='+id,
By this:
data: {acao: 'consulta', editid: id},
As your id comes from an href, it would be better if it's automatically escaped.
Also, instead of this:
echo 'Error querying';
something like:
echo json_encode(array('Error querying'));
so it doesn't give JSON parse errors (return as javascript array of errors).
Also, ensure your mod6_uploads table has a nome field.
I see the rest is fine.
Cheers
PS: I suggest you to use a dev tool for debugging. One very easy is chrome's, just press F12, click the network tab and then run your ajax request.
If you use dataType:'json', success callback will only trigger if the server response is a valid JSON.
So if error callback is triggering, your response is 'populated' with extra data that makes JSON invalid.
In this case try to comment dataType:'json' and write in your success callback:
alert(carga)
or
console.log(carga)
This will output the server response and you will be able to see what's wrong with it.
Also if you deside to use JSON, try to use JSON everywhere in that file and avoid such code:
echo 'Error querying';
Otherwise you may get unexpected result

Ajax GET request, why does success function not print?

I have this function that performs a GET request for a given id:
var findById= function(id) {
console.log('findById: ' + id);
$.ajax({
type: 'GET',
url: rootURL + '/' + id,
dataType: "json",
success: function(data){
console.log('findById success: ' + data.name);
currentRaceEntry = data;
renderList(currentRaceEntry);
}
});
};
When I enter sitename/rest/entries/8 it returns a page with the xml for the object requested(as expected). (I can show this code but I dont think the problem is there). When I preform this request the console shows:
findById 8
My question is why doesn't it show console.log('findById success: ' + data.name);? The xml displays in the browser which looks to me like it was successful. So why doesn't the success function appear to be called? Thanks!
EDIT
this is what it looks like:
The console in the browser is blank
If you ajax request returns XML data, you need to set dataType as "xml".
At that point, the data object in the success function is an XML fragment, not a javascript objet, and you need to process it as such. The data.name property doesn't exist.

JSON Processing - Sending JSON text string to JSP, how to process in JSP

sendng json data to another jsp page - for testing really.
You enter a JSON formatted string in a text field on my jsp. I submit this through a form request, handled by jquery processing. It is sent to a receiver JSP. I am using the following code to do this.
$.ajax({
type: "POST",
url: "receiver.jsp",
data: term, // This is a formatted JSON string
success: function(data, textStatus, jqXHR) {
alert('Success : ' + data);
alert('textStatus : ' + textStatus);
alert('jqXHR : ' + jqXHR);
var jsonJqXHR = JSON.stringify(jqXHR);
alert('jsonJqXHR : ' + jsonJqXHR);
},
error:function (xhr, ajaxOptions, thrownError){
alert('Error xhr : ' + xhr.status);
alert('Error thrown error: ' + thrownError);
},
//complete: alert('complete'),
dataType: "text" // xml, json, script, text, html
});
My question is, how do I pick this POST up in the receiver JSP and do something with it? I have seen somethings with getParameter etc but I am not sure.
I think it will be easy to send it as parameter:
data: "jsonData=" + term,
Also you can put it in form input with name="jsonData" and serialize your form:
data: jQuery("form").serialize(),
Then you can read it in receiver.jsp:
<%
String jsonData = request.getParameter("jsonData");
%>

Categories

Resources