getJSON fails, JSON validates - javascript

I have a getJSON call which is inexplicably failing. The idea is, you click to submit a comment, a URL gets hit which determines if the comment is OK or has naughty words in it. The response is given in JSON form.
Here's the paired down JS that generates the call. The comment and the URL are already on the page, it grabs them and hits the URL:
FORM HTML:
<fieldset id="mg_comment_fieldset" class="inlineLabels">
<div class="ctrlHolder">
<textarea id="id_comment" rows="10" cols="40" name="comment"></textarea>
</div>
<div class="form_block">
<input type="hidden" name="next" value="" />
<input id="mg_comment_url" type="hidden" name="comment_url" value="" />
<input id="mg_comment_submit" type="submit" value="Remark" />
</div>
</fieldset>
SPECIFIC JS BLOCK THAT SENDS/READS RESPONSE:
$('input#mg_comment_submit').click(function(){
var comment = $("textarea#id_comment").val();
var comment_url = $('input#mg_comment_url').val();
$.getJSON(
comment_url+"?callback=?&comment="+comment+"&next=",
function(data){
console.log(data);
alert(data);
});
});
The JSON response:
[{"errors": {"comment": ["Weve detected that your submission contains words which violate our Terms and Conditions. Please remove them and resubmit test"]}}]
It's being returned as a mimetype of application/json. It validates in JSONLint. I also tried adding a couple AJAX functions to try to catch errors, and they're both silent. I can see the request going out in Firebug, and coming back as status 200 responses, which validate in JSONLint and which I can traverse just fine in the JSON tab of the response. If I put an alert before the getJSON, it runs; it's just that nothing inside of it runs. I also find that if I change .getJSON to .get, the alerts do run, suggesting it's something with the JSON. I'm out of ideas as to what the problem could be. Using Firefox 3.0.13.

The querystring parameter "callback=?" comes into play if you are using cross-site scripting or jsonp, if you are posting the same server, you don't need to use that.
If you need or want to use that option, the server side code needs to come back with the callback function included in the json response.
Example:
$jsonData = getDataAsJson($_GET['symbol']);
echo $_GET['callback'] . '(' . $jsonData . ');';
// prints: jsonp1232617941775({"symbol" : "IBM", "price" : "91.42"});
So either make a server side change if necessary or simple remove the "callback=?" parameter from the url.
Here's more info on jsonp

Are you able to manually call your service without any errors? Have you tried using firebug and looked under XBR to see the post/response of the JSON payloads? I normally use .NET as my endpoints, and with .NET 3.5 I need to use content type "application/json; charset=utf-8".
Here is an example of a working JSON call I use in .NET with jQuery 1.3.2
$.ajax({
type: "POST",
url: "WebService1.ASMX/HelloWorld",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{}",
success: function(res) {
// Do your work here.
// Remember, the results for a ASMX Web Service are wrapped
// within the object "d" by default. e.g. {"d" : "Hello World"}
}
});

Have you tried it with $.ajax? You can then define both error and success callbacks and have better idea.

Can you try adding a global ajaxError function to log the error.
$.ajaxError( function(event, XMLHttpRequest, ajaxOptions, thrownError){
console.log( thrownError );
});

Related

Passing JS to PHP

I am trying to pass a string stored in a variable to a mysql table via php.
Currently I am using an <input> with type hidden, I assign the variable that I want as its value and post it through a form submit.
it is working but it's ugly.
I know there is $.post and $.ajax but I don't seem to figure out how to use them in the js side and php side. I have looked for them online and there are a lot of questions of this sort but none of them work for me (probably because I am missing knowledge)
How can I do it?
Here is a very basic example. We start out with a form on an HTML page. When this button is clicked, we are going to activate a javascript function.
<html>
<form>
<input type="email" id="email-field" />
<input id="submitButton" type="submit" value="Submit" />
</form>
</html>
Now, here is the javascript function being activated due to the button click. Inside, we extract any information that might have been filled out in the input field with id of "email-field", then send that off via ajax to a php file that sits on the server.
$('#submitButton').click(function() {
var email = $('#email-field').val();
$.ajax({
type: 'POST',
url: './yourphpfilename.php',
data: {
email: email
}
}).done(function(data) {
console.log(data) // Will send you the result that is echoed in the PHP file
})
})
As long as you put the correct url in your ajax request to your PHP file, you can easily receive the data being sent like so,
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$email = $_POST['email'];
echo 'I have received your request.';
}
To send the data back, I use the echo command to do so here.
Try to read some documentation on the $_POST variable in PHP. Notice how I call for ['email']. The identifier inside the brackets directly correlates to the key inside the data object in the js file. For example, say we decided to name our email key something different in the js file.
data: {
useremail: email
}
You would then just change the PHP code like so,
$email = $_POST['useremail'];
This was very confusing for me starting out, and sometimes it's hard to even pose a quality question on it if you have no idea how it works. In the future though, I would atleast try to post some code showing that you attempted the problem.
There are several things you need to do:
You have a form tag and you need to prevent it from submitting, like this:
$("#myformid").submit(function(event) {
//Do something
event.preventDefault();
});
If your form is no longer submitted, then you are on the right track.
You need to use $.ajax to send the request, like this:
$("#myformid").submit(function(event) {
//Here I assume that all variables have been properly initialized
$.ajax({
url: "yoururl",
method: "POST",
data: yourdata, //yourdata should contain the things you intend to send to the server
}).done(function(response) {
//callback
});
event.preventDefault();
});
You will need a PHP code which will properly handle the POST request you send at yoururl. This is how you can check in PHP whether the request method was POST:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
//It is a POST request
} else {
//It is not a POST request
}

