I have a form and I want to add AJAX functionality to this form.
Architecture: MVC
I have a basic form like this:
<form id="customForm" method="post">
<input type="text" id="name" name="zone_name" value="" class="input-block-level" />
<button type="submit" id="save" >Save</button>
</form>
I have this JS on my MVC-View:
$('#save').click(function()
{
var name = $('#name').val();
$.ajax
({
type: 'POST',
url: 'http://localhost/myApp/process',
data: "{name:"+name+"}",
success: function (result) {
alert(result);
},
error: function () {
alert('fail');
}
});
});
I have a process class which is there in controller and have this code within
class process {
function __construct() {
echo 'Constructor';
}
}
But Doing all this gives me Error message through AJAX. Why is this happening? Is there any other way of doing this. Here under is snapshot:
enter image description here
Here under is my .HTACCESS rule
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^(.+)$ index.php?url=1ドル [QSA,L]
So when I am directly navigation to my process class its working. But not with AJAX. What would be the possible reason for this?? Here under is the screenshot:
enter image description here
2 Answers 2
your button must not submit the form, make its type button:
<button type="button" id="save" >Save</button>
Comments
What is the ajax status code? Is it generating any error message? You can get the status code as:
$('#save').click(function(e)
{
e.preventDefault(); //prevent default button action
var name = $('#name').val();
$.ajax
({
type: 'POST',
url: 'http://localhost/myApp/process',
data: "{name:"+name+"}",
success: function (result) {
alert(result);
},
error: function (xhr, status, errorMessage) {
alert(xhr.status);
}
});
});
If the status code is zero the network access my be forbidden. I see localhost in your ajax url and 192.168.1.6 in your alert box.
4 Comments
XSS is happening and page does not exist as I am able to access the page through http://localhost/myApp/process
GET, then when you use Ajax you are usingPOST, is your controller RESTful? Do you define your routes somewhere and have to make them respond to more than one HTTP Verb?localhost/myApp/myPageAnd on there the Ajax is calling thisprocessclass..."here:"{name:"+name+"}", you need an object, not a string:data: {name: name},name, and just didn't include other fields in his example to make it shorter?