I have a question about how to use both GET and POST at the same time. What I'm trying to do is that before saving the form, I want to verify that the new user name does not already exist.
{ “status”: “success”, “results” : [ { “id” : 1, “name” : “John Smith”, “password”: “123456” }, { “id”: 2, “name” : “Jane Doe”, “password”: “654321” } ] }
I want to write code to validate that user name doesn't already exist before saving the form. If the user name exists, I want to show an alert to the browser. If there are no errors, I want to submit the form.
Here's what I got so far! Any help would be greatly appreciated!
$('form').submit(function(event) {
var username = $('#user_name').val();
$.getJSON('user.json', function(data) {
var results = data.results;
var match = false;
$.each(results, function(i, result) {
if(result.name === username) {
match = true;
}
});
if(!match) {
console.log("POST");
// Submit the form!
} else {
alert("Username already exists!");
}
});
});
Is there better way to do this? even without using jQuery? what would be good reasons to use jQuery?
check the below code to send some data in json format.
if(!match) {
console.log("POST");
$.ajax({
cache: false,
url : ?,
type: "POST",
dataType : "json",
data : JSON.stringify(data),
context : Form,
success : function(callback){
//Where $(this) => context == FORM
console.log(JSON.parse(callback));
$(this).html("Success!");
},
error : function(){
$(this).html("Error!");
}
});
}
remove data : JSON.stringify(data), incase you dont need.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.