ajax - getting success response values to text fields - javascript

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.

Related

ajax form submitting but calling error function

This is a simple form which takes 2 dates from and to and I am submiiting those to values to server.
<form action="#" method="get">
<label for="from">From</label>
<input type="text" id="from" name="fromDate">
<label for="to">to</label>
<input type="text" id="to" name="toDate">
<input type="button" value="Recv Amount" id="recv">
</form>
and the following is the controller code
#RequestMapping("getPayments")
#ResponseBody
public void getPayments(HttpServletRequest request,Model uiModel)
{
String toDate=request.getParameter("toDate");
String fromDate=request.getParameter("fromDate");
System.out.println(fromDate+" "+ toDate);
}
and this is js code
$('#recv').click(function(){
var fromDate=$('#from').val();
var toDate=$('#to').val();
$.ajax({
type: "GET",
url: url,
data:{"fromDate":fromDate,"toDate":toDate},
dataType:"json",
success: function( data ) {
console.log('success');
},
error:function()
{
console.log('failed');
}
});
});
when ever I hit the button I can see todate and from date in the server console (This means System.out.println(fromDate+" "+ toDate); is executed) but in the browser console failed is printed(this means console.log('failed'); is executed)
I do not have any error in browser console but the success function of ajax is never executed.
What could be the reason behind it?
jsfiddle
You are waiting for a JSON answer, but you are not returning anything. jQuery is going to give you an error. Remove 'dataType' from your ajax request or return a valid json object.
From jQuery documentation:
"json": Evaluates the response as JSON and returns a JavaScript object. The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. As of jQuery 1.9, an empty response is also rejected; the server should return a response of null or {} instead. (See json.org for more information on proper JSON formatting.)
jQuery ajax query
EDIT:
Based on the information provided issue is that data is expected the way you formed your success parameter.
Since no data is returned (void method) it won't actually do anything.
Therefore you need to use:
statusCode: { 200: function() { alert( "success" ); } }
Remove success and error as success won't work (no data being returned) and error will display (simply because no data is returned) and replace them with relevant status codes.

Passing array through ajax

I'm fairly new to the jQuery execute on the same page stuff. So far I have been passing only single values trough ajax which is working fine. Now, I need to pass an array which is created by checkboxes through ajax.
My form html, dynamically created by php:
<input type=checkbox class=box name=box[] value=".$row['DoosID']." />
My jQuery:
var BackorderDate = $("#BackorderDate").val();
var Box = $(".box").val();
if( (TerugleverDatum == "") ){
$("#backorderresult").html(" * Some Error .").fadeIn("Slow").fadeOut(3000);
} else {
$("#backorderresult").fadeOut();
$.ajax({
type :'POST',
url :'./backorder.php',
data : box : Box,
backorderdate: BackorderDate,
dataType:"json",
success: function(data){
// Do Something
}
});
}
My PHP:
$boxlist = json_encode($box);
foreach($boxlist as $boxvalue){
// Do something with every value
}
this gives me a javascript error on submit saying box is not defined.
change this:
data : box : Box, backorderdate: BackorderDate, // invalid way of sending
to this:
data : {box : Box, backorderdate: BackorderDate}, // valid way
data
Type: PlainObject or String
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs.
More Info
Why don't you try enclosing all the data values in a open and close curly braze( { and } ) .
Else it will conflict with the syntax of $.ajax method.
I think it is causing the problem.
You are sending data value in wrongly manner -
The data property should always be a JavaScript object. It's properties are serialized into a regular query string (for GET requests), or a normal post body parameter string (for POST requests). This serialized string is then sent to the server, along with the AJAX request.
On the server you can read the properties of the data object as if they were sent as simple request parameters, via either GET or POST. Just like if the properties had been fields in a form.
Try this :
$.ajax({
type :'POST',
url :'./backorder.php',
data : 'box='+Box+'&backorderdate='+BackorderDate,
dataType:"json",
success: function(data){
// Do Something
}
});
For more information see jQuery Ajax
You might want to refer to the php file like this: url :'../backorder.php' (double dots). At least, that's how I do it always.

How to pass form data to PHP via AJAX call (CodeIgniter Framework)

