Skip to content

Instantly share code, notes, and snippets.

@renatosousafilho
Created August 3, 2012 13:08
Show Gist options
  • Save renatosousafilho/3247573 to your computer and use it in GitHub Desktop.
Save renatosousafilho/3247573 to your computer and use it in GitHub Desktop.
Aqui estão a página HTML, meu controller e meu modelo
class Contact < ActiveRecord::Base
attr_accessible :name, :phone
end
class ContactsController < ApplicationController
respond_to :html, :xml, :json, :js
def create
# contact = Contact.new
# contact.name = params[:name]
# contact.phone = params[:phone]
# contact.save
render :json => {:message=>"salvo com sucesso"}, :callback => params[:callback]
end
def show
@contact = Contact.first
render :json => {:message=>"salvo com sucesso"}, :callback => params[:callback]
end
end
[10:32:35.845] POST http://localhost:3000/contacts [HTTP/1.1 200 OK 224ms]
[10:32:35.858] ({readyState:0, setRequestHeader:(function (a, b) {if (!s) {var c = a.toLowerCase();a = m[c] = m[c] || a, l[a] = b;}return this;}), getAllResponseHeaders:(function () {return s === 2 ? n : null;}), getResponseHeader:(function (a) {var c;if (s === 2) {if (!o) {o = {};while ((c = bG.exec(n))) {o[c[1].toLowerCase()] = c[2];}}c = o[a.toLowerCase()];}return c === b ? null : c;}), overrideMimeType:(function (a) {s || (d.mimeType = a);return this;}), abort:(function (a) {a = a || "abort", p && p.abort(a), w(0, a);return this;}), done:(function () {if (c) {var a = c.length;n(arguments), j ? (l = c.length) : e && e !== !0 && (k = a, o(e[0], e[1]));}return this;}), fail:(function () {if (c) {var a = c.length;n(arguments), j ? (l = c.length) : e && e !== !0 && (k = a, o(e[0], e[1]));}return this;}), progress:(function () {if (c) {var a = c.length;n(arguments), j ? (l = c.length) : e && e !== !0 && (k = a, o(e[0], e[1]));}return this;}), state:(function () {return e;}), isResolved:(function () {return !!i;}), isRejected:(function () {return !!i;}), then:(function (a, b, c) {i.done(a).fail(b).progress(c);return this;}), always:(function () {i.done.apply(i, arguments).fail.apply(i, arguments);return this;}), pipe:(function (a, b, c) {return f.Deferred(function (d) {f.each({done: [a, "resolve"], fail: [b, "reject"], progress: [c, "notify"]}, function (a, b) {var c = b[0], e = b[1], g;f.isFunction(c) ? i[a](function () {g = c.apply(this, arguments), g && f.isFunction(g.promise) ? g.promise().then(d.resolve, d.reject, d.notify) : d[e + "With"](this === i ? d : this, [g]);}) : i[a](d[e]);});}).promise();}), promise:(function (a) {if (a == null) {a = h;} else {for (var b in h) {a[b] = h[b];}}return a;}), success:(function () {if (c) {var a = c.length;n(arguments), j ? (l = c.length) : e && e !== !0 && (k = a, o(e[0], e[1]));}return this;}), error:(function () {if (c) {var a = c.length;n(arguments), j ? (l = c.length) : e && e !== !0 && (k = a, o(e[0], e[1]));}return this;}), complete:(function () {if (c) {var a = c.length;n(arguments), j ? (l = c.length) : e && e !== !0 && (k = a, o(e[0], e[1]));}return this;}), statusCode:(function (a) {if (a) {var b;if (s < 2) {for (b in a) {j[b] = [j[b], a[b]];}} else {b = a[v.status], v.then(b, b);}}return this;}), responseText:"", status:0, statusText:"error"}) @ file:///home/renatofh/development/agenda2/index.html:29
<html>
<head>
<title>Formulario</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$(function() {
$("#meuForm").submit(function(event) {
event.preventDefault();
var $form = $(this),
name = $form.find('input[name="name"]').val(),
phone = $form.find('input[name="phone"]').val(),
url = $form.attr('action'),
params = $form.serialize();
$.post(url, params, function(data) {
console.log(data);
}, "jsonp");
});
});
</script>
</head>
<body>
<form id="meuForm" action="http://localhost:3000/contacts" method="POST">
<table>
<tbody>
<tr>
<td>Nome</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>Telefone</td>
<td><input type="text" name="phone"></td>
</tr>
</tbody>
</table>
<input type="submit">
</form>
</body>
</html>
@renatosousafilho
Copy link
Author

