updating combo values - php

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

Related

Cascading dropdown list in Codeigniter not working

In one of my View, i have a modal popup containing 2 dropdown lists (ddlPublications & ddlEditions).On page load, ddlPublications will be populated while ddlEditions will remain empty.However, ddlEditions will be populated on the onchange event of ddlPublications.
View
<div class="modal-body" style="height: 100%;">
<div class="col-md-12">
<div class="form-group">
<label>Publication</label>
<select id="ddlPublication" name="ddlPublication" class="form-control" onchange="load_editions(this.value)">
<option value="0">--select--</option>
<?php
foreach ($pub_data as $key => $pdata) {
?>
<option value="<?php echo $pdata['pub_id'];?>"> <?php echo $pdata['pub_title'];?> </option>
<?php
}
?>
</select>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label>Edition</label>
<div id="edn_div_data">
<select id="ddlEdition" name="ddlEdition" class="form-control">
<option value="0">--Select--</option>
</select>
</div>
</div>
</div>
</div>
<script>
function load_editions(pub_id){
alert(pub_id);
var p_id = pub_id;
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>pmachine/pages/get_editions/"+pub_id,
dataType: 'json',
success: function(result){
$("#edn_div_data").html(result);
},
error: function(result) {
$("#edn_div_data").html("Sorry, something went wrong");
}
});
}
</script>
CONTROLLER
public function get_editions($pubid)
{
$data['edn_data'] = $this->Process_pages_model->pop_editions($pubid);
echo json_encode($data);
}
Problem
ddlEditions is not getting populated.It shows the message 'Sorry, something went wrong'.Please suggest what's wrong with my code.
It's hard to tell what the issue could be here because I see several places it could be failing. First of all, make sure you have debugging on. You can use the built in profiler https://www.codeigniter.com/userguide3/general/profiling.html or I believe you can use xdebug with a little manual setup. Now let's debug.
Start by replacing url in your ajax request with an actual url. So replace
<?php echo base_url(); ?>pmachine/pages/get_editions/ with the actual url, something like
localhost/pmachine/pages/get_editions/
Try creating a simple ajax example to make sure you have a good handle on it. Here is a question about basic php/ajax examples that you can use for reference:
Basic PHP and AJAX
Try echoing $data['edn_data'] rather than just $data.
Echo a string rather than $data to make sure you're even getting a response.
print_r($this-> Process_pages_model->pop_editions($_POST['pubid'])); to make sure you're getting the info from the database. If you're not getting anything, make sure you're connecting to your database with a basic connection test:
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
print_r($_POST['pubid']); to make sure you're getting your post data
Try returning the data without encoding it as JSON and remove the
dataType:json from your ajax request.
try to change your ajax pist function and your controller like this:
$data['edn_data'] = $this-> Process_pages_model->pop_editions($_POST['pubid']);
Ajax call
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>pmachine/pages/get_editions/"
data: {pubid: pub_id},
dataType: "json",
cache:false,
success: function(result){
$("#edn_div_data").html(result);
},
error: function(result) {
$("#edn_div_data").html("Sorry, something went wrong");
}
});
Your ajax success function replace the whole 'edn_div_data', which I doubt you rebuild the DOM within the result.
Try to console.log the result, and assume the result is:
{"edn_data":[{"edn_id":"1","edn_title":"Edition 1"},{"edn_id":"2","edn_title":"Edition 2"},{"edn_id":"3","edn_title":"Edition 3"}]}
and replace your ajax success function become like:
success: function(result){
for (var i = 0; i <= result.edn_data.length - 1; i++) {
$("#ddlEdition").append("<option value='"+result.edn_data[i].edn_id+"'>"+result.edn_data[i].edn_title+"</option>");
}
},

Display MySQL queries on the same page

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 :

issue sending and retrieving value using ajax

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);
?>

ajax update to database

