So I'm learning Ajax and I followed this tutorial: https://phpacademy.org/course/submitting-a-form-with-ajax to create a function that works for any form. This is the complete function:
$('form.ajax').on('submit', function() {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response) {
alert(url + ' ' + response);
}
})
return false;
});
As you see all I'm doing is alerting the response, which in this case is php echo. That's where my problem starts, I need a flexible and secure way to handle the javascript/php communication. Preferrably one function for all forms, maybe with if () statements instead of alert(url + ' ' + response); depending on the form url.
The function I need is not very complicated, based on the response I get I will just update the current form with errors.
Aslong as I know what to use in the communication I'm fine from there, echo '1'; as I have now doesn't feel like the ideal solution but it's all I could handle.
So, what type of response should I send from the php page, and where (in the javascript) and how is the best way to handle it? I've heard of json but having a hard time wrapping my head around it. Could someone show a json response sending a basic integer thats easy for my response to pick up as an int?
{ response : 1 }- Accessed asresponse.response(I typically usedataas my param name in the success callback, but that's all preference)if () { response : 1}tried with semi-colon and everything I could think of, and in the js I dosuccess: function(response) { alert(url + ' ' + response.response); }json_encodeyour data on the PHP side. (Assuming your type isjson.