Send and recieve parameter with ajax using jquery - php

I'm tring to send and receive parameters with AJAX without any sucess
First I choose AREA and than the CITIES in this area.
Can you please tell me what do I do wrong?
Client side:
<script>
$(document).ready(function(){
$("#first").click(
function(){
var area_id=$("#area_id").val();
$.ajax({
type: "POST",
url: "recs.php",
data: "area_id="+area_id,
cache:false,
success:
function(data){
$("#second").html(data.message);
}
});
return false;
});
});
</script>
<form method="post" action="tosomewhere.php">
<select id="first" name="area_id">
<option value="1">1</option>
<option value="2">2</option>
</select>
<select id="second" name="section"> </select>
</form>
Server Side:
$areaID = $_POST['area_id'];
$second_option = "";
$query2 = mysql_query("SELECT * FROM `cities` WHERE area_id = $areaID ORDER BY id ASC");
while($index = mysql_fetch_array($query2))
{
$id = $index['id'];
$name = $index['name'];
$second_option .= "<option value='$id'>$name</option>";
}
echo $second_option;
exit;
Thank you in advanced
After editing:
I changed the code to something even simpler:
Client side:
<script>
$(document).ready(function(){
$("#first").click(
function(){
var area_id=$("#area_id").val();
$.ajax({
type: "GET",
url: "recs.php",
data: "area_id="+area_id,
cache:false,
success:
function(data){
$("#second").html(data);
}
});
return false;
});
});
</script>
<form method="post" action="tosomewhere.php">
<select id="first" name="area_id">
<option value="1">1</option>
<option value="2">2</option>
</select>
<div id="second"></div>
</form>
Server side:
some text
I'm still not getting the string into

change
$("#second").html(data.message);
to
$("#second").html(data);

<script>
$(document).ready(function(){
$("#first").click(function(){
var area_id=$("#area_id").val();
$("#second").load('tosomewhere.php?area_id=' + area_id);
return false;
});
});
</script>
Changed the jquery a bit. Using GET.
Also the script has changed:
$areaID = (int) $_GET['area_id'];
$second_option = "";
$query2 = mysql_query("SELECT * FROM `cities` WHERE area_id = '$areaID' ORDER BY id ASC");
if (mysql_num_rows($query2) > 0){
while($index = mysql_fetch_array($query2)){
$second_option .= '<option value="'.$index['id'].'">'.$index['name'].'</option>';
}
echo $second_option;
} else {
echo 'No result!';
}
die();
Added (int) before $_GET as a pre-security measurement.

Add this parameter to the ajax function
dataType:'text'

You need to debug code where is actually fault whether you ajax call is actually initialize.
i: check whether value properly fetch in "area_id" js variable
alert(area_id);
ii: if it ok check whether data proper returned from server scriptinog
alert(data); or alert(data.message);
iii: for testing whether you receive data properly, just send out test script.
echo "sample text";
exit;
or try to send data in json format
die('{"message" : "sample text"}');
If all three steps working, then there should be fault in data access script.
If you are not getting output in ajax try using firebug to check what is actually happening in sending request and getting response.

Related

How to implement a code igniter country and cities select that countries determines the city?

