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.
Related
I am new to AJAX here. How can i replace the initial php function after the action of ajax is execute? I have found that the page will not refresh after the action is execute.
Here is the code:
javascript
function set_ddm(another_data) {
var result = $.ajax({
url: '../display/ea_form_header.php',
type: 'POST',
data: {
action: 'set_ddm',
Data_store: another_data,
},
success: function(data) {
console.log(data);
}
}).responseText;
}
php code
<td>
<?php
//initial function (customized drop down)
print ddm_jsfunc_employee("employee_list",$employee_list)
set_ddm(data);
if($_POST['action'] =='set_ddm') {
$employee_list=$_POST['Data_store'];
$employee_list_decoded = json_decode($employee_list,true);
//expected this function to replace the initial function after ajax was called
print ddm_jsfunc_employee("employee_list",$employee_list_decoded);
} ?>
</td>
I expect the function will replace the initial function and show in the main page but it only show in console after ajax(page aren't refresh to show it). Is there any wrong with the code or any solution for this? (the ddm_jsfunc_employee must be there to print the drop down)
thanks in advance
From ajax success callback you have to set that response in the html to view on web page.
like this:
$('.elementClass').html(response);
i hope this will works for you.
I think you have a slight misunderstanding about what AJAX is, it is not something to replace your PHP code with, but to asynchronously get data and update your webpage without reloading.
Let's first take a look at the .ajax function specifically interesting for us now is the .done() callback method, because JavaScript does the request realtime (async) JavaScript does not know when the request is done. But it allows us to specify a function inside the .done for it to call when it is done.
A really simple example would be:
$.ajax('https://stackoverflow.com')
.done(function(data) {
// We can do what we want with the data here.
console.log(data);
});
Now when the request is done the function we defined in .done will be called, in this case a simple log. But you would want to change this to a function that updates your HTML.
I also see you are calling JavaScript functions in your PHP, this will not work as PHP runs on your server but JavaScript runs in your browser. (Unless you use node or the likes)
Just a tip; it is advised to place JavaScript at the bottom of your HTML page as JavaScript is blocking content. (proper link explaining needed here)
Meaning your browser will stop parsing the HTML and run the JavaScript as it finds it.
Long story short, if you want to replace the PHP code, you would have to remove it. Make a PHP script which gives you your data. AJAX call it and then use .done or success and update your webpage from there.
I am trying to send a row and column number of the clicked cell via GET method.
to php file, where I can check if this cell contains something or not.
For example that the URL will loke like this:
.php?c=3&r=5
I am using:
https://www.w3schools.com/jquery/ajax_get.asp and I have been trying to send data like it is listed on W3schools:
Request "test.php" and send some additional data along with the request (ignore return results):
$.get("test.php", { name:"Donald", town:"Ducktown" });
I am doing it like this:
$(document).ready(function() {
$("td").click(function(event) {
var clickedBtnID = $(this).attr('id');
values=clickedBtnID.split('.');
var row=values[0];
var col=values[1];
$.get("info.php", {"row":row, "col":col});
I was looking at some other examples on StackOverFlow, like:
How to send data to PHP file using JQuery Ajax?
I would like to say it that info.php is the diferent .php file, as the one we are working from. And another thing is that the best way to do this, would be to do it without refreshing the page. So is Ajax call the best way for this? I have tried many different things, but it seems like I can't send the data via GET method.
I'm not 100% sure I understand what you're looking to do, but I'll try to help!
Have you tried something like this? In your js file:
$.get("info.php?c=3&r=5");
Then in your PHP file:
//Retrieve the variables
$c = ($_GET["c"]);
$r = ($_GET["r"]);
//Then do what you need to do with $c and $r
Let me know if that helps.
I have tried this:
$.ajax({ url: 'info.php',
data: {'row':row, 'col':col},
type: 'GET',
success: {}
});
And it works perfectly. I don't know why the jquery $.get didn't work.
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.
How do I call a function from a component from a view? (ctp file)
I am using something like this:
App::import('Component', 'YourComponent');
$theComponent = new YourComponent();
$theComponent->yourMethod();
I want the line $theComponent->yourMethod(); to be executed on a button click but instead it is executed upon page load...
here is a part of the code:
<script type="text/javascript">
function assign()
{
var links_list = [];
var links =document.getElementById('unassignedUsers').getElementsByTagName('a');
for(var a in links) {
if(typeof links[a] == undefined) continue;
links_list.push(links[a].innerHTML);} var str =links_list.toString();
var array = str.split(',');
alert(array);
}
<?php App::import('Model', 'Account');
$account = new Account();
$account->insertPos();?>
}
<button id="button" name="button" onClick="assign();"> Save Changes </button>
//this is the button i need the function to be executed when i click....
Please tell me what to do make the php code inside the javascript to be executed only when the button is clicked?
echo $form->create('Account', array('action' => 'insertPos'));
echo $form->button('Save Changes', array('type' => 'submit'));
echo $form->end();
Both cakephp and the internet work on specific architectures. Granted with Cakephp, it is easier to "break" the architecture and create work arounds, it is very difficult on the internet. The internet uses a client-server architecture where HTML, Javascript, and CSS work on the client-side, also known as the browser and php (along with other languages) operate on the server side. The server only interacts with the client-side after loading with an HTTPRequests (the easiest being AJAX). Only an HTTPRequest will trigger the server side run and that will always be done through an URL. Hence, the following is a rough model in which you should be following.
Client-side <---- HTTPRequest ----> Server-side
Given this and working with Cakephp, in order to follow best practices and gain the most from Cakephp, your request to save should be sent to a controller with the following URL:
www.yoursite.com/controller-name/save
From here, assuming all values are in a form elements, your controller will only be sent the values in the form elements. Then within the controller the following should happen
$this->Account->insertPos();
Best advice, if you want to make your website dynamic. Familiarize yourself with AJAX.
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.