I am trying to add data to a database and for some reason it does not always work. I'd say 80% of the time it will work and I'll see the result in the database but sometimes its like the script won't run.
here is the ajax :
<script type="text/javascript">
$(document).ready(function () {
$(function () {
$('.error').hide();
$("#success").hide();
$(".button").click(function () {
$('.error').hide();
var name = $("input#name").val();
if (name == "") {
$("label#name_error").show();
$("input#name").focus();
return false;
}
$.ajax({
type: 'POST',
url: "class/proccess.php",
data: $("input#name"),
cache: false,
success: function () {
$("#success").fadeIn(200).show();
}
});
});
});
});
</script>
here is the html:
<div id = "contact_form">
<form name ="contact" action="">
<fieldset>
<label for="name" id="name_label">Name</label>
<input type="text" name="name" id="name" size="30" value="" class="text-input" />
<label class="error" for="name" id="name_error">This field is required.</label>
<br />
<input type="submit" name="submit" class="button" id="submit_btn" value="send" />
</fieldset>
<span id="success"> the name has been updated successfully!</span>
</form>
</div>
<div id ="upd"></div>
and here is the proccess.php file:
<?php
$va = $_POST["name"];
$dbconnection = mysql_connect('adatabase','someuser','somepw');
if(!mysql_select_db('some_database', $dbconnection)) {
echo mysql_error();
}
else
{
echo 'connection success';
}
$sql = "INSERT INTO some_db(text) VALUES ('$va')";
$result = mysql_query($sql) or die('erreur sql!'.mysql_error());
if(!$result) {
echo "not working";
}
else {
echo "working";
}
?>
so how come it does not always insert into the database?
and is there a way to get the result from the php if(!$result) to show in the success part of the ajax?
You're actually passing a jQuery-Object to your PHP-File.
$.post("class/proccess.php", {
name: $("input#name").val() //Pass val() not the whole jQuery-Object!
}, function() {
/* success */
});
While you're debugging, make sure MySQL errors are enabled.
In your Javascript for the Ajax success handler, show an alert with the text returned from the call. That way if there's an error with MySQL you'll see it.
Another thing is, could the "text" field be set in the database as UNIQUE? Trying to insert a new record with a duplicate string would fail in that case.
And... the name of the field isn't really 'text' is it? I would recommend avoiding field names that are the same as the basic data types for MySQL. Just to avoid confusion if no other reason.
If it is not working sometimes, you need to check the returned string for errors. The right way to do this using AJAX is as follows.
You can include a parameter in your success callback which will fetch the page-result from the PHP.
Instead of
success: function () {
...
}
use
success: function (data) {
alert(data);
}
Change your ajax call to:
$.ajax({
type: 'POST',
url: "class/proccess.php",
data: {name : $("input#name").val()},
cache: false,
success: function () {
$("#success").fadeIn(200).show();
}
So that $_POST['name'] is set to the value of your input box.
Also, as suggested, you should change your mysql functions to mysqli functions to help protect against sql injections.

Passing Data from form with Ajax

Wondering if someone could help me. I have next to no knowledge with Ajax, and after many attempts at trying to pass my User1_id and Text through to my insert.php I've had no luck with inserting the data I want to my database.
As my profile.php and insert.php stands, the form submits to the database, but when the user submits the form it navigates to the insert.php and would rather have the Ajax send the data and stay on the Profile.php at all times, I feel this is a much better approach when creating such functions.
I'm wondering if someone can guide me in the right direction on how I'd go about doing this.
Profile.php Form
<form id="FormId" action="" method="get">
<input type="hidden" value="<? echo $user1_id ?>">
<textarea placeholder="Whats New??" id="FormId" name="status"></textarea>
<input type="submit" name="Submit" value="Submit">
</form>
Insert.php
<?
session_start();
ini_set('display_errors',1);
error_reporting(E_ALL|E_STRICT);
include "db_connect.php";
if (isset($_GET['status'])) {
$status = $_GET['status'];
}
$user1_id=$_SESSION['id'];
if ($_GET['status']) {
$query = mysql_query("INSERT INTO feed (status,user1_id) VALUES ('$status', '$user1_id')") or die (mysql_error());
if($query){
echo "Posted Into Database";
}
exit();
}
?>
I know I need something similiar to this.. But I think I'm stuck more on the var/data part.
$("form#myFormId").submit(function() {
var mydata = $("form#myFormId").serialize();
alert(mydata); // it's only for test
$.ajax({
type: "GET",
url: "insert.php",
data: mydata,
success: function(response, textStatus, xhr) {
alert("success");
},
error: function(xhr, textStatus, errorThrown) {
alert("error");
}
});
return false;
});
But don't know how to go about it.
Any guidence is appreciated. Not asking anyone to write the code out for me. But good direction is welcomed.
Thanks.
Change your ajax part to:
$("form#myFormId").submit(function(e) {
e.preventDefault(); //prevent default submit
........
Your hidden input should have name
<input name="userId" type="hidden" value="<? echo $user1_id ?>">
And in php,
$userId = $_GET["userId"];
Change id of textarea, its same to your formid and ids need to be unique,
so change your textarea id, and You can try passing data as:
$.ajax({
type: "GET",
url: "insert.php",
data:"status="+$("#yourTextareaId").val()+"&userId="+$("#yourHiddenInputId").val(),
......
Just like to say thank you to both of you for your time and help. I re-wrote the code and have now got it working.
Here is the final code
PROFILE.PHP/JS
<script type="text/javascript">
function createstatus(content){
$.post("insert.php", { user1_id: content } );
refreshstream();
}
function createwallpost(content,user1_id){
$.ajax({
type: "POST",
url: "insert.php",
data: "status="+content+"&user1_id="+user1_id,
success: function(){
document.location = document.location;
}
});
}
</script>
<form action="insert.php" method="POST" target="ifr1" class="form_statusinput">
<input type="hidden" name="user1_id" value="<?php echo $user1_id ?>">
<input type="text" name="status" id="status" class="homescreen_status_input" placeholder="Say something">
<iframe name="ifr1" id="ifr1" style="display:none;"></iframe>
</form>
INSERT.PHP
<?
session_start();
include "db_connect.php";
if (isset($_POST['status'])) {
$status = $_POST['status'];
}
$user1_id = $_POST['user1_id'];
if ($_POST['status']) {
$query = mysql_query("INSERT INTO feed (status,user1_id) VALUES ('$status', '$user1_id')") or die (mysql_error());
if($query){
echo "Posted Into Database";
}
exit();
}
?>
I decided to go with post instead of the GET method, as I feel its securer and passes more information through smoothly.
Thanks again.

Categories