I am new to Ajax and JavaScript
I have a similar problem with my selects that depends on the other select but don't know where it is going wrong?
This is my Controller code- that passes the member_id to the model and it is supposed to return data back to the view selected.
public function getStates() {
$this->load->model('ReferenceModel');
$this->load->model('DailyModel');
$this->load->model('MembersModel');
$this->load->model('FundsModel');
$postData = array('member_id' => $this->request->getPost('member_id'));
$dataa = $this->FundsModel->getStates($postData);
echo json_encode($dataa);
}```
This is my AJAX Request Code
<script type='text/javascript'>
// baseURL variable
var baseURL= "<?php echo base_url();?>";
$(document).ready(function(){
// City change
$('#member_id').change(function(){
var member_id = $(this).val();
// AJAX request
$.ajax({
url:'<?=base_url()?>Historic/getStates',
method: 'post',
data: {member_id: member_id},
dataType: 'json',
success: function(response){
// Remove options
$('#id').find('Select Member').not(':first').remove();
// Add options
$.each(response,function(index,data){
$('#id').append('<option value="'+dataa['id']+'">'+dataa['fund']+'</option>');
});
}
});
});
});
</script>
Model
public function getStates($postData){
$sql = 'SELECT * FROM vw_funds_summary WHERE member_id =' .$postData['member_id'] ;
$query = $this->db->query($sql);
return $query;
}```
And My HTML Codes
<select id="member_id" name="country" class="form-control">
<option>Select Member</option>
<?php
for ($i=0;$i<$fMembers->num_rows();$i++){
echo "<option value='".$fMembers->row($i)->member_id."'>".$fMembers->row($i)->member_name."</option>";}
?>
</select>
<select class="form-control" id="id">
<option>Select Fund</option>
</select>
What is really wrong with my Code?
I have a view of both the funds and the members, that are giving the results as shown in the attached picture.
Or is there another way to do it without having to use AJAX?

Populate <select> on click using AJAX and PHP

