Undefined variable in PHP after include - javascript

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

Related

Chained AJAX dropdown (select) jquery

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!

From a running PHP Code, how to update status in DIV tag

I have a web Page, in which i an downloading data one after another in a loop. After each data download is finished i want to update the status to a DIV tag in the Web Page. How can i do this. Connecting to server and downloading data via php code and the div tag is within the .phtml page.
i have tried
echo "
<script type=\"text/javascript\">
$('#tstData').show();
</script>
";
But the echo statement update will happen at the end only. Refreshing of DIV tag need to happen at the end of each download.
Use jQuery load()
$('#testData').load('http://URL to script that is downloading and formatting data to display');
$("#save_card").submit(function(event) {
event.preventDefault();
var url = "card_save.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
dataType:"json",
data: $("#save_card").serialize(), // serializes the form's elements.
success: function(data)
{
console.log(data);
if(data.msg=="success")
{
$("#submit_msg").html("Thank You !!!");
console.log("Record has been Inserted Successfully!!!");
}
else
{
$("#submit_msg").html(data.er);
console.log("There Is Some Error");
}
$("#submit_msg").show();
setTimeout(function() { $("#submit_msg").hide(); }, 5000);
$("#save_card").get(0).reset();
}
});
return false; // avoid to execute the actual submit of the form.class_master
});
Use This Ajax function to call PHP function to get data. Here
#save_card = Id of the form that you want to submit.
url = action for the form or the location to the php file from where your data is coming.
data: $("#save_card").serialize() = it is sending all the data of the form in serialize form. Data can be created manually to do this repalce this line with data: {'name':name,'year':year}
function(data) = here data is returned from the php code in json formate.
data.msg = It is a way to access different field from data.
$user_email = $_REQUEST['user_email'];
$cat_id = $_REQUEST['category'];
$title = $_REQUEST['title'];
$country = $_REQUEST['country'];
$date = date("Y-m-d H:i:s");
$sql = "INSERT INTO project(title, user_email, cat_id, country, start_date) VALUES ('$title','$user_email','$cat_id','$country', '$date')";
if (mysql_query($sql)) {
$project_id = mysql_insert_id();
echo json_encode(array('project_id' => $project_id, 'msg' => 'Successfully Added', 'status' => 'true'));
} else {
echo json_encode(array('msg' => 'Not Added', 'status' => 'false'));
}
PHP code to send data in json format

Submit POST data without refreshing on a Wordpress site?

I have searched the internet a lot for an answer to my question and have not found exactly what I was looking for. So the standard way, from what I have seen, to accomplish this is to use jQuery's submit and AJAX to send the data and redirect to another PHP page. However, I have multiple problems with this. First of all, AJAX. Regular AJAX does not work on Wordpress sites, from what I have seen. How do I get plain old regular AJAX to work? I have not seen a single good tutorial for this that is in plain English for Dummies. Second of all, the PHP redirect. I just want it to send to PHP already on the page. I just want data to go from my Javascript into my PHP already on the page. I don't need a redirect. So, my final question is, can those two problems be fixed in order to do it the traditional way? Or is there a better way to do it that circumvents these problems? I am a complete beginner, BTW- been doing web programming for less than five months. So please, for Dummies or Complete Idiot's language if you can. Here's the form I am submitting from:
<form method="post">
Search By File Name: <input type="text" name="searchterms" placeholder="search"></input>
<button type="submit" name="SearchSubmit">Display Results</button>
</form>
Here's the PHP I want to execute:
$submit=$_POST['SearchSubmit'];
$results=$_POST['searchterms'];
if(isset($submit))
{
//whole bunch of stuff, like sql queries and file generation
}
There are 3 part of code,
HTML where data want to show.
<div id="msg_alert"></div>
Jquery for ajax;
$('#msg_form').submit(function (event) {
event.preventDefault();
action = 'messaging_post';
user_id = $('#msg_form #user_id').val();
$.ajax({
type: 'POST',
dataType: 'json',
url: ajax_auth_object.ajaxurl,
data: {
'action': action,
'user_id': user_id
},
success: function (data) { //alert(data.message);
if (data.log== true) {
$('#msg_alert').val(data.message);
}
else {
$('#msg_alert').val('There is an error');
}
}
});
});
Third is PHP:
add_action('init', 'ajax_review_loading');
function ajax_review_loading() {
wp_localize_script( 'ajax-auth-script', 'ajax_auth_object', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'redirecturl' => home_url(),
'loadingmessage' => __('Sending user info, please wait...')
));
add_action( 'wp_ajax_messaging_post', 'messaging_post' );
}
function messaging_post(){
/// Your work here.
echo json_encode(array('log'=>true, 'message'=> $htm));
die();
}
For working you must add wp_enqueue_script to ajax_review_loading function
add_action('init', 'ajax_review_loading');
function ajax_review_loading() {
wp_enqueue_script('ajax-auth-script', get_template_directory_uri() );
wp_localize_script( 'ajax-auth-script', 'ajax_auth_object', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'redirecturl' => home_url(),
'loadingmessage' => __('Sending user info, please wait...')
));
add_action( 'wp_ajax_messaging_post', 'messaging_post' );
}
function messaging_post(){
/// Your work here.
echo json_encode(array('log'=>true, 'message'=> $htm));
die();
}
You might need 2 php files, the one that generates the page that you are already seeing, let's call it "my_page.php", and the one that generates the data that you load in that first page without refreshing it, let's call it "livedata.php".
So for example if "my_page.php" generates the following html:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
function refresh_data(start_at) {
$("#data_updates_go_here").empty(); // Clear previous contents of the div for refresh
$.getJSON("livedata.php?start_at=" + start_at,
function(json_returned) {
$.each(json_returned, function(key, value){
$("#data_updates_go_here").append(key + " = " + value + "<br />");
});
});
}
</script>
Data: <br/>
<div id="data_updates_go_here">
</div>
<input type=button onClick="refresh_data(1);" value="Refresh data at 1">
<input type=button onClick="refresh_data(3);" value="Refresh data at 3">
You can see that when you load "my_page.php", it won't display any data. inside of the div.
Now "livedata.php" on it's side will have to generate a json structure, as you can see above, it can receive parameters, so you can use them for instance, to limit a query to a database or for any other purposes that you need a parameter to be passed to your php. In the example, "livedata.php" should return a 'json' structure. For instance, your php code could be
<?php
header('Content-Type: application/json');
if ($_REQUEST['start_at'] == 1) {
echo json_encode(array('value1' => 'data1', 'value2' => 'data2'));
} else if ($_REQUEST['start_at'] == 3) {
echo json_encode(array('value3' => 'data3', 'value4' => 'data4'));
} else {
echo json_encode(array('value1' => 'data1', 'value2' => 'data2'));
}
?>
You can see how you can control the values refreshed by passing a different value for "start_at".

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.

