Chained AJAX dropdown (select) jquery - javascript

So, recently I have been dabbling a bit in cakephp but I have run into an issue I just can't seem to solve. I suspect it's something simple I'm missing (as most cases).
The premise of what I'm trying to do is somewhat self-explanatory in the title: I have a view (my add.ctp) within this add I have a form created with the form helper.
I have multiple selects, the first select is a list of companies. Once the company has been selected, I now want to update the next select based on the selected value using jquery and ajax sending a get request to the controller.
The AJAX request completes successfully however, I cannot seem to access the desirable returned data (a list of projects that belong to the selected company).
To be clear I'm trying to return an array in the success callback
I have read a lot and searched around, but I feel that maybe examples are lacking for v3 cakephp.
Some of my code :
Controller
$projectphase = $this->Projectphases->newEntity();
$data = ['content' => 'hi', 'error' => 'nothing found'];
$projects = array('0' => 'Select something');
if($this->request->is('ajax')){
$company_id = $this->request->data('company_id');
$projects = $this->Projectphases->Projects->find('list', ['limit' => 2, 'conditions' => ['company_id' => $company_id]]);
$arr = array();
$arr = $this->chainedProjects($company_id);
$data = ['content' => 'hello', 'error' => ''];
$this->set(compact('projects', 'data'));
$this->set('_serialize', ['projects', 'data']);
}elseif($this->request->is('post')){
debug("hit post");
die();
}
Public function chainedProjects
$projects = $this->Projectphases->Projects->find('list', ['limit' => 2, 'conditions' => ['company_id' => $id]]);
$projs = $projects->toArray();
$values = array();
$x = 0;
foreach ($projs as $key => $value) {
$values[$x] = "<option value='$key'>$value</option>";
$x++;
}
return $values;
Javascript [jquery ajax]
$(document).ready(function(){
$('#company').change(function () {
$company_id = $('#company').val();
var data = {
'type' : 'dropdown',
'company_id' : $company_id
};
$.ajax({
type : 'GET',
//url : 'delegate1/projectphases/add',
data : data,
encode : true,
beforeSend: function(xhr){
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
},
success: function(response){
console.log('success');
console.log(response.content);
console.log(response.message);
//console.log(data.response);
//console.log(result.content);
console.log(response);
}
}).done(function(){
console.log('done');
})
});
})
Jquery 2.1.3
Any help whatsoever will be appreciated!

Related

method : "DELETE" in ajax cause *Failed to load resource: net::ERR_HTTP2_PROTOCOL_ERROR* error in the console

I am a little bit confused that what is happening here.
In my case, I want to delete the dynamically loaded record on my page so I passed the id from ajax to PHP like this
$(document).on("click" , "#delete_button" , function(){
const id = $(this).attr("data-delete_user_id");
$.ajax({
url: "api/deleteUser.php",
method: "DELETE",
data : JSON.stringify({id}),
success: function (data) {
const res = JSON.parse(data);
console.log(res);
}
});
})
and simply log the response into the console after deleting the record from the database.
Hence, the console shows me DELETE https://hamza786504.000webhostapp.com/admin-user-test/api/deleteUser.php net::ERR_HTTP2_PROTOCOL_ERROR error as you can see in the image below.
Here is the code inside of api/deleteUser.php.
<?php
include_once("config.php");
$json = file_get_contents('php://input');
$data = json_decode($json , MYSQLI_ASSOC);
if(isset($json)){
session_start();
if($_SESSION["user_id"] !== $data["id"]){
$user_id = $data["id"];
$sql = "DELETE FROM users WHERE user_id = {$user_id}";
if(mysqli_query($con , $sql)){
echo json_encode(["status" => "200" , "message" => "record deleted successfully!"]);
}else{
echo json_encode(["status" => "404" , "message" => "user not found"]);
}
}else if($_SESSION["user_id"] == $data["id"]){
echo json_encode(["status" => "404" , "message" => "Sorry, You can not delete your own account"]);
}
}
?>
We also don't have api folder and deleteUser.php file in our source tab but the payload (in our case payload is id)is being passed to it but and nothing comes in the response more than an error.
This picture would more clear the think
Alright, this was the issue I was facing until I use the method: "POST" in ajax call. As soon as I change the method from "DELETE" to "POST" it started working. Like this:
$(document).on("click" , "#delete_button" , function(){
const id = $(this).attr("data-delete_user_id");
$.ajax({
url: "api/deleteUser.php",
method: "POST",
data : JSON.stringify({id}),
success: function (data) {
const res = JSON.parse(data);
console.log(res);
}
});
})
The output in the console is
As we already know that the DELETE method is specially used when we want to delete the record, but in my case, why DELETE method is not suitable to delete the user from the database?
Why I had to use the 'POST' method to avoid this issue?