I have the following HTML structure:
<form method="POST">
Name : <input id="asgname" type="text"> <br>
Description : <input id="asgdescription" type="text"> <br>
Save
</form>
I want that on clicking the save button, the form values are sent to the server via AJAX call.
For that, I've attached the click event via following command
$("#asgsave").click(save_assignment);
save_assignment is also a javascript function defined as follow:
function save_assignment() {
return $.ajax({
type: "POST",
url: "<?php echo base_url();?>index.php/user/save_assignment",
data: $('form').serialize(),
success: function(response) {
alert('Form was submitted');
},
error: function(error) {
alert("Error");
}
});
}
The above is not working. So I tried the following approach as well:
function save_assignment() {
var formvalues = {
name : $('#asgname').text(),
descripion : $('#asgdescription').text(),
};
return $.ajax({
type: "POST",
url: "<?php echo base_url();?>index.php/user/save_assignment",
data: {values : formvalues},
success: function(response) {
alert('Form was submitted');
},
error: function(error) {
alert("Error");
}
});
}
But this is also not working.
Can anyone please guide me as to why are the above methods not working and what is the correct way to do so ?
EDIT-1 :
By not working, I mean: in the first case ($('form').serialize() approach) the data is not being sent to the server. I checked it via chrome and firefox debugger that there was no post data sent corresponding to the form.
And in the second case, empty values are being sent. i.e. the post data sent to server is like following:
values[name]
values[description]
i.e. the above values are empty.
EDIT-2:
By logging on firephp, I have confirmed that the save_assignment PHP script is BEING EXECUTED. Thus ajax call is working fine but it is NOT passing the data correctly.
Try to use event.preventDefault() like,
$("#asgsave").on('click',function(e){
e.preventDefault();
save_assignment();
});
or use return false after ajax call like,
function save_assignment() {
//ajax code
return false;
}
you have to use callbacks in the success function, cause ajax is asynchronously
edit
have you already tried console.log('foo'); in your function? so you are able to test if the function is called ;)
edit 2
add the following line to your ajax options
dataType: "json"
You could just serialize your form values:
http://api.jquery.com/serialize/
However, looking over your code, I'll take a stab and guess that you are not getting and sending your values properly. Using jQuery, you grab a value from input like so:
$('#idofInput').val();
http://api.jquery.com/val/
You are doing: $('#asgname').text()
Format your data properly: data : { foo : 'bar', bar : 'foo' }
One last guess, make sure your CodeIgniter config has CSRF protection disabled, otherwise you would need to pass: $this->security->get_csrf_token_name() & $this->security->get_csrf_hash();

How to get POST variables in jQuery [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
how to get GET and POST variables with JQuery?
I have the following HTML:
<form action='.' method='post'>{% csrf_token %}
<div class="parameters">
Show
<select name="earnings_filter">
<option value="all">Total earnings</option>
<option value="hd">HD earnings</option>
<option value="sd">SD earnings</option>
</select>
<input type="submit" name="submit" class="submit float-right" value="submit" id="submit_financials"/>
</div>
</form>
I need to do an ajax call with this, which I'm triggering on:
$("#submit_financials").live('click', function(){
...
});
Is there a way to get the variables that are submitted in POST, for example which option was selected (and there are about 10 other variables I need to get). Or do I need to use the jQuery selectors to get the value of each?
$("#submit_financials").live('click', function(){
$.ajax({
url: '', // script url to send
method: 'POST', // method of sending
data: $('form').has(this).serialize(), // .serialize() make query string with form inputs name and value
dataType:'json', // expected data format returned from server, you may have something else
success: function(response) {
// response contains data returned from server
}
});
});
It would be better replace live() with .on() if you're using jQuery > 1.7 and it'd be better if possible. So you can write it
$("#container").on('click', '#submit_financials', function(){
$.ajax({
url: '', // script url to send
method: 'POST', // method of sending
data: $('form').has(this).serialize(), // .serialize() make query string with form inputs name and value
dataType:'json', // expected data format returned from server, you may have something else
success: function(response) {
// response contains data returned from server
}
});
});
Here #container point to holder of #submit_financials that belong to DOM at page load.
If all the values are in input elements on the form...
$("#formId").serialize()
You could serialize the form and send to the server page
$.post("yourServerPage.php", $("form").serialize(),function(data){
//Do whatever with the result from ajax server page.
});
How about creating several input values of type hidden
<input type="hidden" id="sample_id" value="SOMETHING" />
give them ids and acces the data inside using:
$('#sample_id').val()
Unfortunately, POST variables are communicated in the request from the client to the server, but they are not automatically included in the response from the server back to the client. This is one of the things that sets them apart from GET variables.
If your data isn't excessively long, you may want to switch to the GET method instead. You can then retrieve the variables using a function like one listed in this question: How can I get query string values in JavaScript?
Alternatively, if you have access to the server-side code, you could include these variables in HTML returned; however this is another question entirely :)

getJSON fails, JSON validates

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

Categories

Resources