I just started learning AngularJS and will be using PHP for the backend.
I got the basics of Angular working, but now I'm at the point of form submission. Now I'm thinking that I could just do an $.ajax({...}); call to a PHP file and include that function at the bottom of my view.
However, I see there are other ways using controllers, which I'm researching; I just want to know if that would be considered bad practice or if there is a simple way to transition from one method to the other.
Thanks.
EDIT:
Here's what I did now and it's working great in my opinion. Doesn't hurt the integrity of Angular, the form submits, and all is good. Is there a downside to this:
function submitNewPatient(){
$.ajax({
url: 'ajax/patients/new_patient.php',
type: 'post',
data: $("#new_patient_form").serialize(),
success: function()
{
$("#new_patient_form")[0].reset();
}, error: function()
{
alert('something went wrong');
}
});
}
You'll want to look into the $http method.
Here's an example:
$http.post('api/user', {params: {id: '5'}
}).success(function(data, status, headers, config) {
// Do something successful.
}).error(function(data, status, headers, config) {
// Handle the error
});
Along with .get the $http service has .head, .post, .delete, .put, .jsonp. In your case $http.post, the params and URL in the example above evaluate to api/user?id=5
Also, forms in Angular come with an ng-submit directive which is very useful for calling a function on submission. The ng-submit prevents the browser from its default POST action. This way you can use it to call a function on the controller attached to the view.
<form ng-submit="sendForm()" ng-controller="FormSubmission">
<button>send form!</button>
</form>
Related
I am trying to delete a post when clicking the (x) icon using Ajax request
here is my html code relating to this part :
I copied the JS and php parts from google , I've never written an Ajax request before
so I cannot figure out where I did wrong, please help
It seems that you have a problem with the right location of the php file.
It seems to be located on /static/delete.php, but you are calling /post/delete.php.
Other than that, you are not (at the moment) using DELETE, but POST.
Some frameworks use the POST as the method, but require some extra field (like _method on Laravel) to be present on the form, as some (if not all) HTTP servers do not accept methods other than GET or POST
$('#btnDeleteEmployees').click(function () {
$.ajax({
url: '/api/employees' + empID,
method: 'DELETE',
headers: {
"Content-Type": "application/json"
},
success: function (res) {
},
error: function (res) {
}
});
});
This is what am trying to achieve, I have a function in controller that generates a random password and returns the same, on button click I want to capture the generated password and display it in the view (password field). Here is the jquery/ajax call:
$(document).ready(function(){
$("#generate_password").click(function(){
$.ajax({
type: "GET",
dataType: 'text',
url: "http://127.0.0.1/public/admin/content/manufacturers/generate_password",
async:false,
success: function(resp){
alert(resp); //this alerts BLANK
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
});
});
Controller function:
public function generate_password($length = 9)
{
return $password_str;
}
Is this the correct way to call controller method?
Why am I getting blank value on alert, even though when printed in php am getting correct value?
Coz it's in the admin area can that be the reason, don't think so but is there any interference because of tokens?
In most cases, it is going to work okay, however you can use json format(and just json_encode/json_decode will finish the job for you), not sending via GET method and some other modifications.
Are you sure that the url is correct, if you open it in your browser, what happens?
You have to echo the variable in your function in place of return. Because return returns the value to the caller whereas echo sends something to the browser. JavaScript will only understand data which is sent to the browser. So, edit your function code as follows:
public function generate_password($length = 9)
{
echo $password_str;
}
On the other hand you should be doing this over HTTPS rather than HTTP as mentioned by #rodamn
Well strange but changing the url from:
url: "http://127.0.0.1/public/admin/content/manufacturers/generate_password",
to this:
url: "generate_password",
did the trick and everything is working fine now :)
Thanks everyone for their valuable inputs.
Hey guys I am building an application in which I send input value from a text box via AJAX to a controller function and then return what I send back to the user (I am developing an instant search, this is a first step).
The AJAX links to the method fine however I am having problems returning the information. I receive no error messages, the problem is that the return string is BLANK.
I receive [you wrote ] rather than [you wrote WHATEVER I IN PUTTED ]
Any help greatly appreciated.
view_index.php
function search(){
var term = document.getElementById("mainsearch").value;
$.ajax({
type: "POST",
url: "<?php echo base_url('index.php/site/search/')?>",
data: term,
cache: false,
success: function(html){
alert("you wrote " + html);
}
});
controller_site.php
function search(){
$gotcha = $this->input->post('term');
return $gotcha;
}
The data: parameter accept a key : value json to pass to the POST, as the json array key will be your $_POST key
Try with this:
$.ajax({
type: "POST",
url: "<?php echo base_url('index.php/site/search/')?>",
data: {'term': term }
cache: false,
success: function(html){
alert("you wrote " + html);
}
});
You didn't send your data correctly, so PHP has nothing to process, and you end up sending back nothing:
data: term,
POST/GET requests MUST be in key=value format, and you're sending only the value portion. Try
data: {foo: term},
and then
$gotcha = $this->input->post('foo');
You need to change return to echo as AJAX response works on whatever echo from called function.
So, you can code like :
function search(){
$gotcha = $this->input->post('term');
echo $gotcha;
}
or
function search(){
echo = $this->input->post('term');
}
The responseText property returns the response as a string, and you can use it accordingly
It is generally a bad idea to return HTML from your controllers. Instead try to just manage data server-side wise and do all the frontend on the client side.
Now, for the error:
The success callback takes 3 parameters
You need to pass key-value pair in the data argument of the .ajax call
Make sure you handle errors on your controller appropriately because if something goes wrong you'll get an html document as a response from CodeIgniter and you'll spend a lot of time debugging javascript to find out that the error was actually server-side
1 the callback:
Your success callback function should look like this:
function (data, status, response) {
}
Where:
data is whatever you are echoing from your controller's method. You'll probably want JSON.
status Will tell you if the HTTP response message (e.g. "Not Found" is the status for a 404 code, "success" for a 200 code)
response is the jquery wrapped XmlHttpRequest object that gives you a handful information of the transaction, for example response.responseText would give you whatever you outputed from PHP, response.responseJSON would give you a JSON object if you echoed a json encoded object, etc.
Why should you care? Because those extra parameters will let you decide if something went wrong on your backend so you can handle the situation client-side not leaving the user wondering if you app just don't work. Worse, giving the infamous red cross on the status bar of the browser.
If you set the dataType parameter of the jQuery.ajax function then you can explicitly tell jQuery what kind of data you are expecting to be retrieved from the server on data parameter from your callback.
2 the sent data
As said, you need to either pass value-pairs or a URL encoded string. If you intend to use GET then you can pass the URL encoded string, but that means you have to have arguments on your CI function like:
function search($term)
And then CI automatically routes the incoming parameters. But since you want to do POST then you'll want to effectively get the values with $this->input->post("name")
If you have your input inside a form, or several fields that you need to send, then its easier to just serialize the form:
$.ajax("url", {
type : 'POST',
data : $('#form').serialize(),
dataType : 'json',
success : function(data, status, response) {} error : function(response, status error) {}});
3 handle errors
If you are relying on AJAX then make sure that you return some sort of error or warning so you can catch it client side:
function search() {
$term = $this->input->post("term")
if($term == FALSE) {
//return a 404 so that you can catch .error on jquery
} else {
echo $term;
}
}
Do a research on RESTFul apps. It'll help you a lot understanding that. this is a good starting point and although your question was not exactly related to this, it is a good practice to have separate layers on your application so that you just consume data from your backend, handle situations and then just react accordingly on the frontend, that is, you just use javascript to either send, receive and list data. If you are using CI or any other MVC framework then you should not really be generating HTML on your controllers, thats what the views are for.
PJAX's documentation states that Github uses $.pjax.submit() in submitting a Gist form. A desired feature of an ajax form submission which Github nicely implements is that the URL redirects from the form's action to a newly created URL (in this case, one containing the newly server-side created gist ID).
For example, from this:
https://gist.github.com/gists // form action
to this:
https://gist.github.com/tim-peterson/5019589 //assume this ID is generated server side
I've gotten this to work similarly on my site (i.e., the page itself redirects to the equivalent of https://gist.github.com/tim-peterson/5019589) but I can't redirect the URL (it stays like https://gist.github.com/gists).
Is this entirely a server-side issue (setting headers?) or is there something in pjax that I'm missing? I'm using a version of pjax I downloaded today so it can't be that i'm using a buggier version of pjax.
Did you find any solution to this?
I had the similar issue.
Basically you need to set X-PJAX-URL property in response header.
It's value should be same as Request URL.
In Laravel, I did it like this...
App::after(function($request, $response)
{
$response->headers->set('X-PJAX-URL', $request->getRequestUri());
});
There may be a more-elegant / proper way to do this with $.pjax.submit(), but this is the solution I've been using without any problems. I serialize the form inputs prior to submission, then POST them to my server. Then check the reply from the server to make sure I don't need to prevent the user from going forward before calling my PJAX to continue.
$("#save").click(function(e) {
e.preventDefault();
dataString = $("#form").serialize();
$.ajax({
type: "POST",
url: $("#form").attr("action"),
data: dataString,
dataType: "json",
success: function(data)
{
// Handle the server response (display errors if necessary)
$.pjax({
timeout: 2000,
url: data.url,
container: '#main-content'
});
}
});
});
It happens if response HTML doesn't contain initial PJAX container
I have a good understanding of AJAX and normally would have no problems using it but I am relatively new to Joomla and have only recently started building components, etc.
I have created a component (named directory) which is using the 'default' view. Within here I have the following code which is an AJAX call:
<script type="text/javascript">
var url = "index.php?option=com_directory&view=directory&task=clubFilter&format=raw";
jQuery(document).ready(function() {
jQuery('#city').change(function() {
jQuery.ajax({
url: url,
type: "POST",
data: jQuery("#city").serialize(),
dataType: 'json',
success: function(data) {
alert('data');
}
});
});
});
And within my 'views/directory/views.html' file I have created the following function which currently contains a die so I can confirm when it is working:
public function clubFilter() {
die(print_r('here_i_am'));
}
When I run the following code I ge the following error within Firebugs console..
'Error: 500 View not found [name, type, prefix]: directory, raw, directoryView'
I think it is because of the AJAX url var being incorrect but I have tried many different solutions from here nad other sources and just can't get the AJAX function working. Is my URL wrong?
Many Thanks
Normally, I make ajax calls to a task on the controller.
Here is the url format I am using in one of my extensions that uses ajax calls to a component:
index.php?format=raw&option=<component_name_goes_here>&task=<task_goes_here>
Then, in my component's default controller I put a function with the same name as the task:
function getSomeData()
{
echo(json_encode($data));//I normally return json
}
Hope this helps.
try this url. it might help you out.
var url = "index.php?option=com_directory&view=directory&task=clubFilter&tmpl=component";
format=raw replace with &tmpl=component
Else you can try the below format too.
jQuery.post('index.php',{
'option':'component_name',
'controller':'controller_name',
'task':'task_name',
'format':'raw',
'data': jQuery("#city").serialize(),
'dataType': 'json',
},function(result){
//edit the result here
return;
});
If you have any problem regarding this don't hesitate to ask.