I have an HTML form that posts values to a web service that sends back a JSON status or error message. This form is embedded in Wordpress. How might I access the returned value and display an error message?
Asked
Active
Viewed 516 times
0
-
look into jQuery's .ajax http://api.jquery.com/jQuery.get/ – Kelly Cook Sep 07 '11 at 22:56
-
Could you please post some of the code you have already? @Kelly better yet is : [http://api.jquery.com/jQuery.ajax/](http://api.jquery.com/jQuery.ajax/) which provides more control over returned data. – Bassem Sep 07 '11 at 22:57
-
.get is a shorthand form of .ajax. They are equivalent. – Kelly Cook Sep 07 '11 at 23:01
-
@Kelly Agreed - however some of the configuration is hidden from the developer -- [http://stackoverflow.com/questions/3870086/difference-between-ajax-and-get-and-load](http://stackoverflow.com/questions/3870086/difference-between-ajax-and-get-and-load) – Bassem Sep 07 '11 at 23:04
1 Answers
2
It would involve some Javascript, I'd highly recommend using jQuery with it's ajax function:
;(function($) {
$(document).ready(function() {
$('#form-id').bind('submit', function(e) {
e.preventDefault();
$.ajax({
type: 'post',
url: $('#form-id').attr('action'),
dataType: 'json',
success: function(jsonObject) {
if (jsonObject.error != undefined) {
alert(jsonObject.error.message);
}
else {
alert('The submission was successful');
}
},
error: function() {
alert('A connection error occurred. Please try again');
}
});
});
});
})(jQuery);
That will make an HTTP post to the URL contained in the form's action attribute, and load the returned JSON string into a javascript object.

Clive
- 36,918
- 8
- 87
- 113
-
For debugging purposes @econner can use `console.log(jsonObject);` to display the formatted json object. – Bassem Sep 07 '11 at 23:07
-
The web service returns a the success status or error message in JSON format such as the following: – econner Sep 07 '11 at 23:10
-
{"CreateResellerResult":{"AvailableCredits":0,"DataKey":"","Id":"59fe4d79-7b1f-4560-beb4-7b2f08818da4","MayCreateRecord":false,"Name":"test1000","Products":[{"Id":"81fa46ef-57d7-4658-8eb3-92a18c7486cf","ProductCount":100,"ProductName":"product1"},{"Id":"0730e907-aba5-4095-8650-35bf4794ffc7","ProductCount":50,"ProductName":"product2"}]}} – econner Sep 07 '11 at 23:12
-
I've updated the code above to provide an example, I've also changed it to attach the functionality to the form's submit handler. – Clive Sep 07 '11 at 23:19
-
Well it's very straight forward, try jsonObject.error.message as shown in the edit of @Clive – Bassem Sep 07 '11 at 23:21