Error appears when post value to php by using ajax - javascript

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);
}

Related

JS: Ajax issue with json?

I have an API that returns the following JSON content.
{"server_online":"0"}
I'm trying to update a div's content to say "Online" or "Offline" depending on the 0 or 1 value.
$.ajax({
url: "http://api.dev.net/get/server/status",
success: function(result) {
$('#server-status').html(result);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
My issue is, the content of the div updates to an empty string?
You need to access the property of the object:
$('#server-status').html(result.server_online ? "Online" : "Offline");
You should also use dataType: "json" in the $.ajax options to ensure that it gets parsed as JSON.
In the ajax success you need to use result object and then add if statement. In the if statement you need to use jquery append() function which will add offline or onilne text to div#server-status
success: function(result) {
if(result.server_online == 0){
$('#server-status').append("<span>Offline</span>");
}
if(result.server_online == 1){
$('#server-status').append("<span>online</span>");
}
},
That's because you're not accessing the object property server_online.
Simply do the following:
$('#server-status').html(result.server_online ? "Online" : "Offline");

Unexpected token illegal on Ajax get

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

How to get Youtube video title with v3 URL API in javascript w Ajax & JSON

I am only trying to fetch Youtube video's title. Can't seem to figure it. So far I have this:
q = 'https://www.googleapis.com/youtube/v3/videos?id='+ itemId +'&key='+ ytApiKey +'&fields=items(snippet(channelId,title,categoryId))&part=snippet' ;
$.ajax({
url: q,
dataType: "jsonp",
success: function(data){
alert(data.items[0].title);
console.log(data.snippet.title);
},
error: function(jqXHR, textStatus, errorThrown) {
alert (textStatus, + ' | ' + errorThrown);
}
});
Thanks,
I got it working using
https://www.googleapis.com/youtube/v3/videos?id=itemId&key=apiKey&fields=items(snippet(title))&part=snippet
and
alert(data.items[0].snippet.title);
So, not much wrong with the syntax! But I found that the problem was really in the backend when setting up the Google API's 'allowed referers'. With V3 API, you can select which referers the API should belong to, so others cannot simply steal your API and use it. So the API will work if the request is originated from the domain name/IP you specify.
When I don't give it restrictions, the code works, but when I do enter my domain it fails! I entered .mydomainname.com/ , the same format as it was suggested, but it errors out somehow.. Now I've got figure out why.
The following jquery code will fetch the title of the video.
$.ajax({
url: "https://www.googleapis.com/youtube/v3/videos?id=" + videoId + "&key="+ apiKey + "&fields=items(snippet(title))&part=snippet",
dataType: "jsonp",
success: function(data){
console.log(data.items[0].snippet.title);
},
error: function(jqXHR, textStatus, errorThrown) {
alert (textStatus, + ' | ' + errorThrown);
}
});

How to retrieve JSON array of item sent from servlet in jQuery

I'm trying to retrieve all images in database and display in webpage. The servlet sends an array of items. When I run my servlet program it displays
{"success":true,"imageInfo":[]}
But in web page the jQuery returns undefined.
I'm newbie in jQuery - please anyone help me solve this.
Javascript :
$(window).load(function()
{
$.ajax({
type: "GET",
url: "RetriveIm",
dataType: "json",
success: function( data, textStatus, jqXHR)
{
if(data.success)
{
alert(console.log(data.imageInfo.name));
var items = [];
$.each(data, function(i, item)
{
items.push('<li><img src=data:image/png;base64,'+ item.thumbarray +' data-large=data:image/png;base64,' + item.imageInfo.fullarray + ' data-description=' + item.imageInfo.disc + ' alt=' + item.imageInfo.name + ' data-id='+ item.imageInfo.imageid +'/></li>'); // close each()
$('ul.es-carousel').append( items.join('') );
});
};
},
error: function(jqXHR, textStatus, errorThrown)
{
alert("error");
console.log("Something really bad happened " + textStatus);
},
});
});
My server side program is in this question.
I don't what error in data please help me.....Thanks...
$.getJSON("url",function(json){
console.log(json)
//your set of images check object structure
$.each(json.imageInfo, function(i, item) {//... if i understood well the json you are sending
});
shall be enough for your needs.
& make sure you are sending an header('Content-Type: application/json'); before echoing your response.
you also need to move $('ul.es-carousel').append( items.join('') ); out of the $.each

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