Exchange data between HTML page and Java servlet without page refreshing

I would like to create a simple login form with HTML and Java (and maybe JSON). So, I have a login form with several input fields with the following id-s: txtUsername, txtPasswd, btnLogin.
After click on the button (btnLogin) I would like to send data to the servlet, and get back just a true/false value deepends on the user-passwd combination.
I can write the HTML code of this form, and the server side code, but I don't know, how can I send and recive data without page refreshing.
Here is my frontend code:
<script>
function login(){
var user=document.getElementById("txtUsername");
var passwd=document.getElementById("txtPasswd");
//???
}
</script>
Username: <input type="text" id="txtUsername"/> <br/>
Password: <input type="password" id="txtPasswd"/> <br/>
<input type="button" value="Login" id="btnLogin" onclick="login()"/>
You have to use an AJAX request. One way of doing it is to wire up and event handler on a your login button (like onclick), which calls a JS function to use an Ajax request (XmlHttpRequest), just like you have started.
You can do it in vanilla Javascript, but it is easier to use a library like jQuery. The code would look something like this (with jQuery, note the '$'):
function login() {
$.ajax({
type: 'POST',
url: url, //Url of login endpoint
data: DATA, //Now here you would want to send a payload i.e. your username and password data
dataType: 'json',
contentType: 'application/.json',
success: function(data) {
//HERE 'data' would represent your true or false that came back from the server.
//You can do stuff here with the response
},
error: function(jqXHR, textStatus, errorThrown) {
//IF ERROR then this code would be executed.
}
});
}
Hope this gives you a starting point!
You must use jquery AJAX.
Here is a link to the official documentation: http://api.jquery.com/jquery.ajax/
Hope it helps.

Symfony get PHP variable in Ajax response

Currently I've been Ajaxing a route that renders a Twig template via a Controller and injecting it into the page - all is well.
return $this->render('MyBundle:Requests:results.html.twig', array('system' => $lc_system));
However, in my JavaScript, I would like to get some extra information returned... Specifically I want a count of the results, so I can check it against a JS variable. I could put it into the twig file and then get it in JS that way, but it feels horrible.
Is there any way to get any variables sent down with the Ajax response, or a best practice way to approach this.
Use echo in your PHP function instead of return.
$.ajax({
type: "POST",
url: "somescript.php",
datatype: "html",
data: dataString,
success: function() {
doSomething(data); //Data is output
}
});
In PHP:
<?php
$output = some_function();
echo $output;
?>
It's an argument passed to your success function.
The full signature is success(data, textStatus, XMLHttpRequest), but you can use just he first argument if it's a simple string coming back. As always, see the docs for a full explanation.
If you weren't returning actual page content in your response, I'd say to return a JSON response and call it good. But since you're already using your response body for some HTML, you have to come up with another way to return the info.
One approach I've used in the past is to add a custom HTTP header and return my "meta" values that way. First, set the header in your PHP (make sure this happens before any output):
header('X-MyCustomHeader: ' . $phpVar);
Then, you can get it in your jQuery success method like this:
success: function(result, status, xhr) {
var customHeader = xhr.getResponseHeader('X-MyCustomHeader'));
}
While you can technically name your custom header anything you want, see this post for best practice/naming convention ideas:
Custom HTTP headers : naming conventions