Using ajax to pass javascript array to a controller in codeigniter to use with a function

I have a form with a submit button. When clicked, it adds listed elements to an array.
$("#submitButton").click(function(){
var selection = $("#selectedList li");
var families_selection = [];
selection.each(function() {
families_selection.push($(this).text().replace(/Remove/,''));
});
});
I want to use the array "families_selection" in the controller "Provider", so I can use the following function and instert the values in a database.
$this->Proveedormodel->add_uk_proveedor_familia($idProveedor, $families_selection);
EDIT: I get the value for $idProveedor in the controller, not in the view, using another function in the same "Proveedor" model.
$idProveedor = $this->Proveedormodel->get_idConsecutivo();
This is how I insert the values in the database in my model.
function add_uk_proveedor_familia($id, $params){
foreach($params as $clave){
$this->db->select('id')->from('familia')->where('clave', $clave);
$valor = $this->db->get();
$vl = $valor->row_array();
$familia = $vl['id'];
$this->db->insert('relacionproveedorfamilia', array(
'idProveedor' => $id,
'idFamilia' => $familia
));
}
}
How can I use ajax to pass this array to the controller and use the function I need?
Edited code using Dragan Valjak's response. Now it works!
View add.php
$("#botonGuardar").click(function(){
var seleccion = $("#listaSeleccion li");
var familias_seleccion = [];
seleccion.each(function() {
familias_seleccion.push($(this).text().replace(/Quitar/,''));
});
$.ajax({
url: 'Proveedor/crearRelacion',
method: 'POST',
data: {familias_seleccion: familias_seleccion}
});
});
Controller Proveedor.php
function crearRelacion(){
$this->load->model('Proveedormodel');
$familias_seleccion = $this->input->post($data);
$idProveedor = $this->Proveedormodel->get_idConsecutivo();
$this->Proveedormodel->add_uk_proveedor_familia($idProveedor, $familias_seleccion);
}
Model Proveedormodel.php
function add_uk_proveedor_familia($id, $params){
foreach($params as $clave){
$this->db->select('id')->from('familia')->where('clave', $clave);
$valor = $this->db->get();
$vl = $valor->row_array();
$familia = $vl['id'];
$this->db->insert('relacionproveedorfamilia', array(
'idProveedor' => $id,
'idFamilia' => $familia
));
}
}
$.ajax({
url: 'Provider/functionName',
method: 'POST',
data:
{
families_selection: families_selection
}
});
In Controller
function functionName($data){
$families_selection = $this->input->post($data);
$idProveedor = $this->Proveedormodel->get_idConsecutivo();
$this->Proveedormodel->
add_uk_proveedor_familia($idProveedor,$families_selection);
}
You create your route to handle the ajax, something like '/family_selection' then you can pass your data that you have stored in a post method such as:
$.ajax({
url: '/family_selection',
method: 'POST',
data: {family_data: variable_of_data_you_stored}
});
I'm not familiar with codeigniter but I think you would need to set up a route "something like" $route['family_selection']['post'] = '/family_selection';
In python I would set it up in my controller like so:
Maybe you can use it as an example and implement something similar in codeigniter
#root_resource.route('/family_selection', methods=['POST'])
def family_selection():
family_details = request.form['family_data']
#then I would do whatever it is I want to do with the data...
#then I may or may not want to return an empty response.
return Response(status=http.HTTPStatus.NO_CONTENT)
concentrate on your requirement id and family_data
$.ajax({
url: "Proveedormodel/add_uk_proveedor_familia",
type: 'POST',
data:
{
family_data: variable_of_data_you_stored, //the data that you want to pass..
},
success: function(response)
{
console.log(response);
}
});
In model file: Proveedormodel and function add_uk_proveedor_familia() this changed ur params with family_data
function add_uk_proveedor_familia($id, $params){
$params=$_POST['family_data'];
foreach($params as $clave){
$this->db->select('id')->from('familia')->where('clave', $clave);
$valor = $this->db->get();
$vl = $valor->row_array();
$familia = $vl['id'];
$this->db->insert('relacionproveedorfamilia', array(
'idProveedor' => $id,
'idFamilia' => $familia
));
}
}
here in family_data your passing with large data if your params is the same as family_data then use use post value of family_Data into it.

Undefined variable in PHP after include

