When I try to get a External json object I receive "Uncaught SyntaxError: Unexpected token :" every time. I already tried use json and jsonp to get these values, but never works.
Here is the link: http://177.54.57.242:8080/ws_VerifSenhaPac_RetJSON?aPaciente=181927&aSenha=MVCARS1
jQuery(document).ready(function(){
//evento quando clicar no link com id="pegar-valor"
jQuery("#pegar-valor").click(function(){
//pegamos o valor do input
var usuario = jQuery("input[name=usuariologin]").val();
var senha = jQuery("input[name=usuariosenha]").val();
//mostramos o valor com alert()
//jQuery(this).attr('href', 'http://177.54.57.242:8080/ws_VerifSenhaPac_RetJSON?aPaciente=' + usuario + '&aSenha=' + senha + '');
//var url = 'http://177.54.57.242:8080/ws_VerifSenhaPac_RetJSON?aPaciente=' + usuario + '&aSenha=' + senha + '?callback=?';
var url = "http://177.54.57.242:8080/ws_VerifSenhaPac_RetJSON?aPaciente=181927&aSenha=MVCARS1&callback=?";
jQuery.getJSON( url, function ( result ) {
var objeto = JSON.parse( result );
console.log(objeto.StatusSenha);
});
jQuery.ajax({
url: 'http://177.54.57.242:8080/ws_VerifSenhaPac_RetJSON?aPaciente=181927&aSenha=MVCARS&?callback=?',
dataType: 'JSONP',
type: 'GET',
success: function (data) {
console.log('teste');
}
});
});
});
where is your JSON saved, it happened to me couple of days ago, i saved a JSON in database field, i had to save it like text, when i wanted to retrieve the value it returned with quotes "", and i was having the same error because quoted text is taken as string instead json, you have to check if the place where you are storing that json it '{JSON_CONTENT HERE}' if its stored like "'{}'", then is wrong.
It may be that your response is json and not jsonp. Try with dataType: "json"
Related
I've almost viewed similar kind of questions but my problem has not solved yet.
I've following codes.
Controller
def create
#task_list = TaskList.new(task_list_params)
if #task_list.save
respond_to do |format|
format.json { render json: #task_list}
end
else
return
end
end
Ajax Script
$(document).on('click','.add', function(){
count = 0;
user_id = $('#user_id').val();
var name = $('.new-list').val();
var current = $(this);
if(name){
$.ajax({
method: 'POST',
url: action,
dataType: 'JSON',
data: {
task_list: {
name: name,
user_id: user_id
}
}
}).success(function(response){
var data = JSON.stringify(response);
alert(data.id);
$(current).parent().parent().parent().before(
'<div class="col-md-12">'+
''+name+''+
'</div>'
);
$(current).parent().parent().parent().remove();
$('.add-list').show();
});
}else{
alert('please add title');
}
});
I just want to take id of the record just saved to the database through ajax post request. Here, in success function it just alerts undefined and I don't know what's going wrong.
This is sample response.
.success(function(response){
alert(response.id);
Remove JSON.stringify from your success function. Response is already in JSON format you can directly get the value from it.
JSON.stringfy converts javascript object into string.
Explanation
Your response is already in JSON format and you have used dataType: "JSON" in your AJAX call. Which will make it possible to transfer JSON data between server and client.
When your response is already in JSON format you can use its property without parsing it. I.e response.id
If you have not used dataType: "JSON" and you are passing json encoded response from your controller to view file you have to first decode the response to get its values.
var d = $.parseJSON(response);
alert(d.id);
My AJAX call isn't treating the data from server as JSON, even if i set the datatype in json:
function Getmateriasfromserver(callback){
var status_aux;
//Requisição HTTP, por dados provindos do url dado. Caso os dados recebidos sejam os esperados, entra no caso do SUCCESS
return $.ajax({
url: 'materiasphp/materias.php',
dateType: 'json',
success: function(data)
{
status_aux = data;
callback(status_aux);
var test = JSON.stringify(data);
console.log(data);
console.log(test[1]);
}
Console print test[1] = "["
You also have a typo in your code. dateType: should be dataType:
return $.ajax({
url: 'materiasphp/materias.php',
dataType: 'json',
...
var test = JSON.stringify(data);
Should probably be
var test = JSON.parse(data);
// or just
var test = data;
Because if you stringify it, then you are accessing letters in the string with bracket notation.
var test="cat":
console.log(test[0]);
Is c, the first letter in the string
JSON is a text based data format.
JSON.stringify(data); takes data and converts it to a JSON text, which it stores in a string.
console.log(test[1]); then reads the character at index 1 in that string and displays it.
This is normal behaviour.
If you want to deal with the data as a JavaScript data structure then don't convert it to JSON!.
Just work directly with the data structure in data.
Hello I have the following trigger:
CREATE TRIGGER `update` AFTER UPDATE ON `table 1`
FOR EACH ROW INSERT INTO table 2 (
Id,
Revision,
Purpose,
Change
)
VALUES
(
OLD.Id,
OLD.Revision,
OLD.Purpose,
#purpose_change /* user variable */
);
$$
DELIMITER ;
I am using C# WebService, Ajax, and JavaScript. Here is my C# methods for update (at the moment doesnt work)
"UPDATE table 1 SET Revision=#revision, Purpose=#purpose, #purpose_change=#change WHERE (Id =#id)";
Here starts the problem, because I dont know exactly how to send #purpose_channge.
Here is my Web Method.
[WebMethod(EnableSession = true)]
public string ActualizarAlerta(int id, string revision, string purpose, string change, int op)
{
string respuesta = "An Error Has Ocurred.";
try
{
UpdateAlert ua = new UpdateAlert(id, revision, purpose, change);
int resp = conn.UpdateAlerta(ua, op);
if (resp > 0)
respuesta = "Works!.";
}
catch (Exception ex)
{
respuesta = "An Error Has Ocurred: " + ex.Message;
}
return respuesta;
}
And here is my JavaScript with AJAX call.
$.ajax({
type: "POST",
url: urlServer + "ws_alerts.asmx/ActualizarAlerta",
data: '{' +
'"id":' + id +
',"revision":"' + rev +
'","purpose":"' + pur +
'","change":"' + change +
'","op":' + op + '}',
dataType: "json",
contentType: "application/json",
timeout: 60000,
error: function (xhr) {
bootbox.alert("Ocurrio un error al procesar la peticion.");
},
success: function (data) {
bootbox.alert(data.d);
}
});
id, rev, change, etc. Are $('#MyId').val()
I know that all the problem is in the Update query but I dont know how to do it correctly, how can I do that?
That is a mysql user variable, you must run a raw query before UpdateAlerta()
SqlCommand cmd = new SqlCommand("set #purpose_change = 'Purpose change to 1';", conn);
cmd.ExecuteNonQuery();
ps (I remember another related question here )
We have a .asmx service that returns JSON data. Can someone point me to a simple example that calls the service from a page w JavaScript ?
Tks
You can use jQuery's get function.
var dataID = $('#WhatINeedForAParameter').val();
$.get('WebApiAddress/MethodName', { id: dataID },
function(data) {
alert(data);
// Since your method returns a JSON object you can access
// the properties of that object
alert(data.id);
alert(data.name);
});
Or if you want to use the long hand jQuery ajax you can do the following:
var dataID = $("#WhatINeedForAParameter").val();
var request = $.ajax({
url: "WebApiAddress/MethodName",
type: "POST",
data: { id : dataID },
dataType: "jsonp"
});
request.done(function(msg) {
alert('You got this ' + msg);
});
request.fail(function(jqXHR, textStatus) {
alert( "Your request failed: " + textStatus );
});
I am sending a request by post using jquery ajax, but some of the words i send have + to join words like: HTA+HIPERAQUITISM+DBLR, the php recieve HTA HIPERAQUITISM DBLR changing the + by blank spaces, i post the code below. help!
function getItemInfo(itemName, itemField, itemComparative, itemTable){
var result = "";
var nombreItem = itemName;
var campoItem = itemField;
var comparativeItem = itemComparative;
var tableItem = itemTable;
$.ajax({
type: 'POST',
async: false,
url: 'modules/medicos/controller.php?fun=consul_item&nombre_item=consul_item'+
'&nombre_item='+nombreItem+
'&campo='+campoItem+
'&comparador='+comparativeItem+
'&tabla='+tableItem,
success: function(data) {
result = data.toString();
},
failure: function() {
result = "";
}
});
return result;
}//end function
This is because in a URL + means space.
You'll need to URL encode the data first before adding it to the query string.
You can use the encodeURIComponent() function to encode your value before adding it to the query string.
Once your PHP code picks it up you can then decode the value with the urldecode function
So your code should update to something like this:
url: 'modules/medicos/controller.php?fun=consul_item&nombre_item=consul_item'+
'&nombre_item='+encodeURIComponent(nombreItem)+
'&campo='+encodeURIComponent(campoItem)+
'&comparador='+encodeURIComponent(comparativeItem)+
'&tabla='+encodeURIComponent(tableItem),
Your code seems to be correct. You are passing those variables one by one (nombreItem, campoItem, comparativeItem and tableItem). So I don't really understand what you say is not working.
A suggestion to make passing data easier:
$.ajax({
type: 'POST',
async: false,
url: 'modules/medicos/controller.php',
data : ({ fun : consul_item,
nombre_item : nombreItem,
campo : campoItem,
comparador : comparativeItem,
tabla : tableItem }),
success: function(data) {
result = data;
},
failure: function() {
result = "";
}
});
If you want to pass all your info as one textual string you should do:
...
data: ({ test : consul_item + '+' + nombreItem + '+' + campoItem + '+' + comparativeItem + '+' + tableItem }),
...