yii controller action won't fire from form - ajax

I'm trying get a simple ajax call working with yii, not using the native yii means. My goal is to populate state and city fields on input from a zip code field, using a db look up in the create action. I have a separate javascript file,
$('#Accounts_zip').bind('focusout',function(){
$.ajax({
type: 'POST',
url:'/gatesadmin/index.php?r=Accounts/Ziplookup',
data: {zip:$('#Accounts_zip').val()},
success: function(datain, textStatus, jqXHR) {alert(datain.statecode);} ,
error: function(jqxhr, textStatus, errorthrown){alert(errorthrown);},
dataType:JSON
});
alert($('#Accounts_zip').val());
});
and in my AccountsController I have:
public function actionZiplookup()
{
$z = new ZipDao();
$row = $z->GetCityStateByZip($_REQUEST['data']);
header('Content-Type: application/json; charset="UTF-8"');
echo CJSON::encode(array('output'=>$row));
}
and my form is out of the box generated CRUD:
...
<div class="row">
<?php echo $form->labelEx($model,'zip'); ?>
<?php echo $form->textField($model,'zip',array('size'=>10,'maxlength'=>10)); ?>
<?php echo $form->error($model,'zip'); ?>
</div>
...
I know the javascript is working because I get my alert, and if I call the URL directly yii fires the actionZiplookup event because I'm getting the returned json. I just can't seem to be able to get the form to invoke the ajax successfully because I get External Server error in the jquery ajax failure event. I've combed through the net and the closest examples I can find embed the javascript in the form itself and use the Yii::app()-createUrl() method to define the url, but there has to be a way getting the controller action to fire while keeping javascript code in a separate file.
Any help would be greatly appreciated.

It turns out what I was missing can be found here:
How to get response as json format(application/json) in yii? It all has to do with telling the controller to ignore the layout, etc.

Related

getting a response data in ajax using codeigniter

