I am trying to assign a value from a variable created in JavaScript in my view to a variable in my controller. How can I do that? I am new to CodeIgniter and JavaScript.
The idea is that I validate an email input field in my view with JavaScript and then assign that value to a controller variable and then retrieve that value in my controller.
$john_email is my controller variable and email my JavaScript variable
$('#submitRequests').click(function(){
console.log("Clicked submit");
var data = getTableContent();
console.log("machines: ");
console.log(data);
var email = $("#emailInput").val();
if(isEmail(email)){
$john_email = email; // something like this!
uploadMachines(data);
}
else
alert("Incorrect email");
});
It sounds like you're very new to client-server programming. JavaScript runs on the client (web browser), PHP runs on the server. To send data from JavaScript to PHP, you need to submit the data back to the server, either by posting the page, or by using AJAX for asynchronous communication with the server (allowing you to send data back to the server and update the page on the client without posting and reloading it).
There are many great tutorials on AJAX out there, and I've linked, what I feel, is the best one. Read up on the subject, and if you still need help, report back with what code you've tried and what results you got.
Since you are already using jQuery in your code, take a look of jQuery.ajax() method. Also, for CodeIgniter take a look of Input class.
// Javascript
$('#submitRequests').click(function(){
console.log("Clicked submit");
var data = getTableContent();
console.log("machines: ");
console.log(data);
var email = $("#emailInput").val();
if(isEmail(email)){
$.ajax({
type: "POST",
url: base_url + "controller/post_email", //here base_url = http://domain.com
data: {email: email},
dataType: "text",
cache:false,
success:
function(john_email){
alert(john_email);
}
return false;
});
}
else
alert("Incorrect email");
});
//codeigniter controller
<?php
function post_email()
{
$john_email = $_POST['email'];
return $john_email;
}
?>
Related
Hi im having a problem refreshing my page when a condition is met in php using ajax, if the php script is successful i want it to reload the page but when it is not then i only want to echo the errors.
The following is the part of my PHP code that returns the 'success' or error message:
if ($login) {
echo "success";
} else {
echo '<p>Username and Password does not match</p>';
};
This is working as i have tested it separately and the user gets logged in even though ajax
The problem i think comes in the ajax call back with the if statement.
Here is the my js script that is running the ajax call back.
$('form.ajax').on('submit', function(){
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value){
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response){
if(response == "success") {
//location.reload();
window.location = "index.php";
} else {
$('#loginError').html(response);
};
}
});
return false;
});
I have tried everything on the net but every time the PHP script is successful it just echo's out the word success rather then redirecting the page or reloading
Thanks chris85 for the perfect advice worked like gold and was able to fix the problem, that was that there was a extra line at the top of my PHP script that I missed and saw it when i used console.log(response), also read the post you linked and it will help with future problems like this for me so thanks again.
Im on project to make an app with codeigniter but i got stuck, when i want to pass same variable outside field via ajax into controller i got error the variable is not defined.
this is a example.
$("#form_status_update").submit(function() {
var date = new Date().toString();`
$.ajax({
type: 'POST',
url: "<?php echo base_url()?>socialcontroller/setdate",
data:date,
success: function(data) {
window.location.href = "<?php echo base_url()?>socialcontroller/ssetdate";
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError); //throw any errors
}
});
});
after passing some var i want to insert into my database.
and my question is how to pass a variable not field into controller via ajax thanks, i already search on google but i didnt geting the right answer :)
`
The line data:date, is wrong. You are passing up a number on the querystring and not a key/value pair.
It needs to be
data: {date : date},
or
data: "date=" + encodeURIComponent(date),
From jQuery Docs:
data
Type: PlainObject or String or Array
Data to be sent to the
server. It is converted to a query string, if not already a string.
It's appended to the url for GET-requests. See processData option to
prevent this automatic processing. Object must be Key/Value pairs. If
value is an Array, jQuery serializes multiple values with same key
based on the value of the traditional setting (described below).
Here is the code that help you with your problem
You can just adapt it with your code and it should work !
<script>
$(document).ready(function(){
$("button").click(function(){
var myDate = new Date();
$.ajax({
// Send with POST mean you must retrieve it in server side with POST
type: 'POST',
// change this to the url of your controller
url:"index.php",
// Set the data that you are submitting
data:({date:myDate}),
success:function(result){
// Change here with what you need to do with your data if you need of course
$("#div1").html(result);
}});
});
});
</script>
<body>
<div id="div1">
<p>Today date here</h2>
</div>
<button> Get Date< /button>
</body>
</html>
and your PHP code can be something like this !
<?php
// This line of code should get your data that you are sending
$data = $_POST['date'];
/// This code was just for checking purpose that it is returning the same value through ajax
$arr = array(
'receive_date'=>$data,
);
echo json_encode($arr);
I think this code can work with must of MVC framework if you are setting your controller URL as url parameter. Check also the Framework documentation about getting the data through POST !
your selector $("form_status_update") doesn't match a class or an id of the DOM.
and it doesn't match an html element either.
so this for sure gives you some (extra) problems.
couldnt you have tried running the date function at the php controller youre calling from the ajax function.
i dont see any specific reason as to why you have to send in date as the input parameter from the javascript function.
remove the date var and data field.
and in your php controller.
when you get the controller called.
run a date function in the php code and use the date from there.
I'm trying to send an email using the PHP mail function, but the required content is stored in a JS variable, I'll try to code out my situation for you to understand better.
<script type="txt/js">
var content = "This is what I need to send via email";
if({Irrelevant validation check})
{
alert("Form submitted! Redirecting... <?PHP mail('admin#admin.com', 'subject', [XXX]);?>");
}
</script>
I need the text stored in the content variable to be in place of the [XXX] above.
I would appreciate any help. :)
You can try this way simpler using $.post():
$.post("sendEmail.php", { contentData: content }, function(response) {
console.log(response);
//Form submitted! ...Redirecting...
});
sendEmail.php
$content = $_POST['contentData'];
$to = 'someemail#domain.com';
$subject = 'The content';
$message = 'Content'.$content;
$headers = 'From: youremail#domain.com' . "\r\n";
if (mail($to, $subject, $message, $headers)){
echo "Your email was sent!";
}else{
echo "Email did not send";
}
As others have mentioned it, using AJAX is your best option. You can pass the information to the php file using AJAX as follows:
$.ajax({
type : "POST",
url : url,
data : content,
success : alert('success'),
error: alert('error')
});
To have better data handling, you can define a Formdata and save the content var in that data.
var data = new FormData();
data.append("content", content);
and then you can post this data:
$.ajax({
type : "POST",
url : url,
data : data,
success : alert('success'),
error: alert('error')
});
No, you cannot use pure javascript to do ANYTHING that affects the PHP code. PHP is run on the server side. Javascript is run on the client side. However if you set up your php as a service, i.e. in PHP set up page X to accept mail information, and then use javascript to post to page X, page X will effectively send the mailing with the info given to it by javascript. But javascript cannot directly affect PHP code.
PHP Code is rendered first, Then HTML, Then Javascript. It's the web stack.
AJAX can be used to talk back and forth between client and server like the other answers are mentioning, but the question was is it possible and how do you use JS to send mail via PHP.
I simply used the window.open(url.php?var=var); method using Javascript, and passed the variable through the GET parameter, then the "url.php" page picked it up via $_GET['var'];
Its better to use AJAX in this kind of situations. Pass the "var content" value via AJAX and do whatever you want.
I'm trying to program a custom contact content manager in HTML/CSS with PHP/mySQL/Jquery to make it dynamic.
I have my login form which send the $_REQUEST to my connection.php, when the auth is correct, I return json to my Jquery and when it is good, I use window.location.replace to redirect the user to the control panel.
When I'm on the index.php of the control panel, I want to check if the user's session_id is into my sql database and if it exceeded the expiration time.
I have my functions which check this and return the good value but I want to execute it and send the result to my jquery without using GET or POST method.
If I remember, you have
$.ajax({
type: "POST", //or GET method
dataType: "json",
url: $(this).attr('action'),
data: $(this).serialize(),
success: function({
}),
error: function({
})
});
But you must specify the element "data" no? can I use it without data and put "file.php" as url without POST or GET method?
I want to get into my success method the result of my php functions :
if the json return false, the user can access the page.
if the json return true, I will logout the user and redirect him to the login.php
I'm doing this system because I don't want anybody can access the control panel by writing the correct url or after 4 days.. I put an expiration time to one hour (for the moment) for anybody who login into the control panel and I check on all page that the expiration time isn't exceeded.
I saw that using 'window.location.replace' doesn't allow to return to the previous page.. has anyone a solution? I don't want to have an event to redirect the user, only redirect him to another url (my file.php) after a condition.
Currently, I use it to execute php without POST, GET method with $.ajax..
$(document).ready(function(){
$(function(){
var ticket = '<? echo $tickets; ?>';
console.log(ticket);
if ( ticket === '' )
$(".new_ticket h2").after('<p>Aucun nouveau ticket.</p>');
else
{
console.log('else');
$(".new_ticket h2").after('<p>Il y a un ticket.</p>');
}
});
});
I have a last question, when I write :
$(document).ready(function(){
$(function(){
}
Is it directly executed by jquery when the DOM is ready? can I write mutliple '$(function(){}' in a file ?
Thanks for the help!
What is the problem with using POST or GET? It works perfectly fine.
Here foobar.php returns a json object with status in it. Change it to whatever your script return.
$.post('foobar.php', function(data) {
if( data.status === false) {
//All good
}else {
//Redirect
window.location.href = "http://newpagehere.com/file.php";
}
});
With window.location.href you will be able to use the back and forward buttons.
And yes, when using $(document).ready(function() { }); it runs when the DOM is ready.
http://api.jquery.com/ready/
One last thing is that I would not rely on Javascript here, I would do all checking with PHP instead when the user changes page. I would also handle the redirection there.
I want to use jQuery Validator to check against the server when a user is signing up for if their desired username is already taken. The PHP script untaken.php does this job, returning ok if the username is available, or taken if it is taken.
My entire source is below, however the line in question is this:
return data != "taken";
Currently the message "Username already taken" permanently appears. However if I change it to:
console.log( data != "taken" );
and type in the text box I see in the console true and false messages exactly when I expect them. That's how I know the design itself isn't to blame, it's just the fact that I can't return anything from the success clause in jQuery.ajax.
$.validator.addMethod("userCannotBeTaken", function(value, element){
var check;
check = $.ajax({
type: "GET",
url: "untaken.php",
data: ({ "user" : value }),
dataType: "text",
success: function(data){
return data != "taken"; //return false if taken or true if not, based on response
}
});
}, "Username already taken");
How can I return something from within jQuery.ajax?
Turns out I was overthinking the whole thing and it can be easily done with jQuery Validator's built-in remote method. Here's my code if it helps someone:
Rule in validator script:
remote: "untaken.php"
PHP:
<?php
//mysql info
[snip]
//connect to database
$sql = new mysqli($mysql_host, $mysql_user, $mysql_password, $mysql_database);
//Populate variable
$newun = $sql->real_escape_string( $_GET['newuser'] );
//Do the actual checks
$un_already_taken = $sql->query("
SELECT username FROM logins WHERE username = '$newun'
"); //check if UN already in DB
if($un_already_taken->num_rows > 0) //un taken already
print "false"; //tell jQuery to not submit form
else
print "true"; //tell jQuery all is good
As easy as printing "true" or "false". Note it uses GET (ie. URL paramaters) not POST, and the GET variable is the name of the field it is validating (in my case newuser)
To return data to the ajax function, you need to print or echo the result in your untaken.php page.
soemething like:
echo $result;exit;
Then Try to alert the data inside success function
and debug the result with
alert(data);return false;
The function you define for the success action is a callback.
When you make an ajax call, it is done asynchronously, (meaning the script continues executing while the browser connects to the server. You can't use return when dealing with callbacks because they are executed later, rather than immediately as a typical function.
This might make more sense: http://recurial.com/programming/understanding-callback-functions-in-javascript/
The success function should perform whatever actions that you want to happen after you get the data back to the server ie: alert the user that the username is taken.