I'm new to stackoverflow (as a member at least) and I have a question.
I'm also new to PHP by the way.
Thing is:
I want to dynamically fill a second dropdown list with entries based on a first dropdown list (I want to show cities based on a selected province).
I managed to get the selected province to an external PHP file with an AJAX call in Javascript.
But when I include the external PHP file in my original PHP file, the variable of the external file is undefined.
The AJAX call is fired with an onchange event on the first dropdown menu.
And maybe you can also help with how I use that variable to get the right content in the second dropdown. I've used a multidimensional Array for that.
HTML:
echo('<select name="provincie" id="provincie" onchange="ProvinciePHP()">');
foreach ($provincie as $provincies){
echo ("<option> $provincies </option>");
}
echo ('</select>');
echo('<select name="stad" id="stad"> </select>')
PHP ARRAY:
$provincie = array(
'Selecteer een provincie',
'Drenthe',
'Flevoland',
'Friesland',
'Gelderland',
'Groningen',
'Limburg',
'Noord-Brabant',
'Noord-Holland',
'Overijssel',
'Utrecht',
'Zeeland',
'Zuid-Holland',
);
$stad = array(
'Drenthe' => array("Assen", "Emmen", "Hoogeveen", "Meppel"),
'Flevoland' => array("Almere", "Biddinghuizen", "Dronten", "Lelystad"),
'Friesland' => array("Heerenveen", "Joure", "Leeuwarden", "Sneek"),
'Gelderland' => array("Apeldoorn", "Arnhem", "Nijmegen", "Zutphen"),
'Groningen' => array("Delfzijl", "Groningen", "Stadskanaal", "Veendam"),
'Limburg' => array("Maastricht", "Roermond", "Sittard", "Venlo"),
'Noord-Brabant' => array("Breda", "Den Bosch", "Eindhoven", "Tilburg"),
'Noord-Holland' => array("Alkmaar", "Amsterdam", "Haarlem", "Hilversum"),
'Overijssel' => array("Deventer", "Enschede", "Hengelo", "Zwolle"),
'Utrecht' => array("Amersfoort", "Breukelen", "Utrecht", "Zeist" ),
'Zeeland' => array("Goes", "Middelburg", "Terneuzen", "Vlissingen"),
'Zuid-Holland' => array("Alphen a/d Rijn", "Den-Haag", "Rotterdam", "Schiedam"),
);
function getProvincie(){
var provincie = $('#provincie option:selected').val();
$.ajax({
type: "POST",
url: "getprovincie.php",
data: {data: provincie},
success: function(data) {
alert(data);
$('#stad').css('display','inline');
},
error: function(data) {
}
});
}
//PHP page to where the AJAX call points:
<?php
$resultaat = $_POST['data'];
echo($resultaat);

Get URL to ajax trough php/sql

