How do I call MVC Controller from with Javascript function - php

I have a onclick event on a submit button in my CI app. So when user clicks submit, it goes to my js function that disables the button, but it does not continue processing. I used this “document.forms[“mainFrm”].submit();”, but because of the way the code is written I need it to go directly to a controller and finish processing.
So how do I call a CI controller from my js function?
Here is the function that is being called onClick:
function disableWhenSubmit()
{
alert ("You did get here");
var holdBtnElement = document.getElementById('btn_Add');
holdBtnElement.disabled = true;
holdBtnElement.value = "sending ...";
//document.forms["createRequestForm"].submit();
<?= base_url();?>index.php/request"; //this is what I am working on
}
and here is the button:
input type="submit" id="btn_Add" name="btn_Add" value="Submit">

index.php
<script>
// create a global var before calling your external
// javascript file(s).
var BASE_PATH = "<?php echo base_url();?>";
</script>
<script src="link_to_myjavascript.js"></script>
myjavascript.js (jQuery example)
(function($){
$(function(){
var do_ajax = function(some_params){
$.ajax({
url : BASE_PATH + 'controller/method',
});
}
if(conditions)
{
do_ajax(some_params);
}
});
})(jQuery);

Look at ajax call.
Using prototypejs or Jquery
<input type="button" onclick="dosomething()" />
example
<script>
function dosomething() {
var url = "something.php";
new Ajax.Request(url, {
parameters: {//parameters},
onSuccess: function(transport){
// do something when response is good
},
onFailure: function (request) {
// Do something when somehting goes wrong
});
}
</script>

Related

Start a function through url

The following function is inside a page (mainpage.php) which I load dynamically into a tab (tabcontent.php) .
$('.editlink').on('click', function() {
var id = $(this).attr('data-ds');
$.ajax({
url: 'noticejob.php?step=get&ds='+id,
method: 'GET'
}).success(function(response,status) {
...
});
});
I call this function by this link, which is inside the tabcontent.php
<i class="fa fa-pencil"></i>
All works fine.
Now I want to start this function over a url call for adding links into other pages to open the mainpage.php and start with this function (should open a modal).
For Example: mainpage.php?start=edit&ds=123
Is it possible and in which way?
You can just print the JS you need to execute in the PHP page.
...
?>
<script>
$(function() {
foo();
});
</script>
<?php
...
To open the modal automatically, either create a JS function that opens the modal and call it (with the previous method), or do
<script>
$(function() { $('.editlink').click(); });
</script>
Ok, now it works,
i've put a new (named "edit_function") js function into the mainpage.php with the "old" code of the "$('.editlink').on('click', function() {..."
after that i call this function from the mainpage if there is a url parameter. I do it into the php file and create a dynamicaly js code
if($_GET['job']=='new')
{
$p['JS']='edit_function("'.$_GET['detail'].'");';
}
at the other hand i call the function for the tabcontent.php page in this way
$('.editlink').on('click', function() {
var id = $(this).attr('data-ds');
edit_function(id);
});
for me it works

Simple ajax code not working?

<form>
<input type="text" id="user"/>
<input type="button" value="Submit" onClick="post();" />
</form>
<div id="result"> </div>
<script type="text/javascript">
function post()
{
var username = $('#user').val();
$.post('battlephp.php',
{postuser:user}
)
}
</script>
Its a simple Ajax code.. It should take username and display the Php code!
But don't know why its not running?? Actually I am learning...so I cant rectify the error or fault??
I am running ii on localhost.. so is there any problem with using:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
display the Php code
No, it shouldn't.
First, you've changed your mind about the variable name you are using (user, username) half way through your script, so you are going to throw a reference error.
Second, you haven't provided a function (the third argument) to $.post, so you aren't doing anything (such as displaying it) with the returned data.
Third, the server should execute the PHP and return its output. You shouldn't get the actual PHP code.
function post() {
var username = $('#user').val();
$.post(
'battlephp.php',
{postuser:username}, // Be consistent about your variable names
function (data) {
alert(data);
}
);
}
Instead
document.ready()
you can use
jQuery(function($){...});
Try to do this:
<script>
$(document).ready(function() {
function post() {
var username = $('#user').val();
$.ajax({
type : 'post',
url : 'batttlephp.php',
data : {
postuser : user
},
success : function(data) {
alert(data);
},
error : function(data) {
alert(data);
}
});
});
});
</script>
if you're doing a ajax request then is good also handle success and error...
Also I suggest to you "to start the document".
Try the code above and let us know if worked

pass a variable to a JavaScript function [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
I have a button in my php page :
<button id="myButton">Delete me</button>
and in that page I have a variable which I want to pass to a JavaScript function, and this is my JS code :
<script>
$(function() {
$('#myButton').confirmOn('click', function(e, confirmed){
if(confirmed) {
//Here I'll use the variable
}
})
});
</script>
How can I do that ?
I think you might be wanting to put a variable through PHP on your button and pass it to your function using jQuery data. Check this out:
<button data-confirmed="<?php echo $confirmed; ?>" id="myButton">Delete me</button>
And in your js:
$(function() {
$('#myButton').on('click', function(e){
// get jquery object access to the button
var $thisButton = $(this);
// this gets that data directly from the HTML
var confirmed = $thisButton.data('confirmed');
if(confirmed) {
//Here I'll use the variable
}
})
});
Basically, you can access variables in javascript using this method if you are interpolating PHP vars directly on the page. If this isn't what you are looking for, please let me know in comments.
<button id="myButton">Delete me</button>
<input type="hidden" name="variable" id="variable" value=2>
<script>
$(function() {
$('#myButton').confirmOn('click', function(e, confirmed){
if(confirmed) {=
alert(document.getElementById('variable').value);
//Here I'll use the variable
}
})
});
You can declare the variable outside the click event like so:
$(function() {
var confirmed = true;
$('#MyButton').confirmOn('click', function() {
if(confirmed) {
// do stuff
}
});
});
Assuming you're talking about passing php variables to Javascript, you can do this when writing to the page, ex:
<?php
$passThis = 'Passing'
?>
<script language="javascript" type="text/javascript">
var sStr = "My name is <?php echo $passThis ?>.";
document.write(sStr);
</script>
You could also get integer values, doing something like
$integerValue = 5;
var int = "<?php echo $integerValue; ?>";
int = parseInt(int);
By modifying this, you could use it to pass more types of variables, so assuming you have something like this:
<?php
$text = 'someText';
?>
<script>
$(function() {
$('#myButton').confirmOn('click', function(e, confirmed){
if(confirmed) {
//Here I'll use the variable
}
})
});
</script>
you could do
<script>
$(function() {
$('#myButton').confirmOn('click', function(e, confirmed){
if(confirmed) {
console.log("<?php echo $text ?>");
}
})
});
</script>
to make Javascript alert 'someText'.

Jquery and ajax on button click

I have this submit button without a form..
<input type='submit' id='conx' name='X' value='TEST x'>
Now when the button is clicked i need to execute this code.
$con = fopen("/tmp/myFIFO", "w");
fwrite($con, "XcOn");
close($con);
How can i execute it in jquery and ajax?.
$("#conx").click(function(){
//Execute this code
//$con = fopen("/tmp/myFIFO", "w");
//fwrite($con, "XcOn");
//close($con);
});
Thanks.
Post that to a PHP page with Ajax and execute those ther
$("#conx").click(function(){
$.post("yourPHPPageWithMagicCode.php");
});
Make sure yo have that PHP code in yourPHPPageWithMagicCode.php file.
If you want to show a response after the process is done, you can return something from your PHP page and let the callback of $.post handle it.
In your PHP page after your code,put an echo
echo "successfully finised";
Now change the jquery code to handle the callback
$("#conx").click(function(){
$.post("yourPHPPageWithMagicCode.php",function(repsonse){
alert(response);
});
});
Let's say your PHP file is called write.php. I believe you can do this:
$("#conx").click(function() {
$.ajax({
url: "/write.php"
});
});
All in one file.
test.php
<?php
if ($_POST['cmd'] === 'ajax') {
$con = fopen("/tmp/myFIFO", "w");
fwrite($con, "XcOn");
fclose($con);
exit;
}
?>
<!doctype html>
<head>
<meta charset="utf-8">
<title>meh</title>
</head>
<body>
<input type="submit" id="conx" name="X" value="TEST x">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$(function(){
$("#conx").bind('click', function(){
$.post("test.php", { cmd: "ajax" } );
});
});
</script>
</body>
</html>
Add something like below inside your click function to call a PHP script:
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "URL/TO/PHP/SCRIPT",true);
xmlhttp.send();
You need a jquery ajax call between the click event block
$("#conx").click(function(){
$.ajax({
url: "phpfile.php",
type: "post",
//data: serializedData,
// callback handler that will be called on success
success: function(response, textStatus, jqXHR){
// log a message to the console
alert(response);
}
});
});
put whatever code you want in the phpfile.php file.
You need to load the 'click event' on the document load i.e.:
$(document).ready(function($){
$("#conx").click(function(){ .....
one way is
$("#conx").click(function(){
$.post("PHPFILENAME.PHP",{
whatdo:otherstuff
},function(d){
// return d here
}
})
run your code in the php file.
You could call a javascript function from the button:
<input type='submit' onclick="myFunction()" id='conx' name='X' value='TEST x'>
and have a page load in your function:
function myFunction(){
var loadUrl = "magic.php";
var result = $("#result").load(loadUrl);
}
Then have magic.php run your method:
//Execute this code
//$con = fopen("/tmp/myFIFO", "w");
//fwrite($con, "XcOn");
//close($con);
This is all untested pseudo-code...

Ajax call not working on enter keypress, works only for click function

I have a ajax method of calling data from php file, i learned it from one of a blog, now it works file for submit button click function, but when i press enter the variables get shown in address bar and ajax process is not executed, Can any one please help me doing it on a press enter method....
This is my code:-
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$(document).ready(function() {
$("input[name='search_user_submit']").click(function() {
var cv = $('#newInput').val();
var cvtwo = $('input[name="search_option"]:checked').val();
var data = { "cv" : cv, "cvtwo" : cvtwo }; // sending two variables
$("#SearchResult").html('<img src="../../involve/images/elements/loading.gif"/>').show();
var url = "../elements/search-user.php";
$.post(url, data, function(data) {
$("#SearchResult").html(data).show();
});
});
});
});//]]>
</script>
I have tried it by taking an if condition along with keypress event still its not working:-
if (e.keyCode == 13) { // Do stuff }
else { // My above code }
//In this also it seems that i am doing something wrong.
Can anybody please enlighten me oh how to do it.
My input field is:-
<input type="text" name="searchuser_text" id="newInput" maxlength="255" class="inputbox MarginTop10">
My submit button is:-
<input class="Button" name="search_user_submit" type="button" value="Search">
You can try with event.preventDefault(); for enter keypress.
Thanks.
When you type enter there is executed default onSubmit handler for a form. You can use submit jquery function to handle both enter and click on submit button.
$("form").submit(function() {
var cv = $('#newInput').val();
var cvtwo = $('input[name="search_option"]:checked').val();
var data = { "cv" : cv, "cvtwo" : cvtwo }; // sending two variables
$("#SearchResult").html('<img src="../../involve/images/elements/loading.gif"/>').show();
var url = "../elements/search-user.php";
$.post(url, data, function(data) {
$("#SearchResult").html(data).show();
});
return false;
});
return false in this function will prevent submit of the form.

Categories