How to pass two data to Controller using Script? - javascript

I have script like this:
delete_event: function() {
if (this.id != 0) {
var url = base_url + "event/delete_event_data/" + this.id + this.event_id;
location.href = url;
}
else {
alert('Please Select Event');
}
},
I want to pass id and event id to following controller:
public function delete_event_data($id,$event_id) {
$result = $this->event_model->delete_event_data($id);
if ($result == TRUE) {
$this->session->set_flashdata('success-msg', ' Event Data Successfully Deleted. ');
redirect('event');
} else {
$this->session->set_flashdata('failure-msg', ' ERROR! Something went Wrong. ');
redirect('event');
}
}
I have done above but it doesn't work..
Please guide me..

Related

How can I conditionally allow or prevent submission execution?

The situation
I have a page in which I have multiple forms keeping track of the attendance and one progress_update.
On submit of the progress_update form I have got it so that ajax sends the attendance form submissions separately having used the preventdefault() method to stop the original submission, however I would like to on the condition that no errors were returned by the ajax methods allow the original submission that was originally prevented.
What I have so far:
The ajax function:
function send_attendance(name, lesson, form_id, i) {
var url = '/attendance/' + name + '/' + lesson
$('#error-' + i).hide('slow')
$('#error-' + i).html('')
$.ajax({
type: "POST",
url: url,
data: {
attended: $('#attended' + i).val(),
score: $('#score' + i).val(),
writing: $('#writing' + i).val(),
speaking: $('#speaking' + i).val()},
success: function(data) {
if (data.data.message == undefined) {
allow=false;
if (data.data.score[1] == undefined) {
var error_data = data.data.score[0]
} else {
var error_data = data.data.score[1]
}
$('#error-' + i).show('slow')
$('#error-' + i).html('<p style="color:red;">' + error_data + '</p>')
} else {
console.log(data.data.message) // display the returned data in the console.
}
}
});
}
The Intention:
The intention behind this ajax is to send the forms to a separate route for validation and then on success "receiving data.data.message == 'submitted'" pass to the next form in the loop, while on error set the allow variable to false and display the message in hopes to prevent the final form being submitted at the same time.
The call:
$('#update_form').submit(function (e) {
var allow = true;
for (var i = 0; i < studentcount ; i++) {
send_attendance(name=st[i], lesson=lesson, form_id='attendance-' + i, i=i)
}
if (allow == true){
} else {
e.preventDefault();
}
});
The Problem
In doing what I have done I have ended up with a situation of it either submits the ajax submitted forms and that is that preventing the submit form or it submits the form whether errors occured in the ajax that need to be displayed, now how do I get this to work in the way expected? I have tried the methods involved in these previous questions:
How to reenable event.preventDefault?
How to unbind a listener that is calling event.preventDefault() (using jQuery)?
which revolve around using bind and unbind but this doesn't seem to work as needed and results in a similar error.
Any advice would be greatly appreciated.
Edit:
I have adjusted the code based on the comment below to reflect, however it still seems to be evaluating the allow before the ajax have completed. either that or the ajax function isn't changing the allow variable which is set in the submit() call how could i get this to change the allow and evaluate it after the ajax calls are complete?
The Ajax call
function send_attendance(name, lesson, form_id, i) {
var url = '/attendance/' + name + '/' + lesson
$('#error-' + i).hide('slow')
$('#error-' + i).html('')
var form = $('#' + form_id)
$.ajax({
type: "POST",
url: url,
data: $('#'+ form_id).serialize(),
context: form,
success: function(data) {
console.log('done')
if (data.data.message == undefined) {
allow = false;
if (data.data.score[1] == undefined) {
var error_data = data.data.score[0]
} else {
var error_data = data.data.score[1]
}
$('#error-' + i).show('slow')
$('#error-' + i).html('<p style="color:red;">' + error_data + '</p>')
} else {
console.log(data.data.message) // display the returned data in the console.
}
}
});
The function is being called here:
$('#update_form').submit(function (e) {
e.preventDefault();
var allow = true;
var deferreds = [];
for (var i = 0; i < studentcount ; i++) {
deferreds.push(
send_attendance(st[i], lesson, 'attendance-' + i, i));
}
$.when(...deferreds).then(function() {
if (allow == true){
console.log('True')
} else {
console.log('False')
}
});
I also tried:
$('#update_form').submit(function (e) {
e.preventDefault();
var allow = true;
var deferreds = [];
for (var i = 0; i < studentcount ; i++) {
deferreds.push(
send_attendance(st[i], lesson, 'attendance-' + i, i));
}
$.when.apply(deferreds).done(function() {
if (allow == true){
console.log('True')
} else {
console.log('False')
}
});

Prevent sending data to DB/server if form validation is false (VueJS)

I want to stop sending information if form validation is false.
I have a button Save with two functions in it:
<span class="logInBTN" v-on:click="validationFields(); function2(model)">Save</span>
The form validation is being proccessed in validationFields():
validationFields() {
if (this.model.codePerson == '') {
document.getElementById('codePerson').style.borderColor = "red";
this.errors.push("Choose a type!\n");
falseValidation = true;
} else {
document.getElementById('codePerson').style.borderColor = "#CCCCCC";
}
if (falseValidation == true) {
alert("Form validation:\n" + this.errors.join(""));
}
}
So if it's not chosen a type from the input field, function2() must not continue.
Update1:
<script>
export default {
components: {
},
data(){
return {
errors: [];
},
},
methods: {
validationFields() {
this.errors = [];
var falseValidation = false;
if (this.model.codePerson == '') {
document.getElementById('codePerson').style.borderColor = "red";
this.errors.push("Choose a type!\n");
falseValidation = true;
} else {
document.getElementById('codePerson').style.borderColor = "#CCCCCC";
}
if (falseValidation == true) {
alert("Form validation:\n" + this.errors.join(""));
}
if(falseValidation == false){
this.createEori(eoriData);
}
}
createEori(eoriData) {
eoriData.state = '1';
eoriData.username = this.$session.get('username');
console.log("updateEori state: " + JSON.stringify(eoriData));
const url = this.$session.get('apiUrl') + 'registerEORI';
this.submit('post',
url,
eoriData
);
},
submit(requestType, url, submitData) {
this.$http[requestType](url, submitData)
.then(response => {
console.log('EORI saved!');
console.log('Response:' + response.data.type);
if("E" == response.data.type){
alert(response.data.errorDescription);
} else {
alert("Saved!");
}
})
.catch(error => {
console.log('EORI rejected!');
console.log('error:' + error);
});
},
},
}
</script>
createEORI is the function2
Update2
Now it works, but the data from the fields it's not send to the server. That's all fields from the page, some are datepickers or an ordinary input text field. Before the change in the browser console show this, if I write a name in the first field it will show up in c1_name etc:
{"state":"1","c1_form":"","c1_identNumber":"","c1_name":"","c1_shortName":"","c1_8_street":"","c1_8_pk":"","c1_8_name":"","c1_8_city":"","c1_8_codeCountry":"","c1_identNumber1":"","c3_name":"","c3_nameShort":"","c3_city":"","c3_codeCountry":"","c3_street":"","c3_pk":"","c3_phone":"","codePerson":"","codeActivity":"","c1_date":"","c5_date":"","c7_date":"","dateFrom":"","dateTo":"","c8_date":"","c1_numberVAT":"","c8_provider":"","c8_number":"","codeMU":"","agreed1":"","agreed2":"","username":"testuser"}
However, after the change the sent data or at least the seen data is only:
{"state":"1","username":"testuser"}
The log is from
console.log("updateEori state: " + JSON.stringify(eoriData));
from createEORI() function
I think it would be better practice to only call one function from the HTML. Something like this:
<span class="logInBTN" v-on:click="submit(model)">Save</span>
submit(model) {
if (this.validateForm(model) == true)
{
// submission process here (maybe call function2())
}
}
validateForm(model) {
if (this.model.codePerson == ''){
document.getElementById('codePerson').style.borderColor = "red";
this.errors.push("Choose a type!\n");
this.handleFalseValidation();
return false;
}
document.getElementById('codePerson').style.borderColor = "#CCCCCC";
return true;
}
handleFalseValidation() {
alert("Form validation:\n" + this.errors.join(""));
}
Ok I fixed the problems with sending the data.
It was my fault.
I will copy the Chris answer. That worked.
When you call this.createEori(eoriData);, eoriData is undefined. It doesn't exist. Use this.createEori(); instead, and in the createEori function, remove the parameter and add var eoriData = {}; as first line. (note this is very basic javascript, how functions and variables work, and completely unrelated to Vue or server requests)

Get specific section of AJAX response

When i inspect the response from my AJAX request to index.php, I get back some data that i want (some json, a return value i need the value of) but also a load of HTML as the index.php class is used to call a view which is responsible for loading up some HTML.
Here is the first two lines of the response:
{"returnVal":"registered"}<!DOCTYPE html>
<html lang="en">
Due to my code being MVC, i cannot just create a separate file to handle the AJAX request, so i need a way for my login.js class (where the AJAX request is generated) to go through the whole response and find the value of "returnVal" that I need. Do you know of a way I can do this?
Login.js
var loginData, urlPath;
// Allow users to log in or register
function Login() {
if(!document.getElementById("usernameField")) { // If we have no username field on this page, we are just logging in
loginData = "email=" + $("#emailField").val() + "&password=" + $("#passwordField").val() + "&action=" + "loggingIn";
urlPath = "index.php";
} else { // we are registering
loginData = "username=" + $("#usernameField").val() + "&email=" + $("#emailField").val() + "&password=" + $("#passwordField").val() + "&action=" + "register";
urlPath = "../index.php";
}
// Send the login/registration data to database
$(document).ready(function() {
$.ajax({
type: "POST",
url: urlPath,
data: loginData,
success: function (result) {
alert(result); // i need to get the value of 'returnVal' from the response
if(result.returnVal=="registered") {
document.getElementById('notification').innerHTML = "You have been registered";
} else if (result.returnVal=="username") {
document.getElementById('notification').innerHTML = "Username already taken";
} else if (result.returnVal=="email") {
document.getElementById('notification').innerHTML = "Email already taken";
} else if (result.returnVal=="notRegistered") {
document.getElementById('notification').innerHTML = "Please enter registered email";
} else if (result.returnVal=="loginFail") {
document.getElementById('notification').innerHTML = "Please enter correct password";
} else if (result.returnVal=="loggedIn") {
$('#myModal').modal('hide');
document.getElementById('loginButton').innerHTML = "Account Settings";
} else { // Something wrong, tell us
//alert(result);
}
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
})
})
}
index.php
<?php
ini_set("log_errors", 1);
require_once("Model/model.php");
require_once("Controller/controller.php");
require_once("View/view.php");
$model = new Model();
$view = new View();
$controller = new Controller($model, $view);
if(isset($_POST['action'])) {
if($_POST['action'] == "register") {
$controller->Register($_POST['username'], $_POST['email'], $_POST['password']);
echo json_encode($controller->GetReturned());
}
}
$view->Begin();
?>
Ultra simple way is just exit() after you echo the json so the view never gets sent. If this controller is never intended to render a view get rid of $view->Begin();
if(isset($_POST['action'])) {
if($_POST['action'] == "register") {
$controller->Register($_POST['username'], $_POST['email'], $_POST['password']);
echo json_encode($controller->GetReturned());
exit();
}
}
This is a (messy but still) way to extract the data you need.
But please consider my first comment. You should do it the other way round.
var result = '{"returnVal":"registered"}<!DOCTYPE html>someother grap';
var n = result.indexOf("<!DOCTYPE");
var jsonString = input.substring(0, n);
var json = JSON.parse(jsonString);
console.log(json);
// your values are here:
// json.returnVal;
This relies on the strict convention, that every return has a '

Trigger a php script using ajax - how and where to program this?

Good day,
I have a php file (db.php) which contains the following function
function edit_record($id, $value){
if($this->db->query('UPDATE tbl_prototype SET value = ' . $value .' WHERE id_component = '.$id)){
$this->register_changes();
return TRUE;
}
return FALSE;
}
Besides, I have some checkboxes in my html page as follows :
<input id="chk01" type="checkbox" data-onstyle="success" data-toggle="toggle">
<input id="chk02" type="checkbox" data-onstyle="success" data-toggle="toggle">
the html page contains also the following script.
<script>
/* AJAX request to checker */
function check(){
$.ajax({
type: 'POST',
url: 'checker.php',
dataType: 'json',
data: {
counter:$('#message-list').data('counter')
}
}).done(function( response ) {
/* check if with response we got a new update */
if(response.update==true){
var j = response.news;
$('#message-list').html(response.news);
sayHello(j);
}
});
};
//Every 1/2 sec check if there is new update
setInterval(check,500);
</script>
<script>
function sayHello(j){
var json=$.parseJSON(j);
var techname = "";
var techname1 = "";
var c;
var w;
$(json).each(function(i,val){
$.each(val,function(k,v){
if (k=="tech_name")
{
techname = "#" + v;
techname1 = v;
}
else
{
console.log("Mon nom est " + techname + " et ma valeur est " + v);
c=document.getElementById(techname1);
if (c.checked)
{
w = 1;
}
else
{
w = 0;
}
console.log(w);
console.log("techname : " + techname1);
if (v != w)
{
console.log ("Pas identique");
if (v==0)
{
// false
uncheckBox(techname);
}
else
{
// true
checkBox(techname);
}
}
else
{
console.log ("Identique");
}
}
});
});
}
function checkBox(pCtrl)
{
toggleOn(pCtrl);
}
function uncheckBox(pCtrl)
{
toggleOff(pCtrl);
}
</script>
Now for my question: where and how should I specify that I would like to run the function 'edit_record' stored in the 'db.php' file with the two parameters ($id and $value).
Contents of 'checker.php' :
<?php require('common.php');
//get current counter
$data['current'] = (int)$db->check_changes();
//set initial value of update to false
$data['update'] = false;
//check if it's ajax call with POST containing current (for user) counter;
//and check if that counter is diffrent from the one in database
//if(isset($_POST) && !empty($_POST['counter']) && (int)$_POST['counter']!=$data['current']){
if(isset($_POST)){
$data['news'] = $db->get_news2();
$data['update'] = true;
}
//just echo as JSON
echo json_encode($data);
/* End of file checker.php */
Thanks a lot for your valuable inputs. Sorry if the question sounds silly (I'm a newbie in php/ajax/jquery programming).
In modern web apps with rich interface You should go for REST API and create controller which should be in You case in checker.php. Example ( checker.php ):
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
//update code
edit_record($_POST['id'],$_POST['counter]);
}
if ($_SERVER['REQUEST_METHOD'] == 'GET'){
//get code
}
ps. i do not see passing id in ajax, you send only counter, so you should add id like:
...
data: {
id:yourId //here your id
counter:$('#message-list').data('counter')
}
Next thing remove from js:
setInterval(check,500);
and create bind:
$("yourcheckboxselector").on("click",function(e){
check($(this).prop("checked") ) //here you have it was checked or not as boolean
});

Working with Laravel and AJAX - Not loading DIV

I'm really puzzled by this. I have no errors in apache logs or in my browser (chrome).
I can visit this particular page (localhost/admin/networks) and click on an item from a database generated list. When clicked the item will open a css popup div that I can add a database entry with. This portion works fine. However, I also have a live search box so you can type in a partial network to see the results. When you click on one of the results though it will bring up the css popup, but it will be empty like its failing to find the file - even though it works just fine pre-search. I had this working at one point, but I added a route prefix and I think my issue lies between my JS file and my route prefixes. I honestly have no idea where to begin checking though as it works until searched.
Also, feel free to criticize. I'm still learning so if I'm doing something in a terrible way feel free to let me know. Any help is appreciated!
Edit 2:
I've narrowed it down to the third argument on the .load of my javascript file. I added my route prefixes back in and below is my current js file.
current js.js file
var baseURL = "https://localhost/";
var admURL = "https://localhost/admin/";
//DIV View Toggle
function toggle(div_id)
{
var el = document.getElementById(div_id);
if(el.style.display == 'none')
{
el.style.display = 'block';
}
else
{
el.style.display = 'none';
}
}
function togglePopBox(windowname)
{
toggle('popBox');
toggle('popBackground');
}
$(document).ready(function()
{
//Add Networks Button
$("#addNet").on('click', function()
{
$("#popBox").load(admURL + 'addnetwork', setupInternalPopBoxNetworks);
});
//Kills popup
function setupInternalPopBoxNetworks()
{
$("#cancelNet").on('click', function()
{
$("#popBox").load(baseURL + 'blank', setupInternalPopBoxNetworks);
});
}
//Network Search Function
$('#searchNetworkID').keyup(function(e){
$("#networkBox").load(baseURL + 'network.search' + '?networkSearch=' + $('#searchNetworkID').val());
});
//Add Subnets Button
$(".addSubnet").on('click', function()
{
var netID = $(this).attr('id');
$("#popBox").load(admURL + 'addsubnet' + '?network=' + netID, setupInternalPopBoxNetworks);
});
//View Subnets Button
$(".viewSubnet").on('click', function()
{
var netID = $(this).attr('id');
$("#subnetBox").load(baseURL + 'viewsubnet' + '?network=' + netID, setupInternalPopBoxNetworks);
});
//Subnet Search
$('#searchSubnetID').keyup(function(e){
$("#subnetBox").load(baseURL + 'subnet.search' + '?subnetSearch=' + $('#searchSubnetID').val());
});
});
Edit 1:
I removed the route group I defined with the same issue. I reverted
back before I had created another popUp DIV on the suspicion that
maybe I had created a conflict somewhere. I'm not real sure what it
is, but after playing around some more I think there is an issue in my
js.js file.
I am pretty sure the issue I'm running into has to do with async since
I'm using http://api.jquery.com/load/. I changed my subnets button to
the code below and would get a loaded popup, but it would just be the
one it loaded previously because the div would not blank out when
closed.
I feel I'm getting close, but obviously still missing something major.
$(".addSubnet").on('click', function()
{
var netID = $(this).attr('id');
$("#popBox").load(baseURL + 'addsubnet' + '?network=' + netID);
});
routes.php
#Route Prefix for administration
Route::group(array('prefix' => 'admin', 'before' => 'auth'), function()
{
#Network Management Page - Add, Edit, Delete
Route::get('networks', function()
{
$userGroups = implode(',', Auth::user()->groups);
$userGroups = ''.$userGroups.'';
$userGroups = explode(",", $userGroups);
$CanIVisit = Link::whereIn('linkGroup', $userGroups)->count();
if($CanIVisit > 0){
return View::make('networks');
}else{
return Redirect::intended('landing');
}
});
#Adds a Network
Route::get('addnetwork', array(
'as' => 'network.add',
'uses' => 'NetworksController#add'
));
#POSTS added network data
Route::post('networks', array('before' => 'csrf',
'as' => 'network.create',
'uses' => 'NetworksController#create'
));
#Adds subnet to specified network
Route::get('addsubnet', array(
'as' => 'subnet.add',
'uses' => 'NetworksController#addSubnet'
));
#POSTS subnet information to database
Route::post('subnets', array('before' => 'csrf',
'as' => 'subnet.create',
'uses' => 'NetworksController#createSubnet'
));
});
NetworksController.php
public function search()
{
$lineNumber = 1;
$network = Input::get('networkSearch');
$networks = IPv4Network::where('easyNet', 'LIKE', "$network%")
->orWhere('route', 'LIKE', "$network%")
->orderBy('network', 'asc')
->get();
$networksCount = IPv4Network::where('easyNet', 'LIKE', "$network%")
->orWhere('route', 'LIKE', "$network%")
->orderBy('network', 'asc')
->count();
if($networksCount == 0){
echo("No networks matched the criteria entered.");
}else{
echo("<div id=\"networkListHead\">");
echo("<div class=\"networkID\">Network</div>");
echo("<div class=\"networkMask\">Mask</div>");
echo("<div class=\"networkPath\">Route Path</div>");
echo("<div class=\"networkSubnets\">Subnets</div>");
echo("<div class=\"networkHosts\">Hosts</div>");
echo("<div class=\"networkMaxHosts\">Max Hosts</div>");
echo("</div>");
foreach($networks as $foundNet){
$findSubnets = IPv4Subnets::where('networkID', '=', $foundNet->networkID)
->get();
$findSubnetsCount = IPv4Subnets::where('networkID', '=', $foundNet->networkID)
->count();
$mask = (32 - $foundNet->mask);
$MaxHosts = (pow(2, $mask) - 2);
if($lineNumber == 1){
echo("<div class=\"networkListA\">");
echo("<div class=\"networkID\">".long2ip($foundNet->network)."</div>");
echo("<div class=\"networkMask\">{$foundNet->mask}</div>");
echo("<div class=\"networkPath\">{$foundNet->route}</div>");
echo("<div class=\"networkSubnets\">{$findSubnetsCount}</div>");
echo("<div class=\"networkHosts\">");
if($findSubnetsCount == 0){
echo("0");
}else{
$hostCount = IPv4Hosts::all()
->count();
if($hostCount == 0){
echo("0");
}else{
echo $hostCount;
}
}
echo("</div>");
echo("<div class=\"networkMaxHosts\">");
echo $MaxHosts;
echo("</div>");
echo("</div>");
$lineNumber = 2;
}else{
echo("<div class=\"networkListB\">");
echo("<div class=\"networkID\">".long2ip($foundNet->network)."</div>");
echo("<div class=\"networkMask\">{$foundNet->mask}</div>");
echo("<div class=\"networkPath\">{$foundNet->route}</div>");
echo("<div class=\"networkSubnets\">{$findSubnetsCount}</div>");
echo("<div class=\"networkHosts\">");
if($findSubnetsCount == 0){
echo("0");
}else{
$hostCount = IPv4Hosts::all()
->count();
if($hostCount == 0){
echo("0");
}else{
echo $hostCount;
}
}
echo("</div>");
echo("<div class=\"networkMaxHosts\">");
echo $MaxHosts;
echo("</div>");
echo("</div>");
$lineNumber = 1;
}
}
}
}
js.js
var baseURL = "https://localhost/";
var admURL = "https://localhost/admin/";
//DIV View Toggle
function toggle(div_id)
{
var el = document.getElementById(div_id);
if(el.style.display == 'none')
{
el.style.display = 'block';
}
else
{
el.style.display = 'none';
}
}
function togglePopBox(windowname)
{
toggle('popBox');
toggle('popBackground');
}
$(document).ready(function()
{
//Add Subnets Button
$(".addSubnet").on('click', function()
{
var netID = $(this).attr('id');
$("#popBox").load(admURL + 'addsubnet' + '?network=' + netID, setupInternalPopBoxNetworks);
});
//Kills popup
function setupInternalPopBoxNetworks()
{
$("#cancelNet").on('click', function()
{
$("#popBox").load(baseURL + 'blank', setupInternalPopBoxNetworks);
});
}
//Network Search Function
$('#searchNetworkID').keyup(function(e){
$("#networkBox").load(baseURL + 'network.search' + '?networkSearch=' + $('#searchNetworkID').val());
});
});
I got it figured out. I thought I was binding to a static element, but I ended up binding to an element a bit higher up in my page structure - that coupled with some modifications to my js.js file I resolved the issue. Here's what my working js file looks like.
js.js
var baseURL = "https://localhost/";
var admURL = "https://localhost/admin/";
//DIV View Toggle
function toggle(div_id)
{
var el = document.getElementById(div_id);
if(el.style.display == 'none')
{
el.style.display = 'block';
}
else
{
el.style.display = 'none';
}
}
function togglePopBox(windowname)
{
toggle('popBox');
toggle('popBackground');
}
$(document).ready(function()
{
//Add Networks Button
$("#addNet").on('click', function()
{
$("#popBox").load(admURL + 'addnetwork', togglePopBox);
});
//Kills popup
$("#popBox").on('click', '#cancelNet', function()
{
$("#popBox").load(baseURL + 'blank', togglePopBox);
});
//Network Search Function
$('#superDuperBox').on('keyup', '#searchNetworkID', function(){
$("#networkBox").load(baseURL + 'network.search' + '?networkSearch=' + $('#searchNetworkID').val(), null, null);
});
//Add Subnets Button
$('#superDuperBox').on('click', '.addSubnet', function()
{
var netID = $(this).attr('id');
$("#popBox").load(admURL + 'addsubnet' + '?network=' + netID, togglePopBox);
});
//View Subnets Button
$('#superDuperBox').on('click', '.viewSubnet', function()
{
var netID = $(this).attr('id');
$("#subnetBox").load(baseURL + 'viewsubnet' + '?network=' + netID);
});
//Subnet Search
$('#superDuperBox').on('keyup', '#searchSubnetID',function(){
$("#subnetBox").load(baseURL + 'subnet.search' + '?subnetSearch=' + $('#searchSubnetID').val());
});
});

Categories