zend framework partial not render echo on ajax request - zend-framework

I'd like to render a partial as a response to an ajax request in my controller action.
My goal is to echo a Twitter Bootstrap Alert when ajax request is successful.
Here is my action (redigeraLottningAction):
if($this->getRequest()->isXmlHttpRequest()){
$this->_helper->viewRenderer->setNoRender();
$this->_helper->layout->disableLayout();
echo $this->view->partial('partial/alert-ajax.phtml', array('type' => 'success', 'msg' => 'Lyckat! Lottningen är nu sparad.'));
}
And my partial (alert-ajax.phtml):
<div id="alert-msg" class="alert alert-<?= $this->type?> fade in">
<a class="close" data-dismiss="alert" href="#">×</a>
<p><?= $this->msg?></p>
</div>
The problem is that the php scripts in the partial is outputed as text. This is what it looks like in the browser with variables not rendered:
<div id="alert-msg" class="alert alert-<?= $this->type?> fade in">
<a class="close" data-dismiss="alert" href="#">×</a>
<p><?= $this->msg?></p>
</div>
And the jquery part:
$(document).ready(function(){
$('#lottning-spara').click(function () {
$.ajax({
type: "POST",
url: '/turnering/redigera-lottning',
cache: false,
data: {id: getParam("turnering"), klass_id: getParam("klass"), type: "spara", lottning: $('#lottning_str').val()},
dataType: 'html',
success: function(msg){
$('#alert-div').html(msg);
},
error: function(){
$('#alert-div').html('Error!');
}
});
});
});
Any ideas why the php in partial is not rendered??
Edits are bold.
Problem Solved.
The alert-ajax.phtml file was a different charset type.

What if you try this:
<div id="alert-msg" class="alert alert-<?php echo $this->type; ?> fade in">
<a class="close" data-dismiss="alert" href="#">×</a>
<p><?php echo $this->msg; ?></p>
</div>
if($this->getRequest()->isXmlHttpRequest()){
$this->view->assign(array('type' => 'success', 'msg' => 'Lyckat! Lottningen är nu sparad.'));
echo $this->view->render('partial/alert-ajax.phtml');
exit;
}

Problem Solved. The alert-ajax.phtml file was a different charset type.

Related

How to create mysql table entry on form submission in CodeIgniter

I just need to insert data to table on form submission with the entered inputs.
my Controller,
function create_wish() {
$data = array(
'user_name' => $this->input->post('uname'),
'user_email' => $this->input->post('uemail'),
'user_message' => $this->input->post('umessage')
);
$this->model_wishes->createWish($data);
}
model,
function createWish($data) {
$sql = "INSERT INTO wishes (user_name, user_email, user_wish) VALUES (".$data.user_name.", ".$data.user_email.", ".$data.user_message.")";
$this->db->query($sql);
echo $this->db->affected_rows();
}
view,
<form method="post" action="<?php echo base_url() . "index.php/Welcome/create_wish"?>">
<div class="row">
<div class="form-group col-md-6">
<label for="post-name">Name</label>
<input autocomplete='name' type="text" class="form-control" id="uname" name="uname" required />
</div>
<div class="form-group col-md-6">
<label for="post-email">Email</label>
<input autocomplete='email' type="email" class="form-control" id="uemail" name="uemail" required/>
</div>
</div>
<div class="row">
<div class="form-group col-md-12 margin-b-2">
<label for="post-message">Message</label>
<textarea class="form-control" id="umessage" rows="5" name="umessage"></textarea>
</div>
</div>
<div class="row">
<div class="form-group col-md-12 text-left mb-0">
<button id="btn-create" type="submit" class="button-medium btn btn-default fill-btn">Post Wish</button>
</div>
</div>
</form>
Ajax,
$(document).ready(function () {
$('form').submit(function (event) {
var formData = {
'user_name': $('input[name=uname]').val(),
'user_email': $('input[name=uemail]').val(),
'user_wish': $('input[name=umessage]').val()
};
$.ajax({
type: 'POST',
url: 'http://localhost/CodeIgniterProj/index.php/create_wish',
data: formData,
dataType: 'json',
encode: true
})
.done(function (data) {
console.log(data);
});
event.preventDefault();
});
});
execution of above codes displays an error in console
POST http://localhost/CodeIgniterProj/index.php/create_wish 404 (Not Found)
XHR failed loading: POST "http://localhost/CodeIgniterProj/sender.php".
I tried to fix this and failed. Someone please let me know how to fix this issue, help me on this.
Your URL is missing the controller segment
you should call index.php/[controller]/[method]. Regarding the sender.php i cannot see any call to it. Maybe there are other forms in the markup.
Besides that, the model will not work as expected. Since you are dealing with an array you should change:
... VALUES (".$data.user_name.", ...)
to
...(VALUES (".$data["user_name"].", ...)
If you don't want to use the active record class, you should escape the values in your query.
https://www.codeigniter.com/user_guide/database/queries.html#escaping-queries
I hope it helps.
Use site_url in your ajax url , should be like this
$(document).ready(function () {
$('form').submit(function (event) {
var formData = $(this).serialize();
alert(formData);
$.ajax({
type: 'POST',
url: '<?=site_url('Welcome/create_wish');?>',
data: formData,
dataType: 'json',
}).done(function (data) {
console.log(data.id);
});
event.preventDefault();
});
});
Your controller should be like this :
function create_wish() {
$data = array(
'user_name' => $this->input->post('uname'),
'user_email' => $this->input->post('uemail'),
'user_message' => $this->input->post('umessage')
);
$insert_id = $this->model_wishes->createWish($data);
if($insert_id)
{
$response = array('status' => 'success');
}
else
{
$response = array('status' => 'error');
}
echo json_encode($response);
exit;
}
Your model method createWish should be like this ;
function createWish($data)
{
$this->db->insert('wishes', $data);
return $this->db->insert_id();
}

Jquery - Sortable did not work when div.load is called

I have this issue that every time the div is loaded using div.load in the ajax success, the code for sortable will not work. Sortable will work again after the page is refreshed manually. What could be the possible solution for this?
$(document).on('click', '#add-song-tag', function() {
tag_id = $('#tags').val();
$.ajax({
url: base_url + '/songtags/add_song_tag',
type: 'POST',
data: {
song_info_id: song_info_id,
tag_id: tag_id
},
success: function() {
$('#category').load(window.location.href + ' #category');
$('#modal-categories').trigger('change');
},
error: function(xhr) {
console.log(xhr.responseText);
}
})
});
I have my code in the sortable.js like
$( function() {
$( "#sortable, #sortable1" ).sortable({
connectWith: ".draggable-group",
start: function(event, ui){
$(ui.item).width($('#sortable div').width());
}
// containment: "parent",
// tolerance: "pointer"
}).disableSelection();
} );
and in the html it looks something like:
<?php if($selected_tag_for_m['category_id'] == $tempo_id):?>
<div class="btn-group draggable-group">
<div>
<i class="fa fa-minus-circle fa-lg delete-a-tag" aria-hidden="true"></i>
</div>
<div type="button" class="btn btn-default btn-color"><i class="fa fa-circle-o custom-text-blue"></i> <?php echo $selected_tag_for_m['tag_name'];?> </div>
<div type="button" class="btn btn-default custom-bgcolor-blue dropdown-toggle" data-toggle="dropdown">
<span><i class="fa fa-pencil"></i></span>
<span class="sr-only">Toggle Dropdown</span>
</div>
<ul class="dropdown-menu" role="menu" id="tempo">
<?php foreach($tempos as $tempo):?>
<li data-id="<?php echo $selected_tag_for_m['info_tag_id']?>"><a href="" data-id="<?php echo $tempo['tag_id']?>" class="songtaglist" ><?php echo $tempo['tag_name'];?></a></li>
<?php endforeach;?>
</ul>
</div>
<?php endif;?>
I found solution to this by calling sortable.js script in body of the load function. The code looks like this:
$('#category').load(window.location.href + ' #category', function(){
$.getScript(base_url + '/assets/js/sortable.js');
});

Unable to get mizzao/meteor-autocomplete to work with collection

I am using mizzao/meteor-autocomplete and am having problems in trying to get it to work.
When viewing the page in my browser, I am getting no results at all when typing any text. I've created the appropriate collection:
Institutions = new Mongo.Collection("institutions");
and know that there is data in the actual db, however still no success.
I've included my files below.
publications.js (located in the server folder)
Meteor.publish('institutions', function(args) {
return Institutions.find({}, args);
});
registrationStart.js
I've two helpers; one that actually powers the search and the other that should be returning the institutions. I have also tried this with the token: '#' argument with no success.
if (Meteor.isClient) {
Template.registrationStart.helpers({
settings: function() {
return {
position: "top",
limit: 7,
rules: [{
collection: Institutions,
field: "name",
options: '',
matchAll: true,
template: Template.institutionSelectDisplay
}]
};
},
institutions: function() {
return Instititions.find();
}
});
Template.registrationStart.events({
"autocompleteselect input": function(event, template, doc) {
// Session.set(event.target.name, event.target.value);
console.log("selected: ", doc);
console.log("event.target.name: ", event.target.name);
console.log("event.target.value: ", event.target.value);
}
});
}
registrationStart.html template
<template name="registrationStart">
<div class="panel-body" id="loginForm">
<h2 class="pageTitle">veClient Registration</h2>
<form>
<div> </div>
<fieldset>
{{> inputAutocomplete settings=settings id="institution" class="input-xlarge" placeholder="type institution here"}}
</fieldset>
<div> </div>
<button type="submit" class="btn btn-primary btn-sm">Continue Registration</button>
</form>
</div>
</template>
And the template to be rendered
<template name="institutionSelectDisplay">
<p class="inst-state">{{city}}, {{state}}</p>
<p class="inst-name">{{name}}</p>
<p class="inst-description">{{email}}</p>
</template>
Problem resulted because there was no subscription to the "institutions" publication. So need to add a subscribe statement to the registrationStart.js file:
Meteor.subscribe('institutions');

Show bootstrap popover after submitting form that is in modal

I have a form, that is in remote modal window. Here is the modal in index.html:
<a data-toggle="modal" href="contact.html" data-target="#myModal">Contact Me</a>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
</div>
</div>
</div>
Than here is acctual form in contact.html:
<script>
$('#pop').popover({content: 'Message send.'},'click');
</script>
<form id="contactform" method="post" action="data/send_mail.php">
<!--
here is whole form content
-->
<button type="submit" value="Submit" class="btn btn-custom" data-toggle="popover" data-placement="right" id="pop">Send</button>
</form>
Now my problem is: I need to show bootstrap popover after not clicking on the submit button but when the form is really send. I do the validation in browser(no php regular expressions or jQuery validate, simply in browser).
My approach was following (after gathering the data from from and creating message in send_mail.php):
#mail($email_to, $email_subject, $email_message, $headers);
/* Here should be something that will make my popover show, like: echo ('$('#pop').popover('show')');*/
sleep(2);
echo "<meta http-equiv='refresh' content=\"0; url=../index.html\">";
But this second command (in comment does not work). I am total newbie in php, so I try to make my solutions as simple as possible. I hope that I have explained my problem properly.
Thx...
Instead of putting an action to the form you can just leave it blank and do the submit call using jquery.
SCRIPT
This script will be able communicate with your data/send_mail.php and by getting the value from the html input which has an id of name we can pas that as a parameter to the send_mail.php.
<script type="text/javascript">
$('#myButton').on('submit', function(){
var data_value = $('#name').val();
var data_value2 = $('#name2').val();
var data_value3 = $('#name3').val();
var url = 'data/send_mail.php';
$.ajax({
type: "GET",
url: url,
data:{'data_to_pass':data_value,
'second_data': data_value2,
'third_data': data_value3},
success:function(){
$('#pop').popover('show');
}
});
});
</script>
the complete URL will be data/send_mail.php?data_to_pass=data_value
HTML
<form>
<input id="name" type="text" placeholder="input something here" required />
<button id="button" type="button" value="Submit" class="btn btn-custom" data-toggle="popover" data-placement="right" id="pop">Send</button>
</form>
Hope this helps.

view not refreshing after zend redirect

so what i am trying to do, is after the user submit some information, i make a call to a action call saveronda, to save the information on the database, after saving i want to redirect to another page, according to the firebug the html is correct, but the view isnt refreshing.
so here is the code
so in my /rondas/chooseronda ive got this
<span class="st-labeltext">Tags da ronda:</span>
<table id="toolbar2"></table>
<div id="ptoolbar2"></div>
<div class="clear" style="z-index: 670;"></div>
</div>
<div class="st-form-line" style="z-index: 680;">
<span class="st-labeltext">Nome da ronda:</span>
<input type="text" name="nomeronda" id="nomeronda">
<div class="clear" style="z-index: 670;"></div>
</div>
<div class="st-form-line" style="z-index: 680;">
<span class="st-labeltext">Tag Inicial:</span>
<select id="tagini" name="tagini">
</select>
<div class="clear" style="z-index: 670;"></div>
</div>
<div class="st-form-line" style="z-index: 680;">
<span class="st-labeltext">Tag Final:</span>
<select id="tagfim" name="tagfim">
</select>
<div class="clear" style="z-index: 670;"></div>
</div>
<div class="st-form-line" style="z-index: 680;">
<span class="st-labeltext">Ordem:</span>
<select id="ordem" name="ordem">
<option value="Sim">Sim</option>
<option value="Não">Não</option>
</select>
<div class="clear" style="z-index: 670;"></div>
</div>
<div class="button-box" style="z-index: 460;">
<input id="button" class="st-button" type="submit" value="Submit" name="button">
<input id="button2" class="st-clear" type="reset" value="Cancel" name="button">
</div>
when the user press the button submit i am making an ajax call to /rondas/saveronda and send some data, here is the code:
<script language = "Javascript">
$(document).ready(function() {
$("#button").click(function () {
/*
$.ajax({
url: '/rondas/saveronda',
type: 'POST',
data: {param1: param1, param2:param2 },
datatype: "json"
*/
//buscar o nome
/*var nomeronda=$("#nomeronda").val();
//buscar a ordem
var ordem=$("#ordem").val();
//tag inicial e tag final
var taginicial=$("#tagini").val();
var tagfinal=$("#tagfim").val();
if(taginicial==tagfinal)
{
alert("a tag inicial não pode ser a mesma que a tag final");
}
else
{
var tags="";
//var allRowsOnCurrentPage = $('#toolbar2').getDataIDs();
var ids = $("#toolbar2").jqGrid('getDataIDs');
for (var i = 0; i < ids.length; i++)
{
var rowId = ids[i];
var rowData = $('#toolbar2').jqGrid ('getRowData', rowId);
tags=tags+rowData.id_tag.toString()+' ';
}*/
$.ajax({
url: '/rondas/saveronda',
type: 'POST',
data: {param1: "sasa"},
datatype: "json"
});
//}
});
});
</script>
in this case i am sending param1 with the value "sasa", and through firebug i am detecting the post to the /rondas/saveronda.
after saving the data i want to redirect the user to /rondas/list, so i have been trying different solution
public function saverondaAction()
{
// action body
/*
if($this->_request->isXmlHttpRequest())
{
$param1 = $this->_request->getParam('param1');
$param2 = $this->_request->getParam('param2');
$param3 = $this->_request->getParam('param3');
$param4 = $this->_request->getParam('param4');
$param5 = $this->_request->getParam('param5');
$rondasModel= new Application_Model_Ronda();
$this->_forward('list', 'rondas');
}
*
*/
$this->_helper->redirector->gotoRoute(
array(
'controller' => 'rondas',
'action' => 'list'
)
);
}
or using redirect or forward..
none have worked, the view is still the /rondas/choosetags and not /rondas/list
what is my error...
thanks in advance..
Your initial view is /rondas/chooseronda when user press submit you make ajax call to /rondas/saveronda and send some data to it. Now if this is successful you want to redirect from the initial page (/rondas/chooseronda) to /rondas/list.
If the redirect code written in action /rondas/saveronda is not working, then you could return a success message back to initial view (/rondas/chooseronda), there you'll need to detect the success message in jQuery ajax code. If successful, put the redirect jQuery code, that will redirect it to /rondas/list.