I've been searching for a while but nothing I've found match what I need.
I've got a form with 2 variables (dropdownlist) to query a DB (PHP and SQL).
Names of my variables are : "province" and "candidat".
My result page is action.php with all the sql/php code for the results.
Everything is going very fine except that after clicking on the submit button, a new page is opening : action.php with the results of my request.
Now, I wish to display this results on the same page as my form (id = form). The id of the div to display results is"success" (<div id="success">). There is an action on my form : action="action.php", should I remove it ?
I know that I have to use AJAX method but nothing that I've found match my needs. The other point is that I wish to be able to make another query and display the new results in this area.
If you know the solution or a tutorial that fit my needs... MANY THANKS of your help !
Start here: http://api.jquery.com/jQuery.ajax/
And do something along the lines of this:
$.ajax({
url: "action.php",
cache: false
}).done(function( response ) {
alert( response );
$("#success").html(response); //put the response into a DIV with id="success"
});
I'd recommend being more specific with your HTML id's that you are using.
$(document).ready(function(){
var datastring = "your data that is pass for php file";
$.ajax({
url: "action.php",
data: datastring,
type: "post",
success: function(response) {
alert(response);
}
});
});
Here's the code :
PROVINCE
">
<?php
}
?>
</select>
CANDIDAT
<?php
$result = mysql_query($query);
while($data = mysql_fetch_array($result))
{
?>
<option value="<?php echo $data['id_candidat']; ?>">
<?php echo $data['pren1']; ?> <?php echo $data['nom_candidat']; ?></option>
<?php
$id = $data['id_candidat'];
if ($id === $id)
{break;}
}
?>
</select>
<br/>
<input type="submit" class="submit" name="submit" value="ok" />
</form>
Content of action.php :
Related
I have this php script to count button clicks to a txt file
<?php
if (isset($_POST['clicks1'])) {
incrementClickCount1();
}
function getClickCount1() {
return (int) file_get_contents("count_files/clickcount1.txt");
}
function incrementClickCount1() {
$count = getClickCount1() + 1;
file_put_contents("count_files/clickcount1.txt", $count);
}
if (isset($_POST['clicks2'])) {
incrementClickCount2();
}
function getClickCount2() {
return (int) file_get_contents("count_files/clickcount2.txt");
}
function incrementClickCount2() {
$count2 = getClickCount2() + 1;
file_put_contents("count_files/clickcount2.txt", $count2);
}
?>
this is my html
<?php
include ('counter.php');
?>
<div class="count_right"><?php echo getClickCount1(); ?></div>
<div class="count_left"><?php echo getClickCount2(); ?></div>
<form action="counter.php" method="post" >
<button type="submit" class="vote_right" name="clicks1" ></button>
<button type="submit" class="vote_left" name="clicks2"></button>
</form>
What I'm trying or want to do is to update the counts on the divs but without refreshing the page.
I've tried using ajax but could not get the click value to show in the divs.
i thought about using text feilds insted, but dont realy know how.
This is a part of my jquery ajax code i used :
$('.vote_right, .vote_left').click(function(){
$.ajax({
url: 'counter.php',
type: 'post',
dataType:'html', //expect return data as html from server
data: $('.form1').serialize(),
});
});
I assume i made a bit of a mess, but thats why I'm here :)
EDIT
thanks guys, forgot to mention.. the code works but my problame is that its:
refreshes the page after submiting
not working when i use onSubmit="return false"
not displaying changes with e.preventDefault();
Add e.preventDefault(); to your click handler:
$('.vote_right, .vote_left').click(function(e){
e.preventDefault();
$.ajax({
url: 'counter.php',
type: 'post',
dataType:'html', //expect return data as html from server
data: $('.form1').serialize(),
});
});
You should use ajax.
Html
<?php
include ('counter.php');
?>
<div class="vote_right"><?php echo getClickCount1(); ?></div>
<div class="vote_left"><?php echo getClickCount2(); ?></div>
<form action="counter.php" method="post" >
<input type="button" class="vote_right" name="clicks1" >
<input type="button" class="vote_left" name="clicks2" >
</form>
jquery
$('.vote_right, .vote_left').click(function(){
class_count = $(this).attr("class");
count = $("."+class_count).text();
type = class_count == "vote_right" ? "right" : "left";
$.ajax({
url: 'counter.php',
type: 'post',
data: {"type": type,"count" : count},
success: function(data){
$("."+class_count).text(data);
}
});
});
In your php you will get which button it clicked by $_REQUEST["type"](left or right) and current count of this button by $_REQUEST["count"] . Add these lines at the top of your php file.
php
if(isset($_REQUEST["type"]){
if($_REQUEST["type"] == "right" )
$_POST['clicks1'] = "1";
else
$_POST['clicks2'] = "1";
}
It should done your work;
I have index.php with a form. When it gets submitted I want the result from process.php to be displayed inside the result div on index.php. Pretty sure I need some kind of AJAX but I'm not sure...
index.php
<div id="result"></div>
<form action="" id="form" method="get">
<input type="text" id="q" name="q" maxlength="16">
</form>
process.php
<?php
$result = $_GET['q'];
if($result == "Pancakes") {
echo 'Result is Pancakes';
}
else {
echo 'Result is something else';
}
?>
You really don't "need" AJAX for this because you can submit it to itself and include the process file:
index.php
<div id="result">
<?php include('process.php'); ?>
</div>
<form action="index.php" id="form" method="get">
<input type="text" id="q" name="q" maxlength="16">
<input type="submit" name="submit" value="Submit">
</form>
process.php
<?php
// Check if form was submitted
if(isset($_GET['submit'])){
$result = $_GET['q'];
if($result == "Pancakes") {
echo 'Result is Pancakes';
}
else {
echo 'Result is something else';
}
}
?>
Implementing AJAX will make things more user-friendly but it definitely complicates your code. So good luck with whatever route you take!
This is a jquery Ajax example,
<script>
//wait for page load to initialize script
$(document).ready(function(){
//listen for form submission
$('form').on('submit', function(e){
//prevent form from submitting and leaving page
e.preventDefault();
// AJAX goodness!
$.ajax({
type: "GET", //type of submit
cache: false, //important or else you might get wrong data returned to you
url: "process.php", //destination
datatype: "html", //expected data format from process.php
data: $('form').serialize(), //target your form's data and serialize for a POST
success: function(data) { // data is the var which holds the output of your process.php
// locate the div with #result and fill it with returned data from process.php
$('#result').html(data);
}
});
});
});
</script>
this is jquery Ajax example,
$.ajax({
type: "POST",
url: "somescript.php",
datatype: "html",
data: dataString,
success: function(data) {
doSomething(data);
}
});
How about doing this in your index.php:
<div id="result"><?php include "process.php"?></div>
Two ways to do it.
Either use ajax to call your process.php (I'd recommend jQuery -- it's very easy to send ajax calls and do stuff based on the results.) and then use javascript to change the form.
Or have the php code that creates the form be the same php code that form submits to, and then output different things based on if there are get parameters. (Edit: MonkeyZeus gave you specifics on how to do this.)
This is a cleaner code of my preview problem, the idea is to send and retrieve a value using ajax, but the value is not being sent nor ajax seems to work. I updated this code because this way it could be easily tested on any machine. First time using ajax. Here is the code:
Javascript
<script>
jQuery(document).ready(function() {
jQuery('#centro').click( function() {
$.ajax({
url: 'request.php',
type:'POST',
data: $("#form").serialize(),
dataType: 'json',
success: function(output_string){
alert(output_string);
$('#cuentas').html(output_string);
} // End of success function of ajax form
}); // End of ajax call
});
}
});
</script>
HTML:
<?php
$result = 'works';
?>
<form id="form">
<div id="centro">
Click here
<br>
<input type="hidden" name="centro" value="<?php echo $result; ?>">
</form>
<div id="cuentas">
</div>
PHP file, request.php
<?php
$centro = $_POST['centro'];
$output_string = ''.$centro;
echo json_encode($output_string);
?>
Looks like you never tell AJAX that the POST name is 'centro', try to change this:
data: $("#form_"+i).serialize(),
for this
data: { 'centro' : $("#form_"+i).serialize()},
I've run into the same problem with my ajax calls that I call via the POST method. My data was actually getting passed in the message body. I had to access it through the following method:
php://input
This is a read only wrapper stream that allows you to read raw data from the message body.
For more information on this wrapper visit this link.
Tray adding the following to your PHP file:
$centro = file_get_contents("php://input");
// Depending on how you pass the data you may also need to json_decode($centro)
echo json_encode($centro);
// See if you get back what you pass in
This read the message body (with my posted data) and I was able to access the value there.
Hope this helps.
try to using this code in your ajax post :
jQuery('#centro_'+i).click( function() {
$.ajax({
data: $("#centro_"+i).closest("form").serialize(),
dataType:"html",
success:function (data, textStatus) {
$('#cuentas').html(data);
alert(data);},
type:"post",
url:"load_cuentas.php"
});
});
Try this:
HTML
<?php
$i=0;
$f=0;
$consulta = $db->consulta("SELECT * FROM centro");
if($db->num_rows($consulta)>0){
while ($resultados1 = $db->fetch_array($consulta)){ ?>
<form id="form_<?php echo $f++; ?>"> //begin form with its id
<div class="centro" id="centro_<?php echo $i++; ?>">
<?php echo $resultados1['nombre_centro']; ?>
<br>
<input type="hidden" name="centro" value="<?php echo $resultados1['id_centro']; ?>">
<!--this is the data that is going to be sent. I set up a hidden input to do it.-->
</div>
</form>
<div id="cuentas" class="cuentas">
<!--where data is going to be displayed-->
</div>
<br>
<?php
}
}
?>
Javascript:
<script>
jQuery(document).ready(function() {
jQuery('.centro').on('click',function() {
var formElem=jQuery(this).closest('form');
jQuery.ajax({
url: 'load_cuentas.php',
cache: true ,
type:'POST',
dataType: 'json',
data: $(formElem).serialize(),
success: function(output_string){
jQuery(formElem).next('div.cuentas').html(output_string);
alert(output_string);
} // End of success function of ajax form
}); // End of ajax call
});
});
</script>
Server page:
<?php
include ('mysql.php');
$db = new mysql();
$centro = $_POST['centro']; //this is not getting any data. the whole ajax thing
$consulta = $db->consulta("SELECT * FROM cuenta WHERE id_center = '$centro'");
$output_string=array();
if($db->num_rows($consulta)>0){
while ($resultados1 = $db->fetch_array($consulta)){
$output_string []= 'test text';
}
}
mysql_close();
echo json_encode($output_string);
?>
I have a combo that simply displays some mysql databases. I also have a form that creates a database. I would like to dynamicly refresh the combo (if possible) to also display the new database created by the form. here is a snippet of the code:
<div id="tools">
<P>Add a Set list:<br>
<LABEL for="labelName">Set List Name: </LABEL>
<INPUT type="text" name="slName" id="slName"><button id="createSL" value="Create Setlist">Create Set</button>
</P><br>
<P>Delete a Set list:<br>
<? include("remSLcombo.php"); ?> <button href="#" type="button" id="delSl">Delete Setlist</button>
</P>
<p>Check how to reload combos</p>
</div><BR>
<? include("combo.php"); ?>
The Jquery function that is called to create the database:
$('#createSL').click(function(){
var sendIt = $("#slName").val();
$.ajax({
type: "POST",
url: "createSL.php",
data: {slName : sendIt},
error: function(e){
alert("The PHP Call failed! hmmm");
alert(e.status);
},
success: function(response){
alert(response);
}
});
$("#selcombo").load("combo.php");
$("#tools").hide().html(data).fadeIn('fast');
});
Combo.php:
<?php
echo '<select id="tunelist" name="tunelist" >';
$link = mysql_connect('localhost', 'setlist', 'music');
$query = mysql_query("SHOW DATABASES");
echo '<option>Select a Show</option>';
while ($row = mysql_fetch_assoc($query)) {
if ($row['Database'] == "information_schema"){}
elseif ($row['Database'] == "performance_schema"){}
elseif ($row['Database'] == "mysql"){}
else{
echo '<option value="'.$row['Database'].'">'.$row['Database'].'</option>';
}
}
echo '</Select>';
?>
How do I go about refreshing the values in the combo (made by combo.php) after a database is added using the form above?
Any help as always is greatly appreciated!
Loren
Try moving
$("#selcombo").load("combo.php");
to inside of your success function:
success: function(response){
alert(response);
if (response == true) // or something like this to ensure the success of the operation
$("#selcombo").load("combo.php");
}
What you have to do is to give back in createSL.php the code of the new combobox and loaded there.
This is your code
success: function(response){
alert(response);
}
Write something like:
success: function(response){
$('#tunelist').html(response);
}
Where the response is similar to Combo.php
My original goal was to get a php file to execute on a button press. I used ajax. When the javascript was in the view, it worked.
However, I tried to switch the javascript to its own .js file and include it in the header. It doesn't work anymore. I am confused.
the model code:
public function insert_build($user_id)
{
$query = "INSERT INTO user_structure (str_id, user_id) VALUES ('7', '$user_id')";
mysql_query($query) or die ('Error updating database');
}
Something interesting to note here is that when I include $user_id as a value, it completely negates my headertemplate. As in, it simply doesnt load. When I replace $user_id with a static value (i.e. '7') it works no problem.
This is my view code :
<div id="structures">
<h1>Build</h1>
<form name="buildForm" id="buildForm" method="POST">
<select name="buildID" class="buildClass">
<option value="0" selected="selected" data-skip="1">Build a Structure</option>
<?php foreach ($structures as $structure_info): ?>
<option name='<?php echo $structure_info['str_name'] ?>' value='<?php echo $structure_info['str_id'] ?>' data-icon='<?php echo $structure_info['str_imageloc'] ?>' data-html-text='<?php echo $structure_info['str_name'] ?><i>
<?php echo $structure_info['timebuildmins'] ?> minutes<br><?php echo $structure_info['buy_gold'] ?> gold</i>'><?php echo $structure_info['str_name'] ?></option>
<?php endforeach ?>
</select>
<div id="buildSubmit">
<input id ="btnSubmit" class="button" type="submit" value="Submit"/>
</div>
</form>
</div>
Heres my .js file :
$(".button").click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "<?php $this->structure_model->insert_build($user_id) ?>", //the script to call to get data
data: "", //you can insert url arguments here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
success: function(data) //on receive of reply
{
alert("success!");
}
});
});
I am almost sure I know the problem: That structure_model->insert_build($user_id) ?> doesn't work when its outside the view. Though, I dont know the alternative.
I excluded the header file. I confirmed that the .js file is indeed being directed to the correct path.
Could someone please explain the correct way to do this? Thank you!
Did you move your javascript to a .js that is being directly accessed by the browser? I.E: If you view source, so you see the <?php ... ?> in the javascript code?
To me, it sounds as though the PHP is not getting parsed. If this is not the case, then can you please clarify.
If you need to include PHP variables in your javascript, you should use CI to generate the JS page for inclusion. You can even create a View that is purely JS and call it like a normal page.
Otherwise, if you want to seperate the JS from CI, you should reference JS variables instead of PHP. Then in your CI page somewhere, define them with a <script>var jsVar = <?php echo phpvar(); ?></script> tag.
When you move the js file to it's own file, php variables will not be accessible anymore. You can either move the js code back to your view file, or fetch the url through javascript. See below for example.
HTML:
<div id="structures">
<h1>Build</h1>
<form name="buildForm" id="buildForm" method="POST">
<input type="hidden" name="url" value="<?php $this->structure_model->insert_build($user_id) ?>" />
<!-- Rest of your code -->
</form>
</div>
Javascript:
$(".button").click(function(e){
var form_url = $(this).closest('form').find('input[name=url]').val();
e.preventDefault();
$.ajax({
type: "POST",
url: form_url, //the script to call to get data
data: "", //you can insert url arguments here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
success: function(data) //on receive of reply
{
alert("success!");
}
});
});