this is my variable in setings.php
$error = output_errors($errors);
i want to echo out in my jQuery file 'settings.js'
$('#save_settings').click(function(){
var first_name = $('#first_name').val();
var last_name = $('#last_name').val();
var email = $('#email').val();
$.post('settings.php', { first_name: first_name, last_name: last_name, email: email}, function(data){
$('#show').html('settings saved').fadeIn(500).delay(2000).fadeOut(500);
alert(data);
});
});
If you want to communicate between JavaScript and PHP, the best way is to create a hidden-inputfield in fill in the errors-variable. And then you can read out the value with jQuery.
The inputfield:
<input type="hidden" value="<?php echo $error; ?>" id="errors" />
And the jQuery-Code:
var errors = $("input#errors").val();
You can't place PHP code inside "javascript" file, PHP code must be in PHP file.
The below code can work if it's placed in .php file:
<html>
<head>
<title>javascript test</title>
<script>
var error = '<?php echo $error;?>';
alert(error);
</script>
</head>
<body>
</body>
</html>
I am assuming that your $error will by different depending on the $_POST values.
If your response header is in HTML, then you can do something like this.
// in your JS codes.
$.post('settings.php', function(response) {
$('#show').html(response).fadeIn(500).delay(2000).fadeOut(500);
});
// in your php codes.
<?php if(isset($error)) { echo($error); } else { echo("setting saved"); } die(); ?>
Anything you want in your js from server side has to come as AJAX or JSON response. echo it from your php function and get it as AJAX or JSON in javascript.
$.getJSON('url for the php file', function(data){}
And in the php file just echo the value
see http://php.net/manual/en/function.json-encode.php
Or take a hidden input field and put the value there. You can get that value from js using the 'id' or 'class' attribute
Related
I am making an ajax request where I will type name in input box to search data from db, It's working fine,
<script>
$(document).ready(function(){
$('input#name-submit').on('click', function() {
var nameVar = $('input#name').val();
if($.trim(nameVar) != ''){
$.post('records.php', {name: nameVar}, function(data){
$('div#name-data').text(data);
});
}
});
});
</script>
----php
if(isset($_POST['name'])){
$name = $_POST['name'];
echo $name;
Now the problem is when I embed the html into php and echo it, It prints the html also
echo "<div class='tblDiv'>";
echo "</div>";
result: <div class='tblDiv'> Name </div>
how to avoid that and get the result in style?
You need to use .html() instead of .text()
$('#name-data').html(data);
.text() will not parse the html content, it will escape the html and print the passed value as it is
I created a php page and javascript code that contains some variables from the PHP page, this is a code that inserts php variables into the database using Javascript :
<?php
$id = "Kevin";
$user = "Calvin";
?>
<!-- include jquery library file-->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<!-- The ajax/jquery stuff -->
<script type="text/javascript">
function send(e){
if(e.keyCode == 13 && !e.shiftKey){
$(document).ready(function(){
//Get the input data using the post method when Push into mysql is clicked .. we pull it using the id fields of ID, Name and Email respectively...
//Get values of the input fields and store it into the variables.
var msg=$("#reply").val();
clear();
//here you start PHP->>
//here we put the PHP Variables ^^^^^^^^^///\\\
//use the $.post() method to call insert.php file.. this is the ajax request
$.post('full.php', {msgg: msg, from: <?php echo json_encode($id); ?>, to: <?php echo json_encode($user); ?>},
function(data){
$("#message").html(data);
$("#message").hide();
$("#message").fadeIn(200);
});
function clear() {
$("#myre :input").each( function() {
$(this) .val('');
});
}
});
}
}
</script>
and in the full.php page
<?php
mysql_connect("localhost","root","");
mysql_select_db("db");
$to=mysql_real_escape_string($_POST['to']);
$from=mysql_real_escape_string($_POST['from']);
$msg=mysql_real_escape_string($_POST['msgg']);
$to = mysql_real_escape_string($to);
$from = mysql_real_escape_string($from);
$msg = mysql_real_escape_string($msg);
if(empty($msg)){
exit();
}
$query=mysql_query("INSERT INTO `message`(`user`,`who`,`message`) VALUES ('$to','$from','$msg')");
if($query){
echo "Perfect!";
}else{
echo "Failed!!";
?>
so is there any way to put the Javascript code into another page and inject it using ajax?
Assign PHP variable's value to java script variable :
<script type="text/javascript">
var json{
"id":<?php echo $id;?>,
"user" : "<?php echo $user;?>"
};
</script>
Change this line from your code :
$.post('full.php', {msgg: msg, from: json.id, to: json.user}
Now you'll have separate js file like:
function send(e){
if(e.keyCode == 13 && !e.shiftKey){
$(document).ready(function(){
//Get the input data using the post method when Push into mysql is clicked .. we pull it using the id fields of ID, Name and Email respectively...
//Get values of the input fields and store it into the variables.
var msg=$("#reply").val();
clear();
//here you start PHP->>
//here we put the PHP Variables ^^^^^^^^^///\\\
//use the $.post() method to call insert.php file.. this is the ajax request
$.post('full.php', {msgg: msg, from: json.id, to: json.user},
function(data){
$("#message").html(data);
$("#message").hide();
$("#message").fadeIn(200);
});
function clear() {
$("#myre :input").each( function() {
$(this) .val('');
});
}
});
}
}
Say this file is myjs.js now include it in php file:
<script type="text/javascript" src="myjs.js" />
I've been looking for a week now for a decent full working example of how to use AJAX with Codeigniter (I'm an AJAX novice). The posts / tuts I've seen are old - all the programming languages have moved on.
I want to have an input form on a page which returns something to the page (e.g. a variable, database query result or html formatted string) without needing to refresh the page. In this simple example is a page with an input field, which inserts the user input into a database. I'd like to load a different view once the input is submitted. If I could understand how to do this I'd be able to adapt it to do whatever I needed (and hopefully it would help others too!)
I have this in my 'test' controller:
function add(){
$name = $this->input->post('name');
if( $name ) {
$this->test_model->put( $name );
}
}
function ajax() {
$this->view_data["page_title"] = "Ajax Test";
$this->view_data["page_heading"] = "Ajax Test";
$data['names'] = $this->test_model->get(); //gets a list of names
if ( $this->input->is_ajax_request() ) {
$this->load->view('test/names_list', $data);
} else {
$this->load->view('test/default', $data);
}
}
Here is my view, named 'ajax' (so I access this through the URL www.mysite.com/test/ajax)
<script type="text/javascript">
jQuery( document ).ready( function() {
jQuery('#submit').click( function( e ) {
e.preventDefault();
var msg = jQuery('#name').val();
jQuery.post("
<?php echo base_url(); ?>
test/add", {name: msg}, function( r ) {
console.log(r);
});
});
});
</script>
<?php echo form_open("test/add"); ?>
<input type="text" name="name" id="name">
<input type="submit" value="submit" name="submit" id="submit">
<?php echo form_close(); ?>
All that happens currently is that I type in an input, updates the database and displays the view "test/default" (it doesn't refresh the page, but doesn't display "test/names_list" as desired. Many thanks in advance for any help, and for putting me out of my misery!
Set unique id to the form:
echo form_open('test/add', array('id'=>'testajax'));
I assume that you want replace a form with a view:
jQuery(document).ready(function(){
var $=jQuery;
$('#testajax').submit(function(e){
var $this=$(this);
var msg = $this.find('#name').val();
$.post($this.attr('action'), {name: msg}, function(data) {
$this.replace($(data));
});
return false;
});
better way if you return url of view in json response:
$.post("<?php echo base_url(); ?>test/add", {name: msg}, function(data) {
$this.load(data.url);
},"json");
from your last comment - I strongly not suggest to replace body, it will be very hard to support such code.
but here is anser:
$.post("<?php echo base_url(); ?>test/add", {name: msg}, function(data) {
$('body').replace(data);
});
i have a problem when it comes to retrieving value from jQuery to php.i was able to get the value of my select and pass it to my php but i can't pass it back to php.
here is the code...
<script>
$(document).ready(function()
{
$("select#months").change(function(event)
{
var m=$(this).val();
alert(m);
});
});
</script>
<div>
<select id="months">
<option value='00'>Month...</option>
<option value='01'>Jan</option>
<option value='02'>Feb</option>
<option value='03'>Mar</option>
<option value='04'>Apr</option>
</select>
<select id="years">
<?php
for($yr=10; $yr<=$year; $yr++)
{
echo "<option value='".$yr."'>".$years[$yr]."</option>";
}
?>
</select>
</div>
now i have to get the m variable from the jQuery code and echo it on my php.
You need to post or get the page again, passing "m" as a parameter and reading it inside php.
Php and jquery can communicate with each other only using http posts/gets, cause they run on two different computers (php on your server, jquery on your users browser)
Unfortunately, to answer this question completely would mean teaching client-server from the basics.
The jQuery code will run on your user's browser. You need to send m via POST (or GET) to your PHP script upon change.
Try this:
$(document).ready(function()
{
$("select#months").change(function(event)
{
var m=$(this).val();
$.ajax({
type: 'POST',
url: "http://example.lan/your.php",
data: {m: m},
success: function(){alert("updated")}
});
});
});
and on your PHP code, do something about m if it is set:
<?php
if (isset($_POST['m'])) {
// do stuff with M here
}
?>
PHP and Javascript may appear in the same file, but they are far from being executed by the same machine. For example, take this simple script :
<?php
$foo = "Hello world!";
?>
<div id="mydiv"><?php echo $foo; ?></div>
<script type="text/javascript">
$(function() { alert( $('#mydiv').text() ); });
</script>
When you access this script from your browser, the server actually only parse this :
<?php
$foo = "Hello world!";
echo $foo;
Because everything else is not PHP, thus not processed by the engine (skipped at parsing time). Therefore, the document that is uploaded by the server to your browser is
<div id="mydiv">Hello world!</div>
<script type="text/javascript">
$(function() { alert( $('#mydiv').text() ); });
</script>
As you see, at this point, there is no PHP at all in what's outputted by the server (what is received by the client), so there is no way that you can reference anything PHP at that point. The only way you can do this is by calling the same script again! (or any other PHP script)
PHP may receive parameters from external sources via $_GET and $_POST. Thus, modifying our code would be like
<?php
if (isset($_GET['foo'])) {
$foo = $_GET['foo']; // we received our param like
// '?foo=Hi!` from the HTTP request
} else {
$foo = "Hello world";
}
?>
<div id="mydiv"><?php echo $foo; ?></div>
<form action="" method="get">
<input type="text" name="foo" value="" />
<input type="submit" name="submit" />
</form>
<script type="text/javascript">
$(function() { alert( $('#mydiv').text() ); });
</script>
And you can communication in both directions. For XHR with jQuery, there is no need to send a whole bunch of HTML with the query, we need to modify the source a little:
<?php
if (isset($_GET['foo'])) {
echo "Message got : " . $_GET['foo'];
exit; // do not execute any more code from now
} else {
$foo = "Hello world";
}
?>
<div id="mydiv"><?php echo $foo; ?></div>
<script type="text/javascript">
$(function() {
alert( $('#mydiv').text() );
// note : assuming the code is in file "example.php"
$.get('example.php', {foo: "Hi!"}, function(data) {
alert(data); // will show "Response got : Hi!";
});
});
</script>
In the last example, the file is parsed and processed twice by the server, the code is actually executed in this order :
the browser makes a first query to the PHP script
the server parse the file and sends the HTML,
the client receives the HTML
the Javascript code is executed
alert : "Hello world!"
create and send a GET XHR with parameter foo=Hi!
the server receives another request and parse the file
the $_GET['foo'] argument is found
echo "Response got : Hi!"
the client receives the XHR response and invoke the callback function
alert : "Response got : Hi!"
Now, this last example may seem a bit more complicated, but really as simple as the other code :
<?php
$dataFile = 'data.txt';
if (isset($_POST['text'])) {
file_put_contents($dataFile, $_POST['text'];
echo "Saved!";
exit;
} else if (file_exists($dataFile)) {
$text = file_get_contents($dataFile);
} else {
$text = '';
}
?>
<a id="lnkSave" href="example.php">Save</a>
<script type="text/javascript">
var text = '<?php echo addslashes($text); ?>';
$(function() {
$('<textarea></textarea>').attr('id', 'text').appendTo(document).val(text);
$('#lnkSave').click(function() {
$.post($(this).attr('href'), {text:$('#text').val()}, function(data) {
alert(data);
});
});
});
</script>
I'll let you figure this one out; what it does and how it works.
I have been trying to create a simple calculator. Using PHP I managed to get the values from input fields and jump menus from the POST, but of course the form refreshes upon submit.
Using Javascript i tried using
function changeText(){
document.getElementById('result').innerHTML = '<?php echo "$result";?>'
but this would keep giving an answer of "0" after clicking the button because it could not get values from POST as the form had not been submitted.
So I am trying to work out either the Easiest Way to do it via ajax or something similar
or to get the selected values on the jump menu's with JavaScript.
I have read some of the ajax examples online but they are quite confusing (not familiar with the language)
Use jQuery + JSON combination to submit a form something like this:
test.php:
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript" src="jsFile.js"></script>
<form action='_test.php' method='post' class='ajaxform'>
<input type='text' name='txt' value='Test Text'>
<input type='submit' value='submit'>
</form>
<div id='testDiv'>Result comes here..</div>
_test.php:
<?php
$arr = array( 'testDiv' => $_POST['txt'] );
echo json_encode( $arr );
?>
jsFile.js
jQuery(document).ready(function(){
jQuery('.ajaxform').submit( function() {
$.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
dataType: 'json',
data : $(this).serialize(),
success : function( data ) {
for(var id in data) {
jQuery('#' + id).html( data[id] );
}
}
});
return false;
});
});
The best way to do this is with Ajax and jQuery
after you have include your jQuery library in your head, use something like the following
$('#someForm').submit(function(){
var form = $(this);
var serialized = form.serialize();
$.post('ajax/register.php',{payload:serialized},function(response){
//response is the result from the server.
if(response)
{
//Place the response after the form and remove the form.
form.after(response).remove();
}
});
//Return false to prevent the page from changing.
return false;
});
Your php would be like so.
<?php
if($_POST)
{
/*
Process data...
*/
if($registration_ok)
{
echo '<div class="success">Thankyou</a>';
die();
}
}
?>
I use a new window. On saving I open a new window which handles the saving and closes onload.
window.open('save.php?value=' + document.editor.edit1.value, 'Saving...','status,width=200,height=200');
The php file would contain a bodytag with onload="window.close();" and before that, the PHP script to save the contents of my editor.
Its probably not very secure, but its simple as you requested. The editor gets to keep its undo-information etc.