How to send select value to php using ajax? - javascript

i m trying to passe the value of the selected item from a select tag using ajax for that :
here it is the select tag(it is not in a form):
<select class="select" id="select" >
</select>
here it is the code that fill the select from the database using php:
$(document).ready(function(){
<?php foreach ($espace_ids as $row ) {?>
$('#select').append('<option value="<?php echo $row['espace_id']; ?>"><? php echo $row['nom']; ?></option>');
<?php }?> });
for sending data from the actual page to dashbored.php,here it is the code:
$("#select").change(function() {
$.ajax({
type: 'post',
url: "<?php //echo base_url(); ?>index.php?directeur/dashboard ?>",
data: espace_id: $("#select").val(),
success: function( data ) {
alert( data );
}
});
well i retrieve the value sent with :
$espace_id=$_POST['espace_id'];
the probleme that it display : undefined refrence to espace_id in dashboard.php.
well , the pupose is to load the espace info from the database according to the espace selected by the user.each time the user select an option i should load the appropiate info related to the espace selected.
i wish that you gonna help me.
thanks

You can use following example to get espace id in index.php.
$(document).ready(function ()
{
$('#select').on('change', function ()
{
if ($('#select').val() === null) {
alert("Error");
}
else
{
var selectedValue = $('#select').val();
$.ajax
({
url: 'index.php',
type: 'POST',
data: 'espace_id=' + selectedValue,
success: function(response)
{
alert(response);
}
});
}
});
});
on index.php
if(isset($_POST['espace_id']) && !empty($_POST['espace_id']))
{
// do whatever you want to do here!!
}

For those that want to keep it lighter than Jquery you could do something like this:
<select onchange="livesearch(this.value)"><option></option></select>
<script>
function livesearch(id){
xmlhttp = new XMLHttpRequest(); xmlhttp.open("GET","url?id="+id, false); xmlhttp.send(null); document.getElementById("searchresults").value=xmlhttp.responseText; }
</script>

Related

Show data immediately after insert to db mysql using codeigniter MVC

I have one text box and one button, after filling in the text box and then clicking the button, the data will be saved to mysql.
My question is, how do I when I click the save button, the ID of the data that I save will immediately appear on that page. I mean the ID of the data that just i insert into mysql
This is the view
<label for="userAnswer">Answer</label>
<textarea name="userAnswer" id="userAnswer" class="form-control"></textarea>
<button onclick="saveAnswer()">Submit Answer</button>
This is the js
function saveAnswer(){
var inputAnswer = $('#userAnswer').val();
$.ajax({
type: "GET",
url: GLOBAL_URL + '/Session/saveAnswer?&inputAnswer='+inputAnswer,
dataType: 'json',
});
}
This is the Controller
function saveAnswer(){
$data = array(
'id' => uuid(false),
'answer' => $this->input->get_post("inputAnswer")
);
$this->db->insert('tableAnswer', $data);
}
Thanks
Views File
add this code
<input type="text" id="id">
Controller File
After insert, add this code
echo json_encode(array("val"=> $data['id']));
Javascript
$.ajax({
type: "GET",
url: GLOBAL_URL + '/Session/saveAnswer?&inputAnswer='+inputAnswer,
dataType: 'json',
success: function(val){
document.getElementById("id").value = val.val;
}
});
Thats it...
use this code:-
function saveAnswer(){
var inputAnswer = $('#userAnswer').val();
$.ajax({
type: "GET",
url: GLOBAL_URL + '/Session/saveAnswer?&inputAnswer='+inputAnswer,
dataType: 'json',
sucess:function(result){
alert(result);
},
});
}
the result wll carry your id and it will be shown in alert box, and the returning of id from ajax use this code:-
function saveAnswer(){
$data = array(
'id' => uuid(false),
'answer' => $this->input->get_post("inputAnswer")
);
$this->db->insert('tableAnswer', $data);
$id = $this->db->insert_id;
if($id > 0){
echo $id;
}
}
if you get the result don't forget to tick it right, so other can get help
after insert your data, paste below line in modal
return $this->db->insert_id();
it will reflect last insert data ID
You have to echo the id and not return it to get it from Js
echo $this->db->insert_id();

How to get POST data using Jquery AJAX

I am trying to POST simple data using AJAX. My HTML code is
<input type="text" value="myvalue" id="sweet" name="sweet">
<button type="submit" id="mybtn-1">
My JQuery code is
$('#mybtn-1').click(function(){
var newSweet = $('#sweet').val();
if($.trim(newSweet) !== '')
{
$.ajax({
url:"../test_chat.php",
method:"POST",
data:{sweet:newSweet},
dataType:"text",
success:function(data){
$('#test_wrap').load("../test_chat.php").fadeIn("slow");
alert('Success');
}
});
}
});
And my test_chat.php code is
<?php
echo $_POST["sweet"];
echo 'hello';
?>
I want to echo the POST data in a div with the name "test_wrap". The problem is after clicking the button, I can only echo "hello" on the page.
I know it's happening because the load function is reloading the PHP file but I am looking for a solution so that I can show the POST data on my page.
You could return the data directly from your test_chat.php file after the post request, no need for double request here, return data like :
<?php
echo $_POST["sweet"];
echo 'hello';
?>
Then append it to the div #test_wrap like :
$('#mybtn-1').click(function(){
var newSweet = $('#sweet').val();
if($.trim(newSweet) !== ''){
$.ajax({
url:"../test_chat.php",
method:"POST",
data:{sweet:newSweet},
dataType:"text",
success:function(data){
$('#test_wrap').html(data).fadeIn("slow");
alert('Success');
}
});
}
});
Hope this helps.
You don't need to echo it with PHP, you can display it directly from the jQuery success callback:
$.ajax({
url: "../test_chat.php",
method: "POST",
data:{
sweet: newSweet
},
success: function(data) {
$('#test_wrap').load("../test_chat.php").fadeIn("slow");
if (data !== null && data !== undefined) {
alert('Success');
// Here "data" is whatever is returned from your POST
$("#some_content").html(data);
}
}
});
do ajax request of this way in js file:
$.ajax({
data: {keys: values}/*keys you need to post (sweet: newsweet)*/
, type: 'post'
, dataType: 'json'
, url: './php/someFile.php'
, error: function (jqXHR, status, err) {
console.log(jqXHR, status, err);
}
, success: function (response) {
/*use response to innerHTML into a div here*/
}
});
use echo json_encode in php:
<?php
echo json_encode($_POST["sweet"] /*or some value from function in php*/);/*of this way, you can return a response
from server to client, echo just print something, but does not return...*/
?>

How to use data from one HTML page to retrieve data to be used on another HTML page using ajax

I would like to use the 'sID' in the first HTML form to retrieve data from the database and then use the data retrieved from the database on the second HTML page. I can do this with just php, but I just can't figure out how to do it using ajax.
I'm really new to javascript/ajax so please be gentle with your answers :)
HTML 1
<div class="moreR">
<form action="moreR_2.0.php" method="GET">
<input type="hidden" name="sID[]" value="a_certain_ID"/>
<input type="image" src="Icons/PNG/greater_than.png" alt="submit"/>
</form>
</div>
PHP (moreR_2.0.php)
<?php
include ('session_start.php');
include ('db_connect_mO.php');
if (isset($_GET['sID'])) {
foreach($_GET['sID'] as $sID) {
}
}
$sql = mysqli_query($con, "SELECT * FROM mo WHERE sID=$sID");
$row = mysqli_fetch_array($sql);
while ($row = mysqli_fetch_assoc($sql))
{
$test[]= array(
'pZero'=> $row['pZero'],
'pZero_Gname'=> $row['gZero_key'],
);
}
header('Content-Type: application/json');
echo json_encode ($test);
//detailed error reporting
if (!$sql)
{
echo 'MySQL Error: ' . mysqli_error($db);
exit;
}
?>
JavaScript
$(document).ready(function() {
"use strict";
function connect2mR() {
$.ajax({
url:"moreR_2.0.php",
type: "GET",
data:'sID',
dataType:"json",
//async:false,
success:function(data)
{
$('#pZero').html('<img src="rPlanets/' + this.gZero + '.png" alt=""/>');
$('#pZero_keys').html(this.gZero_key);
}, //success
}); //end of ajax
} //end of function
if (window.attachEvent) {window.attachEvent('onload', connect2mR);}
else if (window.addEventListener) {window.addEventListener('load', connect2mR, false);}
else {document.addEventListener('load', connect2mR, false);}
});
HTML 2
<section class="moreR_section">
<div style="width:20%;"><div id="pZero"></div></div>
<div class="moreR_g" style="margin-left:26%" id="pZero_keys"></div>
</section>
What i'm trying to do is; start from HTML 1, collect sID -> then PHP/JS use sID from HTML 1 to get data from database -> then use the result from database on HTML 2. At the moment i'm struggling on how to make this process work. Can't figure out how to start from HTML 1 and end up in HTML 2.
You are not fetching the data from the input element at all.. change your ajax code to below.
$.ajax({
url:"moreR_2.0.php",
type: "GET",
data:{sID: $('input[name="sID[]"]').val()}, // this is the change
dataType:"json",
//async:false,
success:function(data)
{
$('#pZero').html('<img src="rPlanets/' + this.gZero + '.png" alt=""/>');
$('#pZero_keys').html(this.gZero_key);
}, //success
}); //end of ajax
Edit 1: you can use localstorage to save data and retrieve from there when ever required. So you can do as below
In your HTML 1 write this.
localStorage.setItem('sID', JSON.stringify( $('input[name="sID[]"]').val()));
And in HTML 2 you can access the value by reading it from the local storage like below,
var sIDofHTML1 = JSON.parse(localStorage.getItem('sID'));
You will have to update the ajax as below.
data:'sID', // this has to change to data:'sID='+sID,
$.ajax({
url:"moreR_2.0.php",
type: "GET",
data:'sID', // this has to change to data:'sID='+sID,
dataType:"json",
//async:false,
success:function(data)
{
$('#pZero').html('<img src="rPlanets/' + this.gZero + '.png" alt=""/>');
$('#pZero_keys').html(this.gZero_key);
}, //success
}); //end of ajax

Call function inside CodeIgniter's controller using jquery / ajax

Can somebody please explain to me what is the right way to call a php function with jquery / ajax in Codeigniter. Right now, this code isn't working and i cant figure out whay. Note that admin.php controler is inside admin map. Thanks in advance
html code
<form action="#" method="POST" id="change">
<input type="hidden" value="<?php echo $row->id_product; ?>" id="prod" >
<input type="submit" value="switch" >
</form>
<div class="resultdiv">
<?php echo $data; ?>
</div>
my function inside admin.php controller
public function do_search(){
$id = $this->input->post('id');
return $id;
}
Jquery AJAX script
$( "#change" ).submit(function() {
alert( "Change" );
var id = $('#prod').val();
$.ajax({
type:'POST',
url:'admin321/do_search',
data:{'id':id},
success:function(data){
$('#resultdiv').html(data);
}
});
});
Config / routes.php
$route['admin/do_search'] = "admin_controller/admin/do_search";
I know that this is old post, but maybe someone will find this usefull.
I solve this problem by adding index.php in url. Even if the index.php is hidden using rewrite.
$( "#change" ).submit(function() {
alert( "Change" );
var id = $('#prod').val();
$.ajax({
type:'POST',
url:'<?php echo base_url("index.php/admin/do_search"); ?>',
data:{'id':id},
success:function(data){
$('#resultdiv').html(data);
}
});
});
Maybe like this:
$( "#change" ).submit(function() {
alert( "Change" );
var id = $('#prod').val();
$.ajax({
type:'POST',
url:'<?php echo base_url("admin/do_search"); ?>',
data:{'id':id},
success:function(data){
$('#resultdiv').html(data);
}
});
});
You have to load this helper:
$this->load->helper('url');
#edit
$route['admin/do_search'] = "admin_controller/admin/do_search";
This code is unnecessary.
In the past, I have set up a route for the ajax request. Something like this:
$route['admin/search/(:any)'] = 'admin_controller/admin/do_search/$1';
Then my ajax request would look like this:
var prod = $('#prod').val();
$.ajax({
type: 'post',
url:'admin/search/'+prod
...
});
Or, you can grab the form action via jQuery and use that as your url.
<form action="admin/search/123" method="post">
$.ajax({
type: 'post',
url: $('form').attr('action')
...
});
I know this works. My routes file is the default.
I loaded CI URL helper in my controller __construct() function
$this->load->helper('url');
Here's my ajax:
/*
*Ajax function to load confirmation page
*/
var formID=$("div form");
formID.submit(function(event){ //activated on submit event
event.preventDefault(); //stops page from reloading
$.ajax({
type:"POST",
url:'<?php echo site_url("plan/process")?>',
data:formID.serialize(),
success:function(data){
$("div #msg_area").html(data);
window.setTimeout(function(){parent.location.reload()},3000);
}
});
});
I have multiple controllers so it calls the specific one call plan and the \n the function process. The process function one looks like this:
function process (){
$json_data = strtolower(json_encode($this->input->post()));
$res = array();
//Simple Error/success display...
$res = json_decode($this->plan->process_plan($json_data ),true);
if(array_key_exists('error',$res)){
$window = "warning";
$error=explode(":",$res['error']);
$result['message']="<h2><span class='color-dark'>Submission error:</span> ".$error[0]." </h2><p>".$error[1]."</p>";
}
else{
$window = "success";
$result['message'] = "<h2>Submission was a success</h2>";
}
echo $this->load->view("common/components/".$window,$result);
}
This works great for me. Hopefully it helps.
in your routes file you have: admin321/do_search NOT: admin/do_search
You can also try using the absolute path:
`http://www.website.com/admin/do_search` or `http://localhost/admin/do_search`
in the ajax url parameter

Ajax request when we click on the dropdown list element

Friends I created a drop-down list using the following code using js .
<script>
$('.menu').dropit();
</script>
<ul class="menu">
<li>
Product_name
<ul>
<? foreach($customer_details as $details){?>
<li><?echo $details->name;?></li>
<?}?>
</ul>
</li>
</ul>
The problem is that when the user clicks on the link of the dropdown list I need to send the result ie is the
$details->name
through an ajax request to a function in the controller (using codeignitor framework).Hoe this is done ??
JS SOURCE : http://codepen.io/anon/pen/Eoxhp
try this
$('.menu ul li a').on('click', function(e) {
e.preventDefault(); // prevent the link from triggering a pageload
var productName = $(this).html();
$.ajax({
type: "POST",
url: url, // the url you want to send it to
data: {name: productName },
success: function() {
// do whatever you need to do on success
}
});
});
on the server side you'll be able to access the product name using $_POST['name'];
You can try something like this...
// In your HTML replace the line with this
<li><a onclick="sendInfo(this);" href="#"><?echo $details->name;?></a></li>
// JS
function sendInfo(aEl){
var val = $(aEl).text();
$.ajax({
url : "your url",
data : {"name" : val}
}).done(function(){
// Success. Do something
});
}
This is an ajax request on change of drop down it works fine for me
i hope that it will also solve your problem.
<select name="all_users" id="all_users" onchange="Mehdi_ajax(this.value);">
<option value=""><?=$this->lang->line('global_all')?></option>
<?php if($all_users)
{
foreach($all_users->result() AS $item=>$val)
{
?>
<option value="<?=$val->uid?>"><?=$val->username?></option>
<?php
}
}
?>
</select>
script code:
<script type="text/javascript">
var surl = '<?=secure_xss()?>';
function Mehdi_ajax(id)
{
$.ajax({
type:"POST",
url: surl+"movable/jewelry/get_all",
data: "userid=" + id,
success: function(result){
$("#Mehdi_ajax").html(result);
}
});
}

Categories

Resources