How to delete using javascript in codeigniter? - javascript

Need a little help in here. I just want to delete a row from database using javascript. But facing some problems.
Here is my view:
<?php echo anchor("#","Delete",array('class'=>'selectedpagination', 'onclick'=>'confirmDelete("admin/editpage/","'.$file->page_id.'");'))?>
And Javascript is here
function confirmDelete(controller,id)
{
if(confirm("Are you sure you want to delete this record"))
{
<!--location.href="main.php?page="+page+"&tblname="+tblname+"&fldname="+fldname+"&id="+id+"&action=delete";-->
window.redirect("http://localhost/sama/index.php/admin/"+controller+"/"+id);
}
How to make it work?? Its not working.
Please anyone or someone, desperately needing help. Thanks in advance.

You might want to consider using jQuery's shorthand AJAX function $.post() to post data to the page you need like so:
function confirmDelete(controller, id){
if(confirm("Are you sure you want to delete this record")){
var data = "page="+page+"&tblname="+tblname+
"&fldname="+fldname+"&id="+id+"&action=delete";
$.post(controller, data)
.done(function(data) {
// redirect or further logic here
});
}
}
Server-side you receive each of your posted variables like:
$action = $this->input->post('action');
Besides the above solution, you may want to rethink your approach to this. You are sending data to a controller through javascript and then you redirect the browser to another page using javascript throughout the process. It may have been easier to just call the controller and pass the variables you need by the session cookie or through the url and when everything is done server-side, use codeigniter's redirect() helper function to redirect the browser to where you want. The use of javascript and AJAX here would be fine if you wanted to build an asynchronous application... but... ajax call and redirection rather blow the purpose of asynchronous calls. Hope I helped a bit.

Related

Ajax call. Passing value to another php file

I have a problem and hope you can help.
Ii have a status.PHP file containing a js.
STATUS.PHP
<? ..stuff... ?>
<html>
<head>
<title>BCM Status Page</title>
<script src="jquery-3.3.1.min.js"></script>
<script src="updater.js"></script>
</head>
<body bgcolor="#305c57" onload='init();'>
As you can see in the html ihave included a JS, during "onload" i'm calling the init() function of the javascript called updater.js
Now in the UPDATER.JS
function init() {
setInterval(read, 2000)
}
function read() {
$.ajax({
type: 'POST',
url: 'readDB.php',
dataType: 'jsonp',
success: function (data) {
console.log(data);
var json_obj = $.parseJSON(data);
console.log(json_obj[0].gwnumber);
},
error: function () {
console.log("Error loading data");
}
});
}
I'm doing an ajax call to the readDB.php that is working as intended, infact i have the correct value in the json_obj.
My question is: how can i get the json_obj value and pass it to the status.PHP file that is the one who's including the JS too?
Hope you can help. TY
Ok, there is a lot to say in this argument, but i will be the briefiest possible.
first things first
php and Javascript are two different programming language with a completely different paradigm.
The first is a back-end focused programming language;
Javascript instead is more front-end focused, just for entirety i have to mention that JS is used also for the backend part with a special eviroment called Node.js
back to the problem, the things that you are trying to do is not impossible but is excactly as you asked, your're idea (if i got it) was to pass the data from the js to the php like a parameter in a function...
the thing is that the php is elaborate and renderizated before in the server and the javascript is executed in the client, in the client web page there is no more footprint the php. This process is described very well at this link: http://php.net/manual/en/intro-whatis.php
The possible solution is:
FRONT-END(js): make another ajax call(request) to the same page that you are displaying with all the data that you want to elaborate.
BACK-END(php): controll if this request has been made, then access the data with the global variables $_POST & $_GET (depending on the type of the request), then elaborate this data.
if I can I suggest you to make a check if the manipulation that you want to do on those data need to be done in the server-side and not by the js!
Consider the order of execution:
User visits status.php
Browser requests status.php
Server executes status.php and sends response to browser
JS requests readDB.php
Browser requests readDB.php
Server executes readDB.php and sends response to browser
JS processes response
Go To 4
By the time you get to 7, it is too late to influence what happens at step 2.
You could make a new Ajax request to status.php and process the response in JS, but since status.php returns an entire HTML document, that doesn't make sense.
You could use location to load a new page using a URL that includes status.php and a query string with information from the Ajax response, but that would making using Ajax in the first place pointless.
You should probably change readDB.php to return *all** the data you need, and then using DOM methods (or jQuery wrappers around them) to modify the page the user is already looking at.
The simpliest and fastest (maybe not the sexiest way) to do it :
create global variable var respondData; in STATUS.PHP
within you ajax request on success function assign your data callback to it
respondData = data;
Now you have an access to it from every place in your code even when the ajax request is done. Just bare in mind to ensure you will try to access this variable after the page will fully load and after ajax will process the request. Otherwise you will get 'undefined'

Conceal URL in javascript code ( URL generated by PHP )

I am looking for a solution to the following:
I have a piece of JS code, that performs a redirection to a URL that is constructed with PHP, and that redirection is only done when the user presses a button on a confirmation dialog.
The code is, as follows:
function one() {
window.location.replace("<?php
if($new_redir == "1") {
echo "$new_second_redirect_URL/?token=$hash";
}
else {
echo "$second_redirect_URL/?token=$hash";
}
?>");
}
It works perfectly fine. What I wanna do is conceal the URL that is displayed in the source code when a user opens the page.
What would be the best way to do that?
You're thinking too much into this to be honest.
If they want to avoid the confirmation screen and get the URL from the source, there's not really much you could do.
The best really is possibly performing an AJAX request on confirmation and getting a CSRF token based URL from the response and using that, but that could end up being overkill as well.
You could also make it into an actual <form></form> form with a few hidden fields (again, such as a CSRF token), and perform the post validation onclick. If it a success - redirect them.
UPDATE:
Use robots.txt to stop bots
Build the QS with JS to stop most bots, something like:
var csrftoken='XJIWHEOU324uipHFOFUHR';
var url="http://url.com/page.php?token=";
url=url+csrftoken;
What you could also do, is something like us actually, although for your use case it could be too much.
Log every single page load into the DB, and check if if they're a first time visitor to the page after confirmation.
AJAX call (jQuery example):
$.post( "url_to_backend_page_to_get_url", {hasSubmittedForm:"true"}, function( data ) {
window.location.href = data;
});

dynamically change select options with php

Okay, so I have this function in PHP that gets an attribute and returns an array. Something like this:
function getProvinces($countryID){
return arrayWithProvinces($countryID);}
Everytime the parent select changes, the function getProvinces() should be executed with the new ID and the arrayWithProvince should be included as options in the child select.
I'm using jquery to handle the events, as I found somewhere. I need to do something like this.
$("#selectCountry").change(function() {
var parent = $(this).val(); //get option value from parent
var prov = <?php echo json_encode($pagina->getProvinces( <PARENT> )); ?>;
list(prov);
My problem is that I don't know how to tell the getProvinces($countryID) php function which is the new value of the parent.
Thanks in advance.
You should use javascript for that in order to refresh part of your page with dynamic content.Below is an example using jquery's ajax function.When the select with id #parent_select changes you call your php script and you append the returned data (the html of the child select in the example) in a div you want.
Javascript part would be something like this:
$("#parent_select").change(function() {
$.ajax({
url: "your_script.php?cid="+$(this).val(),
success: function(html){
$("#child_select_container").append(html);
}
});
});
And your_script.php code would look something like :
<?php
function getProvinces($countryID){
return arrayWithProvinces($countryID);}
$countryID=(int)$_GET['cid'];
$provinces=getProvinces($countryID);
echo '<select id="child_select">';
foreach($provinces as $key=>$province){
echo '<option id="'.$key.'">'.$province.'</option>';
}
echo '</select>;
I havent tested the example.It is just a basic how to example.You should be able to work your way from here.But if you have any problems let me know.
As far as I know, you cannot execute the function without reloading entire page (I mean php should recompile it and pass it to the client).
You should use only JavaScript for that purpose. Store you arraylist in JS code, and validate it once upon form submission (just to be sure).
You need to make an Ajax request to the server.
Look at it this way: Your Javascript/jQuery is running on the client side (web browser) and you PHP is running on your web server.
So to communicate between the browser(jQuery) and the server(PHP) you need to make a Ajax request.
jQuery has a ajax function you could use, your best bet is to do some research on the subject as Ajax is something you will use all the time and understanding how it works is crucial.

using ajax to send javascript data to php

so i've been looking at how to record and send client-side data to a php server.
i'm not sure of the correct terminologies, but i think that using an ajax call to send a post to the php server is the most elegant way to solve this problem.
so i decided to implement this data exchange:
$("#"+activityInfo.ID).click(function(){
window.open(activityInfo.URL+"userId="+$("#userid").val()+"&activityId="+activityID+"&classId="+classID);
classid = classID;
activityid = activityID;
$("body").append("class: " + classid);
$("body").append("id: " + activityid);
$.post('http://chemcollective.org/chemvlab/php/updateProgress.php', { 'cid':classid , 'aid':activityid } );}); //i think this is the important line that sends the data
and the corresponding php file (updateProgress.php)
$class_id = $_POST['cid']; //receives the data
$activity_id = $_POST['aid'];
i'm not sure why this is the case, but class_id and activity_id variables always return an empty value.
i understand somewhat that the client-browser is on a page that is preloaded by information from a php server. but there were posts that said this is a possible way to communicate back to the php server with information from the client. i'm not really sure what is going on b/c at this point i don't really know what questions to ask.
one of the example explanations that i had been following:
Ajax passing data to php script
thanks for the help.
i've also played around with start_session() and storing/loading session variables as a way to transfer data information. this works but only for php <-> php communication. it does not for saving javascript variables, so i couldn't really use $_SESSION = ..... in my javascript code.
you need to get the cid and aid outside of the single-qouts while using $.post! try this:
$.post('http://chemcollective.org/chemvlab/php/updateProgress.php', { cid:classid , aid:activityid } );

Pass data to database using javascript Onclick

I am a real noob when it comes to javascript/ajax, so any help will be very appreciated.
In reference to this question:
Updating a MySql database using PHP via an onClick javascript function
But mainly concerned with the answer left by Phill Sacre. I am wondering if someone could elaborate on how we are(if we can?) passing values/data through his example, using jquery.
The code example left by him is as follows:
function updateScore(answer, correct) {
if (answer == correct) {
$.post('updatescore.php');
}
}
...
<a onclick="updateScore(this, correct)" ...> </a>
Say for example, we are wanting to pass any number of values to the database with php, could someone give me a snippet example of what is required in the javascript function? Or elaborate on what is posted above please?
Thanks again all.
The simplest example I can think of is this. Make your AJAX call in your if block like this:
$.get('updatescore.php', {'score': '222'}, function(d) {
alert('Hello from PHP: ' + d);
});
On your "updatescore.php" script, just do that: update the score. And return a plain text stating wether the update operation was successful or not.
Good luck.
P.S.: You could also use POST instead of GET.
What you would do is on the php server side have a page lets say its update.php. This page will be visited by your javascript in an Ajax request, take the request and put it in a database.
The php might look something like this:
<?php
mysql_connect(...)
mysql_query("INSERT INTO table
(score) VALUES('$_GET["score"]') ")
Your javascript would simply preform an ajax request on update.php and send it the variables as get value "score".
Phil is not passing any values to the script. He's simply sending a request to the script which most likely contains logic to 'update' the score. A savvy person taking his test though could simply look at the HTML source and see the answer by checking to see what the anchor is doing.
To further nitpick about his solution, a set of radio buttons should be used, and within the form, a button or some sort of clickable element should be used to send the values to the server via an ajax request, and the values sent to the server can be analyzed and the status of the answer sent back to the page.
Since you're using jQuery, the code can be made unobtrusive as seen in the following example:
$('#submit_answer').click(function() {
var answer = 'blah' // With blah being the value of the radio button
$.get('updatescore.php',
{'value': answer},
function(d) {
alert('Your answer is: ' + d') // Where d is the string 'incorrect' or 'correct'
}
});
Enjoy.

Categories