I have a <select> with only one option, i want to get the rest of the options from a database using PHP and then populate said <select> with the PHP result using AJAX.
Unfortunately my code is not working, im not surprised as im new to both AJAX and jQuery but i dont get any errors to guide myself through the issue.
The PHP works as expected because its used in another part of the site and i have no issues with it so my error must be in the AJAX (no big surprise here).
Below my HTML:
<select class="custom-select my-1 mr-sm-2" id="producto" name="producto" required>
<option disabled selected value>Elegir...</option>
</select>
Below my AJAX code:
<script type="text/javascript">
$(document).ready(function() {
$("#producto").click(function() {
$.ajax({
url: 'fetch_lista_productos_compra.php',
type: 'get',
success: function(data) {
$("#producto").append(data);
}
});
});
});
</script>
Below my PHP code:
<?php
require $_SERVER['DOCUMENT_ROOT'].'/testground/php/db_key.php';
$conn = mysqli_connect($servername, $username, $password, $dbname);
$sql_query = mysqli_query($conn, "SELECT * FROM productos WHERE disponibilidad = 'disponible'");
while ($row = mysqli_fetch_assoc($sql_query)) {
$titulo = $row['titulo'];
echo <<<EOT
<option value="$titulo">$titulo</option>\n
EOT;
}
?>
As always any kind of help is greatly appreacited and thanks for your time.
IMPORTANT EDIT
<select> has a duplicated id, perhaps i should i have stated this from the start as i know think thats whats causing my issue.
The fact is that in this <form> the selects are created dynamically on user request. They click on Add product and a new select with the products avaiable is created, i know the id/name of said input must have [ ] (id="producto[]") for it to be converted into an array but i dont know how to make the AJAX deal with this dynamically created reapeated selects issue. I apologise for this belated aclaration i realise now it is of the utmost importance.
You have to edit your response from this:
<?php
require $_SERVER['DOCUMENT_ROOT'].'/testground/php/db_key.php';
$conn = mysqli_connect($servername, $username, $password, $dbname);
$sql_query = mysqli_query($conn, "SELECT * FROM productos WHERE disponibilidad = 'disponible'");
while ($row = mysqli_fetch_assoc($sql_query)) {
$titulo = $row['titulo'];
echo <<<EOT
<option value="$titulo">$titulo</option>\n
EOT;
}
?>
To this:
<?php
require $_SERVER['DOCUMENT_ROOT'].'/testground/php/db_key.php';
$conn = mysqli_connect($servername, $username, $password, $dbname);
$sql_query = mysqli_query($conn, "SELECT * FROM productos WHERE disponibilidad = 'disponible'");
$response = '';
while ($row = mysqli_fetch_assoc($sql_query)) {
$titulo = $row['titulo'];
$response .= '<option value="' .$titulo . '">' . $titulo . '</option>'; //Concatenate your response
}
echo $response;
?>
But i suggest to use JSON to get a response and parse it on client side.
You can do this by pushing all values in to response array and use json_encode(). At the end you get straight response from the server with just a values, and append thous values whatever you need on client side.
Update
Also you append data to your existing select options. You can just add thous by editing this:
<script type="text/javascript">
$(document).ready(function() {
$("select#producto").focus(function() { //Change to on Focus event
$.ajax({
url: 'fetch_lista_productos_compra.php',
success: function(data) {
$("select#producto").html(data); //Change all html inside the select tag
}
});
});
});
</script>
Test result:
$('select#options').focus(function(){
alert("Hello this is a select trigger");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="options">
<option value="test">Test</option>
</select>
Please don't construct your html on the server, try to just send the raw data and then construct the html client-side, it's better that way and it leaves room for changing the view later without much coupling.
That said, instead of doing:
while ($row = mysqli_fetch_assoc($sql_query)) {
$titulo = $row['titulo'];
echo <<<EOT
<option value="$titulo">$titulo</option>\n
EOT;
}
just do
$rows = [];
while ($row = mysqli_fetch_assoc($sql_query)) {
$rows[] = $row;
}
//this is your best bet when sending data from PHP to JS,
//it sends the rows as JSON-like string,
//which you'll parse to an array in the client
echo json_encode($rows);
then in the client
$.ajax({
url: 'fetch_lista_productos_compra.php',
type: 'get',
success: (data /*json-like string*/) => {
const dataAsArray = JSON.parse(data);
$.each(dataAsArray, (index, row) => {
//now HERE you construct your html structure, which is so much easier using jQuery
let option = $('<option>');
option.val(row.titulo).text(row.titulo);
$("#producto").append(option);
});
}
});
Regarding your edit about several selects
I don't have access to your server of course so I'm using a mock service that returns JSON. IDs are dynamically generated and all data loading occurs asynchronously after you click on the button.
Try using your url and modify the success function according to your html.
$(document).ready(function() {
$('#add').click(() => {
//how many so far...?
let selectCount = $('select.producto').length;
const select = $('<select class="producto">');
select.attr('id', `producto${selectCount + 1}`);
//then we fetch from the server and populate select
$.ajax({
url: 'https://jsonplaceholder.typicode.com/posts',
type: 'get',
success: function(data) {
data.forEach((d) => {
const option = $('<option>');
option.val(d.id).text(d.title);
select.append(option);
});
}
});
document.body.appendChild(select[0]);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id='add'>Add product</button><br>
<!--<select class="custom-select my-1 mr-sm-2" id="producto" name="producto" required>
<option disabled selected value>Elegir...</option>
</select>-->
HIH
As it turns out the code in the question was actually working properly, the problem was not the code itself but the fact that, as i stated (sadly on a later edit and not right from the start) in the question, there where more than one <select> using the same id, therefore everytime the AJAX was executed the result was appended to the first <select> only, and it was appended over and over again everytime i clicked it, my solution was unifiying both the AJAX that populated the <select> and the jQuery that created the said dynamic <select>'s all in one script thus solving all of my issues at once.
Below my jQuery/AJAX code:
<script type="text/javascript">
$(document).ready(function() {
var max_fields = 10;
var wrapper = $(".input_fields_wrap");
var add_button = $(".add_field_button");
var x = 0;
$(add_button).click(function(e) {
e.preventDefault();
$.ajax({
url: '/testground/php/fetch_lista_productos_compra.php',
type: 'get',
success: function(data) {
if(x < max_fields) {
x++;
var html = '';
html += '<div class="form-group row" id="inputFormRow" style="margin-bottom: 0px;">';
html += '<label class="col-3 col-form-label font-weight-bold">Producto</label>';
html += '<div class="col-7">';
html += '<select class="custom-select my-1 mr-sm-2" id="producto" name="producto[]" required>';
html += '<option disabled selected value>Elegir...</option>';
html += data;
html += '</select>';
html += '</div>';
html += '<div class="col-1 my-auto" style="padding: 0px 0px 0px 0px;">';
html += '<button id="removeRow" type="button" class="btn btn-danger">X</button>';
html += '</div>';
html += '</div>';
$(wrapper).append(html);
}
}
});
});
$(document).on('click', '#removeRow', function () {
$(this).closest('#inputFormRow').remove(); x--;
});
});
</script>
I want to thank everyone that took the time to help me out with this Swati, Serghei Leonenco and Scaramouche, this community is truly amazing.
<script type="text/javascript">
$(document).ready(function() {
$("#producto").change(function() {
$.ajax({
url: 'fetch_lista_productos_compra.php',
type: 'get',
success: function(data) {
console.log(data)
// $("#producto").append(data);
}
});
});
});
</script>`enter code here`
try run this and check in your console that weather you are receiving the data from your php or not.

If checkbox is checked in php

I have use the following code
order.php
<script type="text/javascript">
function processForm() {
$.ajax( {
type: 'POST',
url: 'ajax.php',
data: { checked_box : $('input:checkbox:checked').val()},
success: function(data) {
$('#results').html(data);
}
} );
}
</script>
<input type="checkbox" name="checked_box" value="1" onclick="processForm()">
And ajax.php
<?php
include "config.php";
$checkbox = intval($_POST['checked_box']);
echo $checkbox;
if($checkbox == 1){
$Query="SELECT * FROM `order` ORDER BY sl_no DESC";
}else{
$Query="SELECT * FROM `order` ORDER BY sl_no ASC";
}
$result=mysql_query($Query);
echo $Query;
while($row = mysql_fetch_object($result)) {
?>
It works good but when I unchecked then error showing
Notice: Undefined index: checked_box in C:\xampp\htdocs\website\admin\ajax.php on line 24
How to avoid this error???
It is not an error, but a notice. You will get that kind of notices if you try to access non initialized variables. Just initialize it with the appropiate start value.
The tricky part in your code is that you assume you'll get the value of the checkbox because it is included in the form. But it happens that the checkbox are not sent UNLESS THEY HAVE BEEN CHECKED.
Instead of intval($_POST['checked_box']); use isset($_POST['checked_box']); to make sure the value exists at all.
After that you can use intval if you still need that value.
It's all because only checked checkboxes are included in POST request. So you need to check if your checked_box key exists to figure out checkbox was set or not:
if(isset($_POST['checked_box']) {
.. set
} else {
.. not set
}
I have a select dropdown box
<select name="status" id="status" onchange="changeStatus()">
<option value="step_1">step_1</option>
<option value="step_2">step_2</option>
<option value="step_3">step_3</option>
<option value="step_4">step_4</option>
</select>
And my javascript
<script>
function changeStatus() {
$('select.changeStatus').change(function(){
$.ajax({
type: 'POST',
url: 'update_status.php',
data: {changeStatus: $('select.changeStatus').val()},
dataType: 'html'
});
});
});
</script>
So I want the value selected from the select dropdown box send to the php file(update_status.php)

Ajax calling PDO function in PHP class to update a page

I have a list of files and a drop down box, I'd like the user to be able to filter them by various categories etc.
I have a php class that has the function for creating the sql query and returning the result. I'd very much like to do this via ajax to prevent a refresh.
I'm stuck and was hoping for some help.
The problem is that I don't know what to do next. This is pretty new to me but still plenty foreign. If the ajax call can be run onKeyUp from the select then even better.
Thank you for any help:
the HTML:
<div>
<form action="" method="post" name="orderBy">
<label for="orderBy" id="orderBy">Order By:</label>
<select>
<option class="orderByOption" value="newest">Newest First</option>
<option class="orderByOption" value="oldest">Oldest First</option>
<option class="orderByOption" value="cat">Category</option>
<option class="orderByOption" value="alpha">Aphabetical</option>
<option class="orderByOption" value="fileType">Filetype</option>
</select>
<label> </label>
<input type="submit" class="orderByTrainingButton" name="submit" value="Go!"/>
</form>
</div>
The Ajax:
//form for changing the ordering of items in training all docs
$(function(){
$(".orderByTrainingButton").click(function(){
//validate and process
//get vlaue
var option = $(".orderByOption").val();
var params = {option: option};
$.ajax({
type: "POST",
url: "../trainingOrderByAjax.php",
data: params,
dataType: 'json',
success: function(data){
if(data.success == true){
//aaaannnd. stuck/
}else{
// shouldn't ge there...I hope.
}
},
error: function( error ) {
console.log(error);
}
});
});
});
The php the ajax will call:
<?php
include_once('core/init.php');
if($_POST){
$orderBy = $_POST['orderByOption'];
if($training->getAlFilesOrderBy($orderBy)){
$data['success'] = true;
}else{
$data['success'] = false;
}
echo json_encode($data);
}
To start with ordering by desc or asc would be great. I can then build on that.
Something like this.
PHP:
if($results = $training->getAlFilesOrderBy($orderBy)){
$data['success'] = true;
$data['results'] = $results;
}else{
$data['success'] = false;
}
echo json_encode($data);
}
JS:
if(data.success){
var results = data.results;
for (var i = 0; i < results.length; i++) {
// do something with results[i]
}
}else{
// shouldn't ge there...I hope.
}
Change your AJAX error handler to:
error: function(xhr, status, errorMsg) {
console.log("AJAX error: " + errorMsg);
}

Triggering JSON request from 'click' event in a selector box using Mootools

Im trying to trigger an asynchronous JSON request when I select an option from an HTML selector box using mootools.
I have the following form element:
<form method="post" id="sel">
<select id = "_selecor_id" size=3>
<option value = "value_a" id = "option_a">OptionA</option>
<option value = "value_b" id = "option_b">OptionB</option>
</select>
<p id="response"></p>
</form>
I'm using the following javascriipt/mootools to send a JSON request carrying the form info
window.addEvent('domready', function()
{
$('_selecor_id').addEvent('click', function(){
new Request.JSON({
url: "my_php_script.php",
onSuccess: function(response)
{
$('response').set('html', response.params)
}
}).get($('sel'));
})
});
to the following php script
$result['params'] = $_GET;
echo json_encode($result);
However, I'm told in Chrome's developer tools 'cannot read property "params" of null'
I don't see why request should be 'null' here.
Any ideas would be greatly appreciated
Hey man the answer to your question is in the question itself.
Your triggering the event when you are clicking on the select when like you said "select an option"
Click on the select would be wrong, however so would click on an option with in the select what your looking for is the onChange event the code would be as follows:
HTML
// Notice no form tag needed unless you are serializing other items
<select id = "_selecor_id" size=3>
<option value = "value_a" id = "option_a">OptionA</option>
<option value = "value_b" id = "option_b">OptionB</option>
</select>
<p id="response"></p>
JAVASCRIPT
window.addEvent('domready', function(){
$('_selecor_id').addEvent('change', function(){
new Request.JSON({ // This must return a valid json object
url: "my_php_script.php",
data: {
'value': this.get('value')
}
onSuccess: function(responseJSON, responseText){
$('response').set('html',responseJSON.params);
}
}).send();
})
});
PHP
$result['params'] = isset($_GET['value']) ? $_GET['value'] : 'Not Set';
echo json_encode($result);
The responseJson variable will now contain something like {"params":"value_b"}
Try this code:
window.addEvent('domready', function(){
$('_selecor_id').addEvent('click', function(){
new Request.JSON({
url: "my_php_script.php",
onSuccess: function(response){
$('response').set('html',(response || this.response || this.responseText || {params: ''}).params)
}
}).get($('sel'));
})
});

Categories