Cakephp master/details add

I have two tables, has-many relationship,
in the master add.ctp, allow user to upload 0~5 files(file path information are stored in details table)
I want to dynamically display attachment(detail) form in the master/add.ctp
1, user choose number of files want to upload from dropdown list,
echo $this->Form->input('attachments', array( 'options' => array(1, 2, 3, 4, 5),'empty' => '(choose one)', 'onchange' => 'showNumber(this.value)'));
then forloop
{
echo $this->Form->input('attachment_path', array('type'=>'file','label' =>'Attachment, Maximum size: 10M'));
}
//but I don't know how to capture this.value, I know Javascript can not pass value to php.
or user click 'add another attachment' link, then detail form shows up.
How to achieve this function, any help would be appreciated.
I have read this article:
Assign Javascript variable to PHP with AJAX
and get same error: the variable is undefined
Edit:
http://cakephp.1045679.n5.nabble.com/Adding-fields-to-a-form-dynamically-a-complex-case-td3386365.html
'For each field use a default name with [] at the end (which will make
it stack like a array) example: data[][book_id] after the fields have
been submitted'
Where should I place the []?
I think you should use Ajax for this.
Simply create an ajax call on select.change() and then a method in the controller that returns the necessary info.
You can return an array of data using echo json_encode(array('key' => 'value')) directly on your controller (or better in a custom view) and access it with Javascript:
success: function(data) {
alert(data.key);
}
Edit...
In your javascript use something like...
$('select').change(function(e) {
var select = $(this);
$.ajax({
type: "POST",
dataType: "json",
url: "/attachments/youraction",
data: { data: { id: select.find(":selected").val() } },
success: function(data) {
for (i in data) {
var input = $('<input>', {type: "file", label: data[i].Attachment.label})
$('form.your-form').append(input);
}
}
})
});
Then in "Yourcontroller" create "youraction" method:
<?php
class AttachmentsController extends AppController
{
public function youraction()
{
if (!$this->RequestHandler->isAjax() || !$this->RequestHandler->isPost() || empty($this->data['id']))
{
$this->cakeError('404');
}
// Do your logic with $this->data['id'] as the select value...
$data = $this->Attachment->find('all', array('conditions' => array('id' => $this->data['id'])));
// ....
// then output it...
echo json_encode($data);
// This should be done creating a view, for example one named "json" where you can have there the above echo json_encode($data);
// Then..
// $this->set(compact('data'));
// $this->render('json');
}
}
It's more clear now?? If you have doubts about ajax + cakephp you should do a search on the web, where you will find a lot of tutorials.
I use this approach to achieve this function. (finally got it :))
http://ask.cakephp.org/questions/view/foreach_loop_with_save_only_saving_last_member_of_array
Yes, AJAX can do lots of things, to me, it's very hard to understand the logic in a day..
Anyway, Thanks again.

Categories