EDIT:
This is what i managed to build...but it still dont work..
$(document).ready(function(){
$("tr").click(function(){
txt=$("input[name=path]").val();
$.ajax({
type: "POST",
url: contract.php, // the same page where i have the table
data: txt, // the variable containing the dynamic id from the clicked row
success: success, // i have no idea what is this parameter for....
dataType: dataType // i have no idea what is this parameter for....
});
});
});
PHP:
$row=mysql_fetch_array($query){
echo '<tr id="'.$row['id'].'">';
echo '<td></td>';
echo '</tr>';
}
What i want,is when the user click on a row , the row id(which is dynamic), must be taken , and returned with ajax post , so i can use it in another query.I have to do this without reloading the page, thats why i try to do it with ajax.
If it's ok to use jQuery i would use something like this to build my table (beside the mysql_*):
<?php
$row=mysql_fetch_array($query){
echo '<tr class="listContractRow" data-path="'.$row['id'].'">';
echo '</tr>';
}
?>
Then catch the click event with a jQuery listener:
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
$(document).on('click','tr.listContractRow', function(e){
var path = $(this).data('path');
//Use the variable path here in your AJAX call
//Assuming you want a GET request, you can also use $.ajax or $.post here
$.get('YOUR_AJAX_URL_HERE?path='+path, function(){
//Do something after the ajax call
});
});
</script>
EDIT
In your PHP you can do something like:
<?php
if(isset($_GET['path']))
{
//Query here with the variable $_GET['path'];
//Echo the results you want
//Perform an exit here, since it's an AJAX call. You probably don't want to echo the code below (if there is)
exit();
}
?>
jquery ajax get example
$.ajax({
type: "POST",
url: "index.php",
data: "{param: "param"}",
success: function(msg) {
},
error: function(err) {
}
});
Related
I have this link that is supposed to delete an entry and refresh a div via ajax. However, for some reason it isn't working at all and its just shifting the page up and adding a # to the url.
If I add an alert to output the id and user_id, it shows up and no # is added to the url.
This is the code
<script>
function removeExistingBranch(id,user_id){
$.ajax({
method: "POST",
url: "<?php echo site_url($this->data['controller'].'/RemoveUserBranch/'); ?>",
data:'id='+id+,
'&user_id'+user_id,
beforeSend: function () {
$('.loading').show();
},
success: function(data){
// $( "#existing_branch_container" ).load( "<?php echo site_url($this->data['controller']);?>/LoadUserBranches" );
$('.loading').fadeOut("slow");
},
});
return false;
}
</script>
Remove
Could someone take a look and see if I am missing something?
You have syntax error in the ajax call. Change it
data:'id='+id+,'&user_id'+user_id,
to
data:'id='+id+'&user_id'+user_id,
I am using an ajax call to save value of a radio button through hidden field in database using ajax call, used an alert to see if its working, and it is.
The URL I mentioned in the ajax call is redirecting it to a controller but I used an alert to see if its working, but its not working. Can't locate what's the issue.
Here is the code of ajax call in view:
<script type="text/javascript">
$('#save').click(function(){
var hint=$('#hidfield').val();
alert('Oops, your response is '+hint);
$.ajax({
url: '<?php echo base_url();?>welcome/save_answer',
type: "post",
dataType: "html",
data:{hint:$hint, <?php echo $this->security->get_csrf_token_name();?>: "<?php echo $this->security->get_csrf_hash();?>"},
success: function(data) {
}
});
});
</script>
Here is the controller:
function save_answer()
{
alert('You Can Do It !!');
$data = array(
'hint'=>$this->input->post('hint')
);
$this->base_model->save_answer($data);
}
Here is the model:
function save_answer($data)
{
$this->db->insert('questions',$data);
}
Please suggest some way out.
You cannot used javascript "alert()" inside controller.
instead of "alert('You Can Do It !!');" use "die('You Can Do It !!');" to debug, and check in to your console.
I am trying to set the content of an empty div after an AJAX call with the data message. I also wired the function to my CHtml::submitButton, which should call the function when clicked, but nothing is happening. Any suggestions?
<div id="myResult">
</div>
JavaScript:
function successMessage(){
$.ajax({
type: "GET",
data: "<div> Replace div with this contentf</div>",
success: function(data){
$('myResult').html(data);
}
})
}
PHP:
echo CHtml::beginForm(array('myForm'), 'get', array('form'));
echo '<div class="row form">';
echo '<div class="row buttons">';
echo CHtml::submitButton('Download Content', array('htmlOptions' => 'successMessage()'));
echo '</div>';
echo '</div>';
Your problem relies in the following line:
$('myResult').html(data);
Here, you are trying to do a jquery selection to an element, which you are not using in your html (this is only possible via pollyfils). So you have to select the element by its ID:
$('#myResult').html(data);
And another thing i've seen, what is the url where you are doing the request?
<script>
function successMessage(){
$.ajax({
type: "GET",
url: "/please/add/an/url/",
data: "<div> Replace div with this contentf</div>",
success: function(data){
$('myResult').html(data);
}
})
}
</script>
first of all, when you are using onclick function like this :
<input type="submit" onclick="successMessage()">
you should use this instead:
<input type="submit" onclick="successMessage();result false;">
but when you are already using jquery, then better approach is:
$( document ).ready(function() {
successMessage(){
// your ajax goes here
}
$('#myResult').click(function(e){
e.preventDefault();
successMessage();
});
});
Then you need to repair your successMessage function. You see, the data you are setting there are not the data, that are coming out as an output. If you need ajax then you probably want to get the result from some php script on some other url. Then you should do it like this :
function successMessage(){
$.ajax({
type: "GET",
url : 'index2.php',
dataType: "json",
data: { mydata: '<div> Replace div with this content</div>'},
success: function(data){
$('#myResult').html(data);
}
})
}
Then you need a php file named index2.php which can look like this :
<?php
echo json_encode($_GET['variable']);
?>
And i dont know if this your line :
echo CHtml::submitButton('Download Content', array('htmlOptions' => 'successMessage()'));
also put the </form> tag after the form to close it.
This should work for you. I tried it and it works fine.
Try this:
$.ajax({
url: "test.html",
type: "GET",
data: "<div> Replace div with this contentf</div>",
success: function(data){
$('#myResult').html(data);
}
})
selector jQuery incorrect in response ajax. and define Url in ajax.
JavaScript
function calcPrimesLoop() {
var primes = document.getElementById('primes');
primes.appendChild(document.createTextNode('\n'+this.prime.nextPrime()));
$.ajax({
url: "/test.php",
type: "post",
data: {prime: this.prime.nextPrime()},
success: function(data) {
}
});
calcPrimesDelay = setTimeout('calcPrimesLoop()', this.delay);
}
Php
<?php
$content = $_POST['prime'];
$fn = "content.txt";
$content = stripslashes('prime'"\n");
$fp = fopen($fn,"a+") or die ("Error opening file in write mode!");
fputs($fp,$content);
fclose($fp) or die ("Error closing file!");
?>
So this is all the relevant scripting I think. I have a script that can get prime numbers and it works perfectly. But now I want to record these numbers on a text file. This is how I am trying to do it but I am having no success at all. Thank you. The issue is the numbers aren't being recorded.
I added an alert the Ajax is working. But when I add a form to the php script and submit it that works. So the ajax and php scripts are not working together as such.
You should read up about AJAX and see how you can pass information to a serverside page using Javascript and retrieve the return value.
http://www.w3schools.com/ajax/default.asp
https://www.youtube.com/watch?v=qqRiDlm-SnY
With ajax and jQuery it is actually simple.
function calcPrimesLoop() {
var primes = document.getElementById('primes');
primes.appendChild(document.createTextNode('\n'+this.prime.nextPrime()));
$.ajax({
url: "myScript.php", // URL of your php script
type: "post",
data: {prime: this.prime.nextPrime()},
success: function(data) {
alert("success");
}
});
calcPrimesDelay = setTimeout('calcPrimesLoop()', this.delay);
}
myScript.php :
<?php
$content = $_POST['prime'];
...
You should definately look for Asynchronous JavaScript and XML.
You can choose between using AJAX with a Javascript function, or simplify your life with jQuery
Here is a sample:
//STEP ONE: INCLUDE THE LAST VERSION OF JQUERY
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
//STEP TWO, GET YOUR FUNCTION TO WORK:
function sendVariableTo(variable,url) {
$.ajax({
url:url, //Or whatever.php
type: "GET", //OR POST
data: { myVar: variable}, //On php page, get it like $_REQUEST['myVar'];
success:function(result){
//If the request was ok, then...
alert(result) //Result variable is the php page
//output (If you echo "hello" this alert would give you hello..)
},
});
}
Hope this helped, bye !
Can somebody please explain to me what is the right way to call a php function with jquery / ajax in Codeigniter. Right now, this code isn't working and i cant figure out whay. Note that admin.php controler is inside admin map. Thanks in advance
html code
<form action="#" method="POST" id="change">
<input type="hidden" value="<?php echo $row->id_product; ?>" id="prod" >
<input type="submit" value="switch" >
</form>
<div class="resultdiv">
<?php echo $data; ?>
</div>
my function inside admin.php controller
public function do_search(){
$id = $this->input->post('id');
return $id;
}
Jquery AJAX script
$( "#change" ).submit(function() {
alert( "Change" );
var id = $('#prod').val();
$.ajax({
type:'POST',
url:'admin321/do_search',
data:{'id':id},
success:function(data){
$('#resultdiv').html(data);
}
});
});
Config / routes.php
$route['admin/do_search'] = "admin_controller/admin/do_search";
I know that this is old post, but maybe someone will find this usefull.
I solve this problem by adding index.php in url. Even if the index.php is hidden using rewrite.
$( "#change" ).submit(function() {
alert( "Change" );
var id = $('#prod').val();
$.ajax({
type:'POST',
url:'<?php echo base_url("index.php/admin/do_search"); ?>',
data:{'id':id},
success:function(data){
$('#resultdiv').html(data);
}
});
});
Maybe like this:
$( "#change" ).submit(function() {
alert( "Change" );
var id = $('#prod').val();
$.ajax({
type:'POST',
url:'<?php echo base_url("admin/do_search"); ?>',
data:{'id':id},
success:function(data){
$('#resultdiv').html(data);
}
});
});
You have to load this helper:
$this->load->helper('url');
#edit
$route['admin/do_search'] = "admin_controller/admin/do_search";
This code is unnecessary.
In the past, I have set up a route for the ajax request. Something like this:
$route['admin/search/(:any)'] = 'admin_controller/admin/do_search/$1';
Then my ajax request would look like this:
var prod = $('#prod').val();
$.ajax({
type: 'post',
url:'admin/search/'+prod
...
});
Or, you can grab the form action via jQuery and use that as your url.
<form action="admin/search/123" method="post">
$.ajax({
type: 'post',
url: $('form').attr('action')
...
});
I know this works. My routes file is the default.
I loaded CI URL helper in my controller __construct() function
$this->load->helper('url');
Here's my ajax:
/*
*Ajax function to load confirmation page
*/
var formID=$("div form");
formID.submit(function(event){ //activated on submit event
event.preventDefault(); //stops page from reloading
$.ajax({
type:"POST",
url:'<?php echo site_url("plan/process")?>',
data:formID.serialize(),
success:function(data){
$("div #msg_area").html(data);
window.setTimeout(function(){parent.location.reload()},3000);
}
});
});
I have multiple controllers so it calls the specific one call plan and the \n the function process. The process function one looks like this:
function process (){
$json_data = strtolower(json_encode($this->input->post()));
$res = array();
//Simple Error/success display...
$res = json_decode($this->plan->process_plan($json_data ),true);
if(array_key_exists('error',$res)){
$window = "warning";
$error=explode(":",$res['error']);
$result['message']="<h2><span class='color-dark'>Submission error:</span> ".$error[0]." </h2><p>".$error[1]."</p>";
}
else{
$window = "success";
$result['message'] = "<h2>Submission was a success</h2>";
}
echo $this->load->view("common/components/".$window,$result);
}
This works great for me. Hopefully it helps.
in your routes file you have: admin321/do_search NOT: admin/do_search
You can also try using the absolute path:
`http://www.website.com/admin/do_search` or `http://localhost/admin/do_search`
in the ajax url parameter