Hi i have this data which i want that only a certain div will refresh using ajax. How will i able to pass the json_encode to the ajax what will load the data on a certain div using codeigniter.
Heres my controller below
$this->data['getNumberOfMessages'] = $this->mm->getNumberOfMessages($this->data['id']);
$this->data['countNumber'] = $this->data['getNumberOfMessages'];
$responseOnject = new stdClass();
$responseOnject->status = 'ok';
$responseOnject->StatusMessages=$this->data['countNumber'];
$this->output->set_output(json_encode($responseOnject));
this line of code here
$this->output->set_output(json_encode($response));
outputs this one
{"status":"ok","StatusMessages":20}
and i want that to pass through my ajax in my code below
$(document).ready(function(){
var id =$(this).data("messageid");
$.ajax({
type: "get",
url: $(this).data("href"),
success: function(data){
alert(data.StatusMessages);
console.log(data.StatusMessages);
$("#" + id + ' span.badge').html(data.StatusMessages);
}
});
});
and target on my certain div so that it will automatically refresh
below is my code
<tr>
<th>
<a href="#" id="<?php echo $id; ?>" data-messageid="<?php echo $id; ?>" data-href="<?php echo base_url().'profile'?>" title="messages">
<span class="badge"><?php echo $countNumber; ?></span>
message(s)</a>
</th>
</tr>
when i tried to alert(data.StatusMessages);it return undefined.
can someone pls help me figured this thing out? ive been stuck in this.. my code really works but i want to be ajax, only certain div refresh without refershing my entire page.
Any help is muchly appreciated.
You need to decode the response JSON first in order to be able to access it as a JS object. This is how it's done in JS:
JSON.parse(JSONStringHere);
So, your success callback should be:
success: function(data){
data = JSON.parse(data); // this is what decodes JSON
alert(data.StatusMessages);
console.log(data.StatusMessages);
$("#" + id + ' span.badge').html(data.StatusMessages);
}
As I said in the comments, you're not calling the right URL with AJAX (although you said you do and that it returns that JSON string; if so, the code above would work). This doesn't look like it would give you a URL:
$(document).ready(function(){
var id =$(this).data("messageid");
$.ajax({
type: "get",
url: $(this).data("href"), // <---- what is the value of this?
Once you fix that, your code will work.
For JSON data your controller should have the following line to output
UPDATE
Just noticed your problem is that codeigniter is outputting html along side your ajax response.
To Make this go away, Your code in the controller should be like this:
$this->output
->set_content_type('application/json', 'utf-8')
->set_output(json_encode($responseOnject))
->_display();
exit;
This would force the output library to display & the exit to stop displaying anything else.
If you do not set the application/json content type, your response won't be treated as JSON And you'd have to use JSON.parse in your javascript code to convert it to json which is a bad practice.

CodeIgniter using Ajax

I cant find error when i click on a button nothing happens, i dont get any error in console, very is error maybe in data field?
I have ajax part
$(document).ready(function() {
$('#brisanje').click(function() {
$.ajax({
url: 'localhost/test2/home/ajax',
type: 'Post',
data: form_data,
success: function() {
alert("paun");
}
});
});
});
button
<button type="submit" id="brisanje" class="btn btn-danger btn-xs">Obriši sliku</button>
and controler
public function ajax(){
redirect('home/login');
}
Try doing this way in your ajax function ,
url : <?php echo base_url(). 'home/ajax' ; ?>,
type : POST,
Answer: Redirecting in the ajax() function caused the problem. I'll leave my junk here anyway, but since I got the checkmark I best provide the actual answer!
This doesn't seem to solve the problem, but I'll leave it here for now anyway
It looks like you're missing the "Action" part of your controller action. You probably are getting a 404 error, although I can't remember exactly what happens when CI cannot find the controller action. Maybe its a 403 error.
Anyway, try naming your ajax function ajaxAction and see if that works. A way to test this would be to browse directly to the url http://localhost/home/ajax (bypass the actual ajax) and you should see any errors that occur.
If you're using a browser with a debugger (most of them, push F12 and see what you get), you should also be able to see the ajax request firing in the console or network tab, and then you can inspect the response for errors.

wordpress create user after form submit with ajax call

i am submitting on form in my wordpress template which goes to remote website now i want to create user with that from fields.but if the form submitted normally then user will not created and form will be redirect to remote url so i use ajax call for this,how ever the user is created but after success function it shows 404 file not found and form does not get submitted.here are the codes first one is ajax request from form fields
<script language ="javascript" type = "text/javascript" >
$na= jQuery.noConflict();
$na(document).ready(function(){
$na('#infuse').click(function(){
alert('start');
var name=$na('#inf_field_FirstName').val();
var password=$na('#inf_field_Password').val();
var email = $na('#inf_field_Email').val();
$na.ajax({
type: "POST",
url: '<?php bloginfo('template_url')?>/user_create.php',
data: 'name='+name+'&email='+email+'&password='+password,
cache: false,
success: function(){
jQuery("#inform").submit();
}
});
});
});
</script>
here is code in user.php file
<?php require('./../../../wp-blog-header.php'); ?>
<?php
$name=$_REQUEST['name'];
$email=$_REQUEST['email'];
$password=$_REQUEST['password'];
wp_create_user( $name, $password, $email );
?>
how ever user created in admin that means ajax works but after that it shows 404 error in console and the form submit process stops
use
<?php require('./../../../wp-load.php'); ?>
in place of
<?php require('./../../../wp-blog-header.php'); ?>
Use:
<?php require('../../../wp-load.php'); ?>
Instead of:
<?php require('./../../../wp-blog-header.php'); ?>

How to send a parameter and update an element using ajax in cakephp 2.x

I have an input field "#PostTitle" in which the user can enter a URL.
I want to send the user's input (upon change or upon exiting the field) to an action in my Posts controller which returns an array. Without CakePHP I think this would look something like this:
$(document).ready(function(){
$('#PostTitle').change(function(){
$.ajax({
type: 'POST',
url: '/posts/setPostImages',
data: $(this).serialize(),
success: function(data){
do something;
},
error: function(message){
console.debug(message);
}
});
return false;
});
});
The action in the Posts controller sets an array of links called $imageArray
(I CURL the page and return an array of all the images on that page, if it's of any interest).
Then, after I make the request, I would like to update an element which depends the contents of that array. The element contains the following code:
<div id="slider-wrap" class="boxframe">
<div class="coda-slider" id="slider-id">
<?php foreach ($imageArray as $image): ?>
<div class="crop">
<?php echo $this->Html->image($image); ?>
</div>
<?php endforeach; ?>
</div>
</div>
Any help is appreciated!
Edit: If I try this, the action isn't called at all:
echo $this->Js->link('update',
array('action' => 'setPostImages'),
array(
'update' => '#selectImage',
'data' => 'www.stackoverflow.com',
'async' => true,
'dataExpression'=>true,
'method' => 'POST'
)
);
If you want to generate this JS with CakePHP, take a look at JsHelper's event method and request method
The action the POST request hits should render your element and respond with HTML. JsHelper::request will then replace the contents of the element specified by the update param with your HTML.
Personally, I find it fairly obtuse to generate Javascript with a PHP framework. It quickly becomes difficult to do what you want. If you have even a moderate amount of Javascript, I recommend just writing it directly (you already seem to know how to do this!).
Your edit refers to a possibly different issue. What kind of Javascript errors are you getting in your browser's console when you click the link generated by that snippet?

jquery ajax codeigniter

I wanted to ask, why does the response from a ajax request using the native ajax not post or get return my entire page? is there anything I should know? I have looked at the documentation on jquery.com and nothing is mentioned of something like that unless i'm looking else where. Can I get any help on why that keeps happening?
This is the function that handles the validation of the form in question.
joe
function showsupport()
{
$this->form_validation->set_rules('supportername','Your Name','trim|required|max_length[20]|xss_clean');
$this->form_validation->set_rules('supporteremail','Email Address','trim|required|valid_email|xss_clean');
$this->form_validation->set_rules('pledgedate','Pledge Date','trim|required|xss_clean');
$this->form_validation->set_rules('messagetxt','Your Message','trim|required|xss_clean');
if($this->form_validation->run() == FALSE)
{
echo validation_errors();
} else {
$this->load->model('support_m');
$name = $this->input->post('supportername');
$email = $this->input->post('supporteremail');
$date = $this->input->post('pledgedate');
$msg = $this->input->post('messagetxt');
$qry = $this->support_m->storepledge($name,$email,$date,$msg);
if($qry){
//$this->template->write_view('content','thanks');
//$this->template->render();
$datamsg['supportmsg'] = 'Message Added Successfully';
}else{
echo 'There was an error inserting into db';
}
}
}
This is the view with the form generated.
<?php
$formdata = array('id'=>'suppform');
echo form_open('homepage/showsupport',$formdata);
$namedata = array('name'=>'supportname','id'=>'supportname','size'=>'30','max_length'=>'25','value'=>set_value('supportname'));
echo '<label for="supportername">Your Name:'.form_input($namedata).'</label><br /><br />';
$emaildata = array('name'=>'supporteremail','id'=>'supporteremail','size'=>'30','max_lenth'=>'25','value'=>set_value('suppoteremail'));
echo '<label for="supporteremail">Email Address:'.form_input($emaildata).'</label><br /><br />';
$pledgedata = array('name'=>'pledgedate','id'=>'pledgedate','size'=>'30','max_length'=>'20','value'=>set_value('pledgedate'));
echo '<label for="pledgedate">Today\'s Date:'.form_input($pledgedata).'</label><br /><br />';
$msgdata = array('name'=>'messagetxt','id'=>'messagetxt','col'=>'2','rows'=>'8');
echo '<label for="messagetext">Your Pledge:'.form_textarea($msgdata).'</label><br />';
$submitdata = array('name'=>'submitbtn','id'=>'submitbtn','value'=>'Send');
echo '<label for="submitbutton">'.form_submit($submitdata).'</label><br />';
echo form_close();
?>
</div>
<div id="errorsechoed"><?php echo validation_errors();?></div>
The html of the retured page is dumped in the div #errorsechoed
$('#suppform').submit(function(eve){
eve.preventDefault();
$.ajax({
type: 'POST',
cache: false,
url: 'homepage/showsupport',
data: $('#suppform').serialize(),
beforeSend: function(){
$('#supportform').block({message:'<h4> Processing...</h4>'})
},
complete: function(){
},
success: function(html){
$('#errorsechoed').text(html);
}
});
});
I have been trying to get this figured out and I think I have made some progress, here is what I have:
a) the template library from William Colin works where regions are specified and so only a particular region will be refreshed all the time and not the only page. As a result it sort of works differently from other standard setups for codeigniter. This is definitely getting in the way of jquery getting a response from the server. It gets the bits of template library (i.e. regions) and renders it out which ends up rebuilding the whole page again.
b) When you run the form_validation library, Template doesn’t allow you to just load a view the normal way in codeigniter, rather you do this by running:
$this->template->write_view('contentregion','viewname'); //writes the view
$this->template->render(); //renders the view on screen.
so if this is not done if validation fails, the error messages spat out by the formvalidation library just never seem to get to the view.
I have tried a lot of permutations of using functions that come with this library and still am just able to render out another page of my site. confused
CONCLUSION:
I think this template library is great but it needs some updating so these issues are met. I will have to look at other templating systems when I have to do a site with a lot of ajax required. Hope Mr. William can see this and help look into this.
Thanks community for an avenue to say what I have learned. Hope this is useful to someone.
It's because you are setting the datatype in the postback to be of type 'html':
"html": Returns HTML as plain text;
included script tags are evaluated
when inserted in the DOM.
if you just want to show that the request succeeded or failed you can have #errorsindicated populated like so:
success: function(){
$('#errorsechoed').html('<h4> Request Successfull...</h4>');
}
error: function(){
$('#errorsechoed').html('<h4> Request Failed...</h4>');
}
you can get more detailed information on the error if you want. See the error option section of the jQuery ajax documentation: http://api.jquery.com/jQuery.ajax/

Resources