Ok, lukas, mas mesmo assim chequei que minha renderização está correta, se eu usar o formulário sem o script, ele me retorna o json normalmente. Redirecionando para uma outra tela, mas de qualquer forma está retornando, o problema é que eu não consigo é usar este json de retorno dentro dos callbacks do jQuery.

@lukelex
Copy link

lukelex commented Aug 3, 2012

Mas apesar do formato retornado pelo rails ser aparentemente válido você tem que validá-lo, por exemplo no jsonlint.com

O jQuery tem alguns problemas na hora de dar um parse em json inválido. Use esse snippet pra saber quando o jquery nao conseguir renderizar o json:

$.ajaxSetup({"error": function(XMLHttpRequest,textStatus, errorThrown){
alert(textStatus);
alert(errorThrown);
alert(XMLHttpRequest.responseText);
}});

@renatosousafilho
Copy link
Author

lukas, coloquei isso e método cia no no callback de error.

@lukelex
Copy link

lukelex commented Aug 4, 2012

Vou assumir que esse método esta sendo executado da forma correta.

Qual o erro que os alerts dele levantam?

@renatosousafilho
Copy link
Author

apenas error e checando o objeto XmlHttpRequest chequei que ele retorna o atributo textStauts: 'error', mas acho que descobri do que se trata; fiz uma experiência, criei uma página PHP e coloquei em um servidor apache, criei uma outra página no meu diretório pessoal não funciona, mas se eu usar a mesma página no meu servidor funciona, a referência a requisição é a mesma para ambas. Pelo visto existe alguma caracteristica inerente a usar páginas inseridas em um servidor, em arquivos 'remotos'. Acho que no meu caso é mais viável mudar de Create para New no rails e manipular o JSON através do método $.getJSON, já testei e deu certo, por que envio um callback. logo mais posto como funciona nessa outra abordagem. Não é a ideal, nem como queria, mas é a que funciona XD.

@renatosousafilho
Copy link
Author

Consegui fazer algo semehante usando PHP, como já havia dito, Funciona normalmente desde que acessado no contexto de servidor, se eu tenata acessar pelo diretório local(/var/www/.../index.html, ele imprime no arquivo o seguinte erro:
[08:41:56.306] [object XrayWrapper [object XMLDocument]] @ file:///var/www/agenda2/index.html:20
[08:41:56.304] nenhum elemento encontrado @ file:///var/www/agenda2/lerdados.php:4

@renatosousafilho
Copy link
Author

Fiz mais um teste, coloquei o arquivo index.html dentro da pasta public do projeto Rails e funcionou perfeitamente quando acessei por localhost:3000/index.html; Mas ao acessar como um arquivo local ele dá o erro pois faz a requisção via GET.

Log: localhost:3000/index.html
[09:20:12.546] POST http://localhost:3000/contacts?callback=jQuery172044519649525006233_1344255604004 [HTTP/1.1 200 OK 12ms]

[09:20:12.558]({message:"salvo com sucesso"}) @ http://localhost:3000/index.html:16

[09:20:55.207] GET http://localhost:3000/index.html [HTTP/1.1 304 Not Modified 6ms]
[09:20:59.602] POST http://localhost:3000/contacts?callback=jQuery172013948980227440033_1344255655315 [HTTP/1.1 200 OK 11ms]
[09:20:59.614]({message:"salvo com sucesso"}) @ http://localhost:3000/index.html:16

Log: arquivo local
[09:20:41.395] GET http://localhost:3000/contacts?callback=jQuery17208715607841069632_1344255634057&name=renato&phone=32326725&_=1344255641282 [HTTP/1.1 200 OK 16ms]

[09:20:41.421]({message:"salvo com sucesso"}) @ file:///home/renatofh/development/agenda/public/index.html:16

[09:21:07.961] file:///home/renatofh/development/agenda/public/index.html

[09:21:14.362] GET http://localhost:3000/contacts?callback=jQuery17206815958319450339_1344255668057&name=renato&phone=32326725&_=1344255674243 [HTTP/1.1 200 OK 15ms]
[09:21:14.391]({message:"salvo com sucesso"}) @ file:///home/renatofh/development/agenda/public/index.html:16

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment