change username settings dynamically php - php

I want to change username name dynamically when user change the settings. Without refresh it should change the name. Any help would be appreciated.
settings code file:
if($User_Name != $row['USERNAME'])
{
$insert = "UPDATE USER_LOGIN SET PASSWORD = '".$New_Password."', USERNAME = '".$User_Name."' WHERE USERNAME = '".$_COOKIE['username']."'";
$result = oci_parse($con, $insert);
// Executes a statement.
$check = oci_execute($result);
if($check)
{
echo "Saved";
// Commit the changes to the table.
oci_commit($con);
}
else
{
// Rollback changes to table.
oci_rollback($con);
}
}
Admin Panel:
<div class="user">
<img src="../../img/Users/Users/Admin.jpg" align="left"/>
<a class="name">
<?php
session_start();
if(isset($_COOKIE['username']))
{
echo $_COOKIE['username'];
}
else
{
echo $_SESSION['username'];
}
?>
<span class="sm">Administrator</span>
</a>
</div>
My ajax function is like this:
<!-- Ajax function is used to post the data to databse and show result in the table without refresh -->
<script>
var frm = $('.wrefresh');
frm.submit(function (ev)
{
ev.preventDefault();
var postdata = $(this).serialize();
var path = $(this).attr("action");
var mehtodtype = $(this).attr("method").toUpperCase();
// Clear fields data. (password).
$('form :input[type=password]').attr('value','');
// Remove selected pictures field.
$('#Picture').attr('src', '../../img/User No-Frame.png');
$.ajax
({
type: mehtodtype,
url: path,
data: postdata,
success: function(data)
{
if(data === "Please Fill Entries.")
{
$('#fullname').css("border-color", "rgb(219, 46, 46)");
$('#old').css("border-color", "rgb(219, 46, 46)");
$('#new').css("border-color", "rgb(219, 46, 46)");
$('#confirm').css("border-color", "rgb(219, 46, 46)");
$('#showmediv').show();
}
}
});
});
</script>
Html:
<form class="wrefresh" action="../Code Files/User.php" method="post">
<div id="photo_settings2" style="margin-left:74px;">
<img id="Picture" src="../../img/User No-Frame.png"/>
</div>
<br><br><br><br>
<div id='Upload_Panel' style="margin-left: 32px;">
<input name='file' type='file' id='file_browse' onchange="readURL(this,'Picture')" style="cursor: pointer;"/>
</div>
<div id="delete" style="margin-top: -40px; margin-left: 198px; cursor: pointer">
<img src="../../img/Delete_Panel.png">
</div>
<div style="margin-left:144px; margin-top:-15px"></div>
<br><br>
<div class="row-form" style="margin-top:10px">
<div class="span4">Username:</div>
<div class="span8"><input id="fullname" style="border: 1px solid #918C8C" type="text" class="cNav" name="uname" value=""/></div>
</div>
<div class="row-form">
<div class="span4">Old Password:</div>
<div class="span8"><input id="old" style="border: 1px solid #918C8C" type="password" class="cNav" name="opass" value=""/></div>
</div>
<div class="row-form">
<div class="span4">New Password:</div>
<div class="span8"><input id="new" style="border: 1px solid #918C8C" type="password" class="cNav" name="npass" value=""/></div>
</div>
<div class="row-form">
<div class="span4">Confirm:</div>
<div class="span8"><input id="confirm" style="border: 1px solid #918C8C" type="password" class="cNav" name="cpass" value=""/></div>
</div>
<br>
<div class="row-fluid" style="margin-left:112px; margin-top:-05px">
<div class="span9">
<button type="submit" class="btn btn-success" style="height:28px">Save</button>
<span id="showmediv" class="label label-important" style="display: none; margin-left: 14px; margin-top:-35px">Please Enter Fields</span>
</div>
</div>
</form>

You need to change the username which you are showing inside
<a class="name">
in ajax success callback like this:
I am not sure it will work or not.
$.ajax
({
type: mehtodtype,
url: path,
data: postdata,
success: function(data)
{
if(data === "Please Fill Entries.")
{
$('#fullname').css("border-color", "rgb(219, 46, 46)");
$('#old').css("border-color", "rgb(219, 46, 46)");
$('#new').css("border-color", "rgb(219, 46, 46)");
$('#confirm').css("border-color", "rgb(219, 46, 46)");
$('#showmediv').show();
//get new name
var userName = $("#fullname").val();
// show new username
$(".name").html(userName);
}
}
});
Onemore thing:
when you are sending ajax call you need to set new username in SESSION .

I hope you are trying to post the form without refreshing as I didnt understood what you were trying to achieve
What you need to do is use ajax to submit your form . Try this plugin and add the following code
http://jquery.malsup.com/form/#ajaxSubmit
download the plugin
and in the form add this
<form onsubmit="javascript:login();return false;">
function action(){
$('#form').ajaxSubmit({
target:'#output_login',
url:'./php/page.php'
});
return false;
}

Related

Search filter bootstrap card didn't show the specific image

When I'm searching the specific name of the image. The rest of the name of the row still showing, but I just want to view only the data from the search. See image below
Display: Select all the data from the database.
<?php$checkQuery = "SELECT `h_business_logo`,`h_business_name`,`h_business_desc` FROM user_bsns WHERE h_isActive = 1 ORDER BY h_business_name DESC";
$checkResult = mysqli_query($db->conn, "$checkQuery")
?>
Card: This card has an animation
<div class="card-body col-lg-12" >
<div class="card-body col-lg-12">
<input class="form-control" id="myInput" type="text" placeholder="Search.." style="float:left; width:25%;">
<button class="btn" style="margin-left: 5px;background-color: #e72329;color: white;"> Search </button>
</div>
<?php
if(mysqli_num_rows($checkResult) > 0):{
}
while($row = mysqli_fetch_array($checkResult)){
?>
<div class="panel" id="myDIV">
<div class="holder flipH" >
<div class="card shadow-none">
<div class="col-sm-0 column <?=$row['h_business_name'];?>" >
<div class="front"style="float:left; >
<img src="<?=$row['h_business_logo']; ?> "
style="height:150px; width:155px; border-radius: 50%; ">
</div>
</div>
<span style= "text-align:center;">
<h5><?=$row['h_business_name'];?></h5>
</span>
<span style="text-align:center;">
<p><?=$row['h_business_desc'];?></p>
</span>
</div>
</div>
</div>
<?php
}
endif;
?>
</div>
<!-- /.card-body -->
</div>
And this one is the function of the search filter.
<script>
$(document).ready(function(){
$(".btn").on("click", function() {
var value = $("#myInput").val();
lastval = "col-sm-5 column "+value;
x = document.getElementsByClassName("column");
$("#myDIV div").filter(function() {
for (i = 0; i < x.length; i++) {
element = x[i];
if (element.className.indexOf(value) == -1){
element.classList.add("nonshow");
element.classList.remove("show");
}
else {
element.classList.add("show");
element.classList.remove("nonshow");
}
}
});
});
});
</script>
Please help me to improve the codes.
Update: I solved my problem using this script(jquery)
update: I used this script in order to search automatically.
$(document).ready(function(){
$("#myInput").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#myDiv ").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1);
});
});
});

Fetch the ID to post in ajax

I need some help with my code as I have got a problem with defined the variable to post them in Ajax. I am working on PHP as I am fetching the data from mysql database to input the information in PHP, so I would like to post the ID in ajax.
I have defined the variable $autoid outside of the while loop, but I am unable to defined them when I am using jquery because it will show empty data when I try to post them in Ajax.
When I try this:
var ID = $(this).data('deleteid');
$.ajax({
type: 'POST',
url: "sendtest.php",
data: {ID : "deleteid"
},
success: function(resultData) {
alert(resultData)
}
Here is the full code:
<?php
// Initialize the session
session_start();
// Check if the user is logged in, if not then redirect him to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: login.php");
exit;
}
else
{
$link = mysqli_connect('localhost', 'mydbusername', 'mydbpassword', 'mydbpassword');
$param_username = $_SESSION['username'];
$autocampaign = $_SESSION["auto_campaign"];
$autor_sql = "SELECT id, subject, day_cycle, enabled, delaysend FROM auto WHERE campaign ='$autocampaign' AND username ='$param_username'";
$autoid = '';
$results = mysqli_query($link, $auto_sql);
if (mysqli_num_rows($results) > 0)
{
while ($row = mysqli_fetch_array($results))
{
$autoid = $row["id"];
$autosubject = $row["subject"];
$autodaycycle = $row["day_cycle"];
$autoenabled = $row["enabled"];
$autodelay = $row["delaysend"];
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style type="text/css">
.calendar-content {
float: left;
width: 100%;
min-height: 112px;
border: 1px solid #ccc;
position: relative;
margin-top: -1px;
}
</style>
<div class="calendar-content">
<div style="margin-left: 40px;margin-top: 20px; height: 40px;">
<span id="autosubject" style="font-size: 25px;color: #0c7ac0;float: left;">Subject: <?php echo $autosubject ?> </span><br>
<div style="margin-left: 35px; margin-top: 15px; height: 40px;">
<form action="" method="post">
<span style="font-size: 15px; color: #ccd5d9; float: left; margin-top: -1px"><a name="autoid" id="autoid" href="#contactModal" role="button" data-toggle="modal">Send a test</a> | <a name="deleteid" id="deleteid" href="/auto/delete_auto.php?id=<?php echo $autoid; ?>"> Delete </a> | Copy to Draft | Settings</span>
</form>
</div>
</div><br>
<!-- email Modal -->
<div id="contactModal" class="modal fade" style="margin-top: 12%;" tabindex="-1" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content" style="height: 250px;">
<div class="modal-header" style="margin-bottom: 10px;">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title">Send A Test Email</h3>
</div>
<div class="modal-body" style="height: 65%;">
<form action="" method="post">
<label class="label-control" value="">Send test message to email address:</label>
<select name="emails" id="emails" value="" style="width: 400px; margin-top: 10px; margin-bottom: 18px; margin-left: 60px;">
<option selected="selected" value='title'>Title</option>";
</select><br>
<button name="send_email" id="send_email" type="submit" class="btn btn-primary" style="margin-left: 36%;" data-auto-id="<?php echo $autoid; ?>">Send Test</button>
</form>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(function() {
$('#send_email').click(function(e) {
$(this)
.html("<span><i class='fa fa-spinner fa-spin'></i> Sending...</span>")
.prop("disabled", true);
var ID = $(this).data('deleteid');
$.ajax({
type: 'POST',
url: "sendtest.php",
data: {ID : "deleteid"
},
success: function(resultData) {
alert(resultData)
$('#contactModal').modal('hide');
$("#send_email")
.html("Send Test")
.prop("disabled", false);
}
});
});
});
</script>
<?php
}
?>
Here is the sendtest.php:
<?php
// Initialize the session
session_start();
// Check if the user is logged in, if not then redirect him to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: login.php");
exit;
}
else if(isset($_POST))
{
$id = $_POST[$autoid];
echo "hello your id is...";
echo $id;
}
?>
What I want to achieve is when I click on a send a test hyperlink, a modal will display and when I click on a button after I select on a dropdown listbox, I want to fetch the ID from the Delete hyperlink so I can post them in ajax. The reasons I want to post the ID in ajax is because I want to stay on the same page while I want to fetch the information from the mysql database.
Can you please show me an example how I can fetch the ID from the Delete hyperlink to post them in ajax?
Thank you for understanding what I am trying to do.
There are several issues in your code:
1st: data: {ID : "deleteid"}, should be data: {ID : ID }, (you want to send the var, not the string "deleteid")
2nd: var ID = $(this).data('deleteid'); should be var ID = $(this).data('auto-id');, because the data-attribute is data-auto-id="...
3rd: $id = $_POST[$autoid]; will throw an error (undefined variable) & a notice (undefined index). Should be $id = $_POST['ID'], because you call the param "ID" here: data: {ID : varname},
4th: you are missing a ; here: alert(resultData)
Here's the corrected ajax-part:
var ID = $(this).data('auto-id');
$.ajax({
type: 'POST',
url: "sendtest.php",
data: {ID : ID },
success: function(resultData) {
alert(resultData);
$('#contactModal').modal('hide');
$("#send_email")
.html("Send Test")
.prop("disabled", false);
}
});

How to validate an input to see if it matches a record in the database

I am trying to create an input that queries the database and returns whether or not a result exists in the database. I have it partially working, but my box is glowing green whenever I only type in one letter. It would be better if it stayed red until it actually found a exact match and then turned green. Edit: I just realized there is also something wrong with my query. It is correctly querying the database now. The original issue is my main problem.
$(document).ready(function(){
$("#load").keyup(function (e){
e.preventDefault();
;
searchRequest = $.ajax({
url: 'check_load_no.php',
data: $('#load').serialize(),
type: 'POST',
success: function (data) {
$(".verify").css('box-shadow', '0px 0px 9px 2px #84f850');
$(".error").css('display', 'none');
$(".success").css('display', 'block');
},
error: function (data) {
$(".verify").css('box-shadow', '0px 0px 9px 2px #ad0037');
$(".success").css('display', 'none');
$(".error").css('display', 'block');
}
});
});
});
Below is my php
<?php include('../model/conn.php'); ?>
<?php include('../model/conn2.php') ?>
<?php
$sql = "SELECT cmt_2 FROM oeordhdr_sql WHERE cmt_2 = '{$_POST['load']}'";
$query = (odbc_exec($conn,$sql));
$row = (odbc_fetch_row($query));
if($row['cmt_2']){
echo 'yeah';
}
HTML
<h1>Please add the info based on your load number</h1>
<form action="" method="post">
<div class="card" >
<input class="verify" id="load" type="text" name="load" placeholder="Load Number" required/>
<span class="error" style="display: none;"><i class="fa fa-exclamation-triangle fa-lg" aria-hidden="true"> </i>I'm not finding anything</span>
<span class="success" style="display: none;"> <i class="fa fa-check-cube fa-lg" aria-hidden="true"> </i> Congratulations, that record exists!</span><br>
<button class="update_button" type="submit" name="add" value="update">Update</button></div></form>
Your error handler will not be called even if "yeah" is not echoed out by PHP script, as the server response would still be HTTP 200. For this reason, your success handler will always trigger (unless of course there is an actual problem with your server/application).
If you want to trigger the error handler, you would have to have the server send a 400 or 500 series HTTP response code (likely 404 in this case) for the case when no match is found.
Alternately, you could just put all your logic in the success handler and not change your server-side code at all. You would just have to test for the value of "yeah" being present or not.
You should also consider adding/removing CSS classes on your DOM elements rather than specifically specifying the CSS in your function. This would allow you to later change the CSS if needed, without having to alter this function.
success: function (data) {
if(data==="yeah")
{
$(".verify").css('box-shadow', '0px 0px 9px 2px #84f850');
$(".error").css('display', 'none');
$(".success").css('display', 'block');
}
else
{
$(".verify").css('box-shadow', '0px 0px 9px 2px #ad0037');
$(".success").css('display', 'none');
$(".error").css('display', 'block');
}
}
check if response is what you need and only then add .success class
Decided to output the error/success message using php instead of changing css
$("#load").keyup(function (e){
e.preventDefault();
searchRequest = $.ajax({
url: 'check_load_no.php',
data: $('#load').serialize(),
type: 'POST',
success: function (data) {
console.log(data);
if(data==="yeah")
{
$(".validate").html(data);
}
else
{
$(".validate").html(data);
}
}
});
});
My php
$sql = "SELECT cmt_2 FROM oeordhdr_sql WHERE cmt_2 LIKE '{$_POST['load']}'";
$query = odbc_exec($conn,$sql);
$row = (odbc_fetch_row($query));
if($row){
echo '<span class="success" style="display: block;"> <i class="fa fa-check-cube fa-lg" aria-hidden="true"> </i> Congratulations, that record exists!</span>';
}else{
echo'<span class="error" style="display: block;"><i class="fa fa-exclamation-triangle fa-lg" aria-hidden="true"> </i>I\'m not finding anything</span>';
}
My HTML
<h1>Please add the info based on your load number</h1>
<form action="" method="post">
<div class="card" >
<input class="verify" id="load" type="text" name="load" placeholder="Load Number" required/>
<div class="validate"></div><br>
<button class="update_button" type="submit" name="add" value="update">Update</button></div></form>

How to access a model method with javascript

Please have a look at the below CakePHP code
Flip2.php (Model)
<?php
class Flip2 extends AppModel {
var $name = 'Flip2';
public $useTable = false;
//Increment the correct_answer field of the specific user
public function correctAnswer($userID=89, $word)
{
$setQuery = "UPDATE `users_words` SET `correctanswer` = `correctanswer`+1 WHERE `userid`=$userID && `wordid`='$word' ";
query($setQuery);
}
}
Flip2Controller.php (Controller)
<?php
class Flip2Controller extends AppController {
public function index()
{
}
}
?>
index.ctp (View)
<?php
//echo $this->Html->css(array('bootstrap', 'mark', 'style'));
echo $this->Html->script(array('timer','swfobject','bootstrap.min.js'));
?>
<style>
#hideall {
display: none;
opacity: 0.7;
position: fixed;
height: 100%;
width: 100%;
top: 0;
left: 0;
background: #000;
border: 1px solid #cecece;
z-index: 1;
vertical-align:middle;
text-align:center;
}
.removeCardflip{
transition: rotateY(0deg);
-webkit-transition: rotateY(0deg);
transition-duration: 0s;
}
/* SECTIONS */
.section {
clear: both;
padding: 0 10px 0 10px;
margin: 0px;
}
</style>
<div id="hideall">
<?php //echo $this->Html->image('progress.gif', array('alt' => 'Wait', 'style' => 'text-align:center; padding-top:200px;'));?>
</div>
<!--<div class="wrapper" style="border: 1px solid red; width: 100%;">-->
<div class="section group" style="margin-top: 50px;">
<div class="col span_3_of_3">
<h3 style="margin:0px; font-size:22px;">Play word game: </h3>
</div>
</div>
<div class="">
<div>
<div>
<span class="remainWords"><?php //echo count($words);?></span> oxxxxxxxxxxxxxxxf <?php //echo $totalWords;?>
</div>
<div>
<?php
echo $this->Html->image("comic_edit.png",
array(
"alt" => "Pareto List",
"id" => "paretoList",
'url' => "javascript:;"
)
);
?>
</div>
</div>
</div>
<div class="container"><div class="row">
<?php
foreach($worddeck as $worcard)
{
?>
<div class="xy col-lg-3 col-md-4 col-sm-6 img-rounded" id="card1" style="width:250px; height:200px; background-color:grey; heiht:170px; margin: 10px 10px;">
<div id="enside1" >
<h1 data-pos="<?php //echo ; ?>" ><?php echo $worcard['unique_wordsforcards']['en_word']; $enSpell = $worcard['unique_wordsforcards']['en_word']; ?></h1>
</div>
<div id="ptside1" style="display:none;">
<?php echo $phonemer[$enSpell]; ?>
<p><?php echo $worcard['unique_wordsforcards']['hint']; ?></p>
</div>
<div id="cntrol1">
<button type="button" id="2" class="a btn btn-success mr5 btn-lg">Acertei</button>
<button type="button" id="2" class="e btn btn-danger mr5 btn-lg">Errei</button>
</div>
</div>
<?php
}
?>
</div></div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script type="text/javascript">
$(document).ready(function(){
$( ".btn-danger" ).click(function(){
console.log("Red Button");
var toclose = $(this).parent().parent();
$.ajax({
url: "../img/media.jpg",
}).done(function() {
console.log( "The act has been done");
toclose.toggle();
});
});
$( ".btn-success" ).click(function(){
console.log("Red Button");
var toclose = $(this).parent().parent();
$.ajax({
url: "../img/media.jpg",
}).done(function() {
console.log( "The act has been done");
toclose.toggle();
});
});
$( ".xy" ).click(function(){
$(this).find("#enside1").toggle();
$(this).find("#ptside1").toggle();
console.log(this);
});
});
</script>
Now, what I need to do is, this. When the user click on the Acertei button, I need to execute the function correctAnswer. I am very new to PHP and CakePHP so I am really confused about how to do this when a button is clicked. Any advice please?
You have
<div id="cntrol1">
<button type="button" id="2" class="a btn btn-success mr5 btn-lg">Acertei</button>
<button type="button" id="2" class="e btn btn-danger mr5 btn-lg">Errei</button>
</div>
You should use different IDs for each button.
You can call the correctAnswer function with ajax:
Change the button to something like
<button type="button" id="2" data-word="<?php $worcard['unique_wordsforcards']['en_word'] ?>" class="a btn btn-success mr5 btn-lg">Acertei</button>
And then add the following code in $(document).ready()
$(document).ready(function(){
$(".btn-success").click(function(){
var word = $(this).data('word');
$.post('/flip2/correct.json', { word: word })
.done(function(data) {
alert('Saved');
});
I am not sure how the user part works. You should probably have that in the session, and not sent to the function. I hardcoded user 89 and added a way for you to send the word.
Use an appropriate model method
The function correctAnswer in the model would better be written using updateAll:
public function correctAnswer($userId, $word) {
return $this->updateAll(
array('correctanswer' => 'correctanswer + 1'),
array(
'userid' => $userId,
'wordid' => $word
)
);
}
Written in this way the inputs ($userId and $word) will be escaped appropriately and not susceptible to sql injection.
Create a controller action
The doorway to the web for an application is a controller action, create a simple function, calling the model method, and write it to output json:
public function correct() {
$postData = $this->request->data;
$word = $this->request->data['word'];
$userId = $this->Auth->user('id');
$result = false;
if ($userId && $word) {
$result = $this->Flip2->correctAnswer($userId, $word);
}
$this->set('_serialize', array('result'));
$this->set('result', $result);
}
Note that
It'll only work via a post request.
The Auth component (the session) is used to get the current user id, it's not a user-defined input.
This function is defined such that it'll work as a json response.
There's no need to create a view file with the above code.
Be sure to setup your app to handle json requests:
After adding Router::parseExtensions('json'); to your routes file, CakePHP will automatically switch view classes when a request is done with the .json extension, or the Accept header is application/json.
Call the controller action
The required js would be of the form:
$(".btn-success").click(function(){
var word = ...;
$.post(
'/flip2/correct.json',
{word: word},
function (data) {
console.log(data);
// {result: bool}
}
);
});
Note that:
The url ends in .json which is a simple and robust way to provoke CakePHP to respond as json.
It is a post request.
The response will be of the form defined by _serializein the controller action.

set view parameters from another action

so im my zend framework aplication and im trying to set the view sucess var to true in order to show a sucess messega.
so in my choosetags.phtml ive got this
<script language = "Javascript">
$(document).ready(function() {
$("#button").click(function () {
var param1 = 'first'; //or get value from some DOM element
var param2 = 'second'; //or get value from some DOM element
$.ajax({
url: '/rondas/saveronda',
type: 'POST',
data: {param1: param1, param2:param2 },
datatype: "json"
});
});
});
</script>
<?php if($this->success): ?>
<div class="albox succesbox" style="z-index: 690;">
<b>Sucesso :</b> A Palavra-passe foi alterada com sucesso.
</div>
<?php endif; ?>
<?php if($this->hasError): ?>
<div class="albox errorbox" style="z-index: 690;">
<b>Erro :</b> <?php echo $this->errorMessage; ?>
</div>
<?php endif; ?>
<div class="simplebox grid740" style="z-index: 500;">
<div class="titleh" style="z-index: 400;">
<h3>Criar Ronda</h3>
</div>
<div class="body" style="z-index: 380;">
<script type="text/javascript">
var t=0;
$(function(){
$("#toolbar").jqGrid({
caption:"Tags",
colNames:['ID','Nome','Cliente','Descrição','Modo','Estado'],
colModel:[
{name:'id_tag',index:'id_tag',hidden:true},
{name:'tag_nome',index:'tag_nome'},
{name:'nome',index:'nome'},
{name:'descricao',index:'descricao'},
{name:'modo',index:'modo'},
{name:'estado',index:'estado'}
],
datatype:"json",
height:421,
rownumWidth:40,
pager:'#ptoolbar',
rowList:[10,20,30],
rowNum:10,
sortname:'id_tag',
sortorder:'desc',
viewrecords:true,
width:700
});
$("#toolbar").jqGrid('navGrid','#ptoolbar',{del:false,add:false,edit:false,search:false});
$("#toolbar2").jqGrid({
caption:"Tags da Ronda",
colNames:['ID','Nome','Cliente','Descrição','Modo','Estado'],
colModel:[
{name:'id_tag',index:'id_tag',hidden:true},
{name:'tag_nome',index:'tag_nome'},
{name:'nome',index:'nome'},
{name:'descricao',index:'descricao'},
{name:'modo',index:'modo'},
{name:'estado',index:'estado'}
],
datatype:"json",
height:421,
rownumWidth:40,
pager:'#ptoolbar2',
rowList:[10,20,30],
rowNum:10,
sortname:'id_tag',
sortorder:'desc',
viewrecords:true,
width:700
});
$("#toolbar2").jqGrid('navGrid','#ptoolbar2',{del:false,add:false,edit:false,search:false});
$("#toolbar").jqGrid('gridDnD',{connectWith:'#toolbar2',dragcopy:true,beforedrop: function (ev, ui, getdata, $source, $target) {
var names = $target.jqGrid('getCol', 'id_tag');
if ($.inArray(getdata.id_tag, names) >= 0) {
// prevent data for dropping
ui.helper.dropped = false;
alert("A tag ja existe na ronda");
}
else
{
document.getElementById("tagini").innerHTML= document.getElementById("tagini").innerHTML +"<option value="+getdata.id_tag+">"+getdata.tag_nome+','+getdata.nome+','+getdata.descricao+','+getdata.modo+"</option>";
document.getElementById("tagfim").innerHTML= document.getElementById("tagfim").innerHTML +"<option value="+getdata.id_tag+">"+getdata.tag_nome+','+getdata.nome+','+getdata.descricao+','+getdata.modo+"</option>"; }}});
});
$(function(){
// Attach the dynatree widget to an existing <div id="tree"> element
// and pass the tree options as an argument to the dynatree() function:
$("#tree").dynatree({
initAjax: {
url: "/locais/tree"
},
onActivate: function(node) {
t=node.data.key;
if(t!=0)
{
$("#echoActive").text(node.data.title);
$("#tables").show();
$("#toolbar").jqGrid('setGridParam',{url:"/rondas/choosetags/id/"+t}).trigger("reloadGrid");
reloadGrid();
}
else
{
$("#echoActive").text("-");
$("#tables").hide();
}
}
});
});
</script>
<div class="st-form-line" style="z-index: 680;">
<span class="st-labeltext">Escolher a localização:</span>
<div id="tree" > </div>
<div class="clear" style="z-index: 670;"></div>
</div>
<!-- Add a <div> element where the tree should appear: -->
<div class="st-form-line" style="z-index: 680;">
<span class="st-labeltext">Localização:<span id="echoActive">-</span></span>
<div id="tables" style="display:none" >
<table id="toolbar"></table>
<div id="ptoolbar"></div>
</div>
<div class="clear" style="z-index: 670;"></div>
</div>
<div class="st-form-line" style="z-index: 680;">
<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>
</div>
</div>
so the user choose when the user press submit data it makes an ajax call to /rondas/saveronda, in this action i will save the data on the database, and once it succeds i want to redirect to the /rondas/chooserondas and show a sucess message, how can i achieve this..
so here is the code for the /rondas/saveronda
public function saverondaAction()
{
// action body
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
if($this->_request->isXmlHttpRequest())
{
$param1 = $this->_request->getParam('param1');
$param2 = $this->_request->getParam('param2');
//save data on the db and return to the /rondas/choosetags and display sucess message.
}
}
and here is the code for the /rondas/choosetags
public function choosetagsAction()
{
// action body
if($this->_request->isXmlHttpRequest())
{
$request= $this->getRequest();
$poll_id = $request->getParam('id');
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
Zend_Paginator::setDefaultScrollingStyle('Sliding');
$page = $this->_getParam('page', 1);
$limit = $this->_getParam('rows', 0);
$sidx = $this->_getParam('sidx', 1);
$sord = $this->_getParam('sord', 0);
$totalrows = $this->_getParam('totalrows', false);
if($totalrows)
$limit = $totalrows;
$tableModel = new Application_Model_Tags();
$select = $tableModel->select();
$select->setIntegrityCheck(false);
$select->from('tags', array('id_tag','tag_nome', 'id_software', 'id_hardware','id_localizacao','descricao','modo','estado'))->joinInner('clientes', 'tags.id_cliente = clientes.id_cliente', array('nome'))->where('id_localizacao='.$poll_id);
$filters = !empty($_REQUEST['filters']) ? (array) json_decode($_REQUEST['filters']) : array();
$adapter = new Zend_Paginator_Adapter_DbTableSelect($select);
$paginator = new Zend_Paginator($adapter);
$paginator->setCurrentPageNumber($page)->setItemCountPerPage($limit);
$count = $paginator->getTotalItemCount();
$total_pages = $count > 0 ? ceil($count / $limit) : 1;
$responce = new stdClass();
$responce->page = $page > $total_pages ? $total_pages : $page;
$responce->total = $total_pages;
$responce->records = $count;
$i = 0;
foreach($paginator as $item)
{
$responce->rows[$i]['id'] = $item['id_tag'];
$responce->rows[$i]['cell'] = array($item['id_tag'],$item['tag_nome'],$item['nome'],$item['descricao'],$item['modo'],$item['estado']);
$i++;
}
echo json_encode($responce);
} else
{
$this->_helper->layout()->pageTitle = 'Rondas';
$this->_helper->layout()->pageDescription = 'Criar as rondas';
}
}
i can show the message if i am on the same action and view , i mean , in the /rondas/choosetags if i put this $this->view->sucess=true, the success message apperas, but i want to set the success var to true in action /rondas/saveronda and then redirect to the action /rondas/choose tags and show success message.
You can't directly. What you can do is save the params you want to set in a temporary session (with a expiration of, for example, 1 hop = 1 successful request):
$hopSession = new Zend_Session_Namespace('tempViewParams');
$hopSession->my_view_param1 = 'string with data';
$hopSession->setExpirationHops(1);
You can than get the values from your temporary session in the next action.
Another way is to add the view values you want to set as params in the url you're redirecting to on a successful save (especially in this case where all you want is a true param). So an url like:
/rondas/choosetags/sucess/1
So you can add something to your choosetagsAction() like:
if(1 == $request->getParam('success'))( {
$this->view->success = true;
}
Of course in case you want to pass through multiple params the SESSION solution would be the most beautiful.

Categories