Passing a (Sinatra) Ruby value to Javascript

So, i'm making a subscribe form.
Jquery
$("<div id='dialog' title='Subscribe!'> <form id='subscribe_form' method='POST' action='/user/subscribe'>" +
"<input type='text' name='subscribe_email' id='email' placeholder='Email Address'> <br/>" +
"<button id='submit_subscribe_form'>Submit</button></p><p id='ruby_bool'></p></form>" +
"</div>").appendTo($("#subscribe"));
When this form is submitted, it sends an ajax call to a Ruby Sinatra listener (sorry if I'm not using the right terminology, haven't really been taught Sinatra, just shown how to use it)
$('form').submit(function(){
$.ajax({
type: "POST",
url: "/user/subscribe",
data: $('form').serialize(),
success: function()
{
Ruby Code
post "/user/subscribe" do
user_Information = EmailList.new
if params[:subscribe_email] =~ /^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/
user_Information.email = params[:subscribe_email]
puts user_Information.save
#email_validation_result = "True"
else
#email_validation_result = "False"
end
puts #email_validation_result
(Yes i know i shouldn't use regex, but the engines i could find were for PHP)
I want to use the #email validation result so i can know what to put in my success: call in my ajax. Problem is, JavaScript doesn't allow Ruby Injection (according to my god knows how many hours of research) and i cant update a div on the web page that contains that variable async. I want to do this all async, so there is no refreshing of the entire page whatsoever. (If it's not possible otherwise i will concede, but i highly doubt that). I tried to put the div on another page and use the JQuery .load() function, but .erb files aren't recognizable.
Out of ideas and nearly out of sanity.
Thanks!
JavaScript:
$.post( '/user/subscribe', $('form').serialize(), function(data){
// Do whatever you want with the response from the server here
// data is a JavaScript object.
}, 'json');
Ruby/Sinatra:
require 'json' # just for a convenient way to serialize
post '/user/subscribe' do
# process the params however you want
content_type 'application/json'
{ :ok => #is_ok }.to_json
end
Without the JSON library you could end your method with just some valid JSON markup, like:
%Q[ { "ok":#{#is_ok} } ]
JavaScript/AJAX will post to the server, the matching Sinatra route will process the request, and the string result of that method (not done via puts) will be sent as the response to the method. The jQuery AJAX handler will receive it, parse it as JSON and invoke your callback function, passing the JavaScript object it created as the parameter. And then you can modify your HTML DOM as desired, client side.

ajax - getting success response values to text fields

I am trying to get the success response to send the values from ajax into their respective fields. For whatever reason I can't get that to happen. In the success section I am issuing a "alert(responseObject)" in which the results are in the attached image. So the data is coming back just as I want it, but I can't get the values to populate into the matching fields.
$(document).ready(function() {
function myrequest(e) {
var man_part_number = $('#man_part_number').val();
$.ajax({
method: "GET",
url: "includes/autofill.php",
data: {
man_part_number: man_part_number
},
success: function(responseObject) {
alert(responseObject);
//This alert response results is in attached image
$('#manufacture').val(responseObject.manufacture);
$('#model').val(responseObject.model);
$('#type').val(responseObject.type);
},
failure: function() {
alert('fail');
}
});
}
$('#fetchFields').click(function(e) {
e.preventDefault();
myrequest();
});
});
<button type="button" id="fetchFields">Fetch</button>
<input type="text" name="manufacture" id="manufacture" />
<input type="text" name="model" id="model" />
<input type="text" name="type" id="type" />
The string returned is not JSON. Look at the end of your string in the Alert box. It has "test". That means that the response is parsed as text by jQuery, since you don't specify the dataType option. If you did specify it as "JSON", it would fail because having "test" next to "{...}" is invalid JSON. I guess the point is that you need to return valid JSON, and if you are indeed expecting JSON back, set the dataType option for the $.ajax call to be "JSON". At the same time, your server should be setting the proper header in the response anyways. It's still better (sometimes) to specify the dataType option.
By default, if you don't specify the dataType option, jQuery will check the headers of the response to get the Content-Type. If it matches a valid type for "JSON", "HTML", "Text", "XML", or a few others, it will attempt to parse it by that. I'm betting your response doesn't have its headers set properly, otherwise jQuery would've attempted to convert it to JSON and failed. It's probably being returned as plain text, so jQuery sees that and parses it as text...which is why it parses fine. But the responseObject you're referencing is not an Object as you expect, because you don't follow these procedures to ensure proper parsing.

Categories

Resources