Im having some trouble here with a website im trying to renew.
In the head a script is called with the name "jquery.script.js" with some code
$.ajax({
url: 'function.js.php?option=urlget&id='+movie_id,
dataType: 'json',
success: function(data){
fanarturl = data['url'];
alert(fanarturl);
alert(data.toSource());
if (data) {
$('#background').fadeOut(500, function(){
$(this).delay(100).attr('src', 'cache/'+movie_id+'_f.jpg');
$(this).fadeIn(500);
})
}
}
});
So this call's a file with the name "function.js.php".
if ($option == 'urlget') {
require('function.php');
$fan = get_fanart($mysql_tables, $_GET['id']);
$fan_js = array(
'url' => (isset($fan['url']) ? $fan['url'] : ''),
);
echo json_encode($fan_js);
}
And this call's a function with is:
function get_fanart($mysql_tables, $movie_id) {
$pos = strrpos($movie_id, "_");
$MovieID = substr($movie_id, ($pos + 1));
if(is_numeric($MovieID)){
$img_sql = 'SELECT id, url FROM ' . $mysql_tables[5]. ' WHERE type="fanart" AND id="'.$MovieID.'"';
$img_result = #mysql_query($img_sql);
if ($img_result) {
$get_img = mysql_fetch_assoc($img_result);
foreach($get_img as $key => $val) {
$fanart[$key] = $val;
}
}
return $fanart;
}}
The alart of the "jquery.script.js" show's : ({url:""})
Now the supid thing is that when I copy the code from "function.js.php" to "index.php"
It show's this: {"url":"http://image.tmdb.org/t/p/original/A82GPC0XeoZMBWDYTe4Dba32cme.jpg"}
Why is this URL not passed on to the "jquery.script.js" file?
Thanks in advance!
At the start of function.js.php you've got this:
if ($option == 'urlget') {
It shouldn't be $option, it should be $_GET['option']. (Or something like that - my PHP is a little rusty.)
Admittedly this sort of answer is more suited to codereview.stackexchange.com but your code has tons of ambiguities and a security vulnerability.
var promise = $.ajax({
url: 'function.js.php?option=urlget&id='+movie_id,
dataType: 'json'
});
// This makes for better readability than a nest of callbacks
promise.done(function(data){
console.log(data);
$('#background').fadeOut(500, function(){
$(this).delay(100)
.attr('src', 'cache/'+movie_id+'_f.jpg')
.fadeIn(500);
});
});
promise.fail(function(data){
console.log('oh noes!', data); // #todo what do we do when 'function.js.php' fails?
});
function.js.php. Notice that we return different HTTP response codes depending on the results.
// #todo fill in db credentials
$db = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
$option = $_GET('option');
if ($option === 'urlget') {
require('function.php');
$fan_art = get_fanart($mysql_tables, intval($_GET['id']), $db);
if ($fan_art && count($fan_art)) {
http_response_code(200);
echo json_encode($fan_art);
} else if (is_array($fan_art)) {
http_response_code(404);
echo json_encode(array('errors' => array('no fan_art found')));
} else {
http_response_code(500);
echo json_encode(array('errors' => array('an error occured when fetching fan art')));
}
}
function.php. Notice that here we pass in the database connection and use bound parameters to insert variables into our SQL.
/**
*
* #param [String] $table - the table to fetch data from
* #param [Int] $movie_id
* #param [PDO] $db - A PDO database connection
* #return [False, Array] Returns false if query fails, otherwise returns array of results
*/
function get_fanart($table, $movie_id, $db) {
$statement = $db->prepare( "SELECT id, url FROM :table WHERE type = 'fanart' AND id = :id" );
$sth->bindParam(':table', $table); // default param type is string
$sth->bindParam(':id', $movie_id, PDO::PARAM_INT);
if ( $sth->execute() ) {
return $sth->fetchAll();
} else {
return false;
}
}
On a side comment, your file & variable naming scheme is pretty horrible. Naming a file .js.php implies that the PHP file renders javascript. Also naming your files function or functions is a maintainence nightmare - why not fan_art.json.php and fan_art.php.

Zend Autofill dropdown after select

I have been working on a code to autofill dropdowns onchange, after selecting the required values from an autocomplete search field. The problem is that my autofill does not work after selecting the value, but the Jquery to execute the script and fetch the id works perfectly, don’t know what I’m missing. here’s a bit of my code and picture. Take note I have multiple jquery scripts executing types of programs. Here is the error message I get
Message: Could not find row 50390
Stack trace:
C:\xampp\htdocs\portal-gep-2\application\modules\admin\controllers\AjaxController.php(366): Model_SicCode->getsiccode('50390'
Request Parameters:
array (
'controller' => 'ajax',
'action' => 'autofill',
'sicid' => '50390',
'lang' => 'en',
'module' => 'admin',
)
The id does exist in my database but my dropdowns just don’t change. How can I go about this?
contoller
public function autofillAction()
{
//get the id send via a get - the sic id
$division= $this->getRequest()->getParam('sicid');
//get majorgroup name, group name and sic description
//fill dropdowns with relevant values - new form with drop downs
//selecting the required values same as autocomplete (don't know)
$mdlSic = new Model_SicCode();
$results = $mdlSic->getsiccode($division);
foreach($results as $result)
{
$Division = $result->div_code;
$mdlDivision = new Model_Division();
$result = $mdlDivision->getSicViaDiv($division);
$name = $result->div_desc;
$id = $result->div_code;
$mgrp_desc->addMultiOption($id, $name);
}
$mgrp_desc->setOrder(4);
$this->_helper->viewRenderer->setNoRender(false);
$this->_helper->layout->disableLayout();
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('newfield', 'html')->initContext();
$id = $this->_getParam('id', null);
$this->view->field = $div_desc->__toString();
}
jquery
function ajaxautofill(id) {
$.ajax({
type: 'POST',
datatype: 'JSON',
url: '<?php echo $this->baseURL()?>/admin/ajax/autofill/sicid/' + id,
//data: 'division':$('#div_desc').val(),
//dataType: 'JSON',
//async: true,
success: function(data)
{
//fill drop downs
$('#t2').append(data);
}
});
}
Get siccode
public function getSICviaDiv($d_id)
{
$select = $this->select()->where('div_code = ?', $d_id);
$results = $this->fetchAll($select);
if (count($results))
return $results;
else
return 'nothing';
}
GetsicViaDiv
public function getSicViaDiv($siccode)
{
$select = $this->select();
$select->where('div_code = ?', $siccode);
return $this->fetchAll($select);
}
Firstly, you've built the select object twice. Secondly, I'd suggest the answer is here:
$row = $this->fetchRow($select);
if (!$row)
{
throw new Exception("Could not find row $id");
}
You're throwing an exception if the RowSet object returned, from fetchRow, is false. I'll work up some code this evening when I have my laptop handy.

Categories