I’m using CodeIgniter framework and I want to make a chained drop-down with JavaScript code. Then I get this error:
SyntaxError: expected expression, got '<' //first line
But my first line is <!DOCTYPE html> and my file type is PHP not JavaScript, here is my JavaScript code:
<div class="form-group">
<div class="form-row">
<div class="col-md-4">
<label for="inputBody">Body Number</label>
<select name="inputBody" id="inputBody" onchange="javascrip: ambildata(this.value);" class="form-control" required="required">
<?php foreach ($body as $bd) { ?>
<option value="<?php echo $bd->bodynumkids ?>" ><?php echo $bd->bodynumkids ?></option>
<?php } ?>
</select>
</div>
<div class="col-md-6">
<label for="inputKiddie">Kiddies Name</label>
<!-- <div class="form-label-group"> -->
<input type="text" name="inputKiddie" id="inputKiddie" class="form-control" placeholder="ex. Super Cop" required="required">
<!-- </div> -->
</div>
<script type="text/javascript">
function ambildata(x) {
$.ajax({
type:'POST',
url :'<?php echo base_url("Repairpaint/chained"); ?>',
jsonp : 'callback',
dataType: 'jsonp',
data :{ '#inputBody' : x},
success: function(response){
console.log(response);
var len = response.length;
if(len > 0){
var tampil = response[0].namakids;
$('#inputKiddie').text(tampil);
} else {
$('#inputKiddie').text('wek');
}
}
})
}
</script>
</div>
</div>
And here the controller :
public function chained()
{
$dataKiddie = $this->input->post('inputBody');
$where = array('bodynumkids'=> $dataKiddie);
$response = $this->Model_repairpaint->chaincb('kiddiejadi', $where)->result();
echo json_encode($response);
}
I have searched similar questions and solutions around Stack Overflow but I found nothing. Can anyone help me find out the solution?
Related
i have an html form with a date input and a multiselect.
When loading page I load the options of the multiselect through a php function.
What i want to do is to capture onChange event of the date input with a js script and launch the php script to reload the option values of the select using the new date.
This is the php code
<?php
//DEFINE
$dateMinimumInput = "";
// Handle AJAX request for changing DateMinimumInput(start)
if(isset($_POST['ajax']) && isset($_POST["dateMinimumChanged"]) ){
echo "Inside function dateMinimumChanged: " .$_POST['dateMinimumChanged'];
$dateMinimumInput = verify_input($_POST['dateMinimumChanged']);
}
$stationList = selectStations($dateMinimumInput); ?>
This is the javascript
<script>
$(document).ready(function(){
$("#dateMinimumInput").change(function(){
//Selected value
inputValue = $(this).val();
console.log(inputValue);
$.ajax({
type: 'POST',
url: '',
data: {ajax: 1, dateMinimumChanged: inputValue},
success: function(data){
console.log('works');
console.log(data);
$('body').append(response);
},
error: function(){
alert('something went wrong');
}
});
});
});
</script>
and this is the html form
<form class="" role="form" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<div class="row">
<div class="col-md-6">
<div class="form-group form-row">
<label for="dateMinimumInput" class="col-form-label col-sm-4">Date Minimum:</label>
<div class="col-sm-8">
<div class="form-group">
<input type="date" class="form-control <?php if ( $dateMinimumInputErr !== "") { echo 'is-invalid'; }?>" id="dateMinimumInput" name="dateMinimumInput" placeholder="Enter date minimum" value="<?php echo $dateMinimumInput;?>">
<div class="invalid-feedback"> <?php if ( $dateMinimumInputErr !== "") { echo 'Please, ' .$dateMinimumInputErr; } ?> </div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group form-row">
<label for="stationInput" class="col-form-label col-sm-4">Station:</label>
<div class="col-sm-8">
<select id="stationInput" name="stationInput[]" class="form-control" multiple>
<?php
foreach($stationList as $station){
if($station['numberofmeasurements'] == 0){
echo '<option disabled="true" value="'.$station['id'] .'">'.$station['location'] .' (' .$station['numberofmeasurements'] .') </option>';
}else{
echo '<option value="'.$station['id'] .'">'.$station['location'] .' (' .$station['numberofmeasurements'] .') </option>';
}
}
?>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 text-right">
<button id="submit" name="submit" type="submit" class="btn btn-primary">Search</button>
</div>
</div>
</form>
The fragments of code are all from the same page.
The problem is that when I change the date, the javascript captures the event but the PHP script is not executed and the options are not reload.
Any help about what I'm doing wrong?
Thank you
I have been at this for a few hours now, i'm pretty sure it's a syntax error from my side, i'm trying to call a .php file and execute the contents, i'm passing through a textarea value to be used in the .php code.
HTML:
<div id="mainContent"></div>
<div class="panel panel-primary">
<div class="panel-heading">Your article rewriter API is - (<span class="results"><b>http://www.example.com/api.php?spinner=1&key=<?php echo $user['api_key']; ?></b></span>)</div>
<div class="panel-body">
<form id="frmAjax" action="spinner.php" method="post" class="form-horizontal container-fluid" role="form">
<div class="row form-group">
<div class="col-sm-4 text-right">
<label for="txtLanguage" class="control-label">Language:</label>
</div>
<div class="col-sm-8">
<select id="txtLanguage" name="txtLanguage" class="form-control" required="required">
<?php
$level = array("syn/en.syn" => "English", "syn/de.syn" => "German", "syn/pl.syn" => "Polish");
?>
<?php foreach ($level as $key => $value) { ?>
<option value="<?php echo htmlspecialchars($key) ?>"><?php echo htmlspecialchars($value) ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="row form-group">
<div class="col-sm-4 text-right"><label for="txtBody" class="control-label">Article:</label></div>
<div class="col-sm-8"><textarea class="form-control" id="txtBody" name="txtBody" required="required"></textarea></div>
</div>
<div class="row form-group">
<div class="col-sm-12 text-right">
<button type="submit" name="spinText" class="btn btn-default">Spin!</button>
</div>
</div>
</form>
</div>
<div class="panel-footer">Paste in an article above and hit <b>Spin</b>!</div>
</div>
<script>
$(document).ready(function() {
$('#frmAjax').submit(function(e) {
var text = $('#txtBody').val();
$.ajax({
url: "ajax-rewriter.php",
type: "POST",
data: { textData : text }
})
});
});
$("#mainContent").load('ajax-rewriter.php')
e.preventDefault();
</script>
ajax-rewriter.php
<?php
include('includes/db_connection.php');
include('includes/sessions.php');
include('includes/functions.php');
if (isset($_REQUEST['textData')) {
$articleBody = strtolower($_REQUEST['textData']);
echo $articleBody;
echo "<pre><b>Original:</b><br /><br /><p>" . $articleBody . "</p></pre>";
$word = "";
$length = strlen($articleBody);
$OutputBody = "";
for ($i = 0; $i < $length; $i++) {
$word = $word . $articleBody[$i];
if ($i == $length - 1)
$comeCha = " ";
else
$comeCha = $articleBody[$i + 1];
$retStr = getWordPattern($word, $comeCha, "syn/en.syn");
if ($retStr != "") {
$OutputBody .= $retStr;
$word = "";
}
}
echo "<br>";
echo "<pre><b>Spun:</b><br /><br /><p>" . $OutputBody . $word . "</p></pre>";
}
?>
Pretty basic code, nothing is happening at all once i press the "Spin!" button, i'm still learning Ajax, i don't see any obvious errors, is there also a way i can debug what the issue is, normally php throws you an error to work from, any help is appreaciated!
Your Ajax should be like this.
$(document).ready(function() {
$('#frmAjax').submit(function(e) {
var text = $('#txtBody').val();
$.ajax({
url: "ajax-rewriter.php",
type: "POST",
data: text,
success: function(html) {
$("#mainContent").html(html); //This will load the data at ID "#mainContent".
}
});
});
});
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$data = $_POST['txtbody'] //where txtbody is the name in input form
}
I am having issues calling my javascript function which loops through an array calling an external PHP page for each value. I get the following error in my developer console in Chrome:
Uncaught SyntaxError: Unexpected token . CSV.php?reg=1:3
When inspecting my values passing to the script everything is there as it should be:
<script type="text/javascript">
function.csvgen(){
var area = "["22","23","24"]";
var start =""2017-01-30"";
var end = ""2017-02-06"";
var len = area.length;
for (i = 0; i < len; i++) {
$.getScript("CSVGEN.php?area="+area[i]+"&start="+start+"&end="+end);
}
}
</script>
I'm not exactly a good programmer and have used very little Javascript (which required assistance from this wonderful forum as well...). Here is my code for the page. The point of the code is to let the user select a number of areas based on their region as well as a start date and an end date and then generate a CSV from my MS SQL database for each, the code for which is in the called CSVGEN.PHP file. I've tested the CSVGen file with a manually generated link and it works, it does not if I put the static link inside the for loop.
<script type="text/javascript">
function.csvgen(){
var area = "<?php echo json_encode(array_values($_POST['arealist'])); ?>";
var start ="<?php echo json_encode($_POST['start']); ?>";
var end = "<?php echo json_encode($_POST['end']); ?>";
var len = area.length;
for (i = 0; i < len; i++) {
$.getScript("CSVGEN.php?area="+area[i]+"&start="+start+"&end="+end);
}
}
</script>
<?php
$page_title="CSV Generator";
include("\Include\header.inc");
include("\Include\connect-db.php");
include("\Include\CSVGen.php");
$error="";
$start_date=date("Y-m-d");
$end_date=date("Y-m-d", strtotime("+7 days"));
if(isset($_GET['reg']))
{
$reg=$_GET['reg'];
}
else{
$reg='1';
}
if($start_date>$end_date){
$error = 'ERROR: End Date cannot be before Start Date!';
}
if ($error != '')
{
echo '<div class="container">
<div class="row">
<div class="alert alert-danger col-md-12">'.$error.'
</div>
</div>
</div>';
}
$sqlareas="SELECT Area_Name, Region_ID, Area_ID FROM Listings_Areas WHERE region = '$reg'";
$arearesult= sqlsrv_query($conn, $sqlareas, array(), array("Scrollable"=>"buffered"));
$areacount = sqlsrv_num_rows($arearesult);
function renderForm($arearesult, $areacount, $start_date, $end_date){
?>
<html>
<head>
</head>
<body>
<div class="container">
<div class="row">
<form id="CSV" name="form1" method="post">
<div class="col-md-2 col-md-offset-1">
<p><select name="arealist[]" size="<?php echo $areacount ;?>" multiple="multiple" tabindex="1">
<?php
while($areas=sqlsrv_fetch_array($arearesult)){
echo'<option value="' . $areas['Area_ID'] . '">' . $areas['Area_Name'] . '</option>';
}
?>
</select>
</div>
<div class="col-md-3">
<strong>Start Date: </strong> <input type="date" name="start" value="<?php echo $start_date; ?>" />
</div>
<div class="col-md-3">
<strong> End Date: </strong> <input type="date" name="end" value="<?php echo $end_date; ?>" />
</div>
<div class="col-md-2">
<input type="submit" onclick="csvgen()" name="submit" value="Get CSVs">
</div>
</form>
</div>
</div>
<?php
}
if($_SERVER['REQUEST_METHOD'] === 'POST'){
print_r(array_values($_POST['arealist']));
echo $_POST['start'];
echo $_POST['end'];
}
else{
renderForm($arearesult, $areacount, $start_date, $end_date);
}
?>
I've tried removing all tabbing/spacing and clearing any potential illegal characters that might have snuck in, but it's showing a period, which I can only guess is referring to either my area.length which as far as I can tell from the manual is right and I still get the error if I remove it or $.getscript, but I've used that elsewhere in similar functions with no issue so I don't know why that would be wrong, or how to replace it.
At the very begining of the script you have:
<script type="text/javascript">
function.csvgen(){
//...
which should be:
<script type="text/javascript">
function csvgen(){
//...
with a space instead . between function and csvgen.
NOTE: this area = "["22","23","24"]"; is also wrong. Use diferent quotes (like area = '["22","23","24"]';) or escape the inner quotes (like area = "[\"22\",\"23\",\"24\"]";)
Find a good javascript tutorial and learn more about how to declare function in javascript.
My database is not updating dynamically. Am I missing something?
It was working before removing some field names and also it was updating the user records automatically. But now it seems some issue in updating dynamically.
Form javascript used for updating
<script type="text/javascript">
// JQUERY: Plugin "autoSumbit"
(function($) {
$.fn.autoSubmit = function(options) {
return $.each(this, function() {
// VARIABLES: Input-specific
var input = $(this);
var column = input.attr('name');
// VARIABLES: Form-specific
var form = input.parents('form');
var method = form.attr('method');
var action = form.attr('action');
// VARIABLES: Where to update in database
var where_val = form.find('#where').val();
var where_col = form.find('#where').attr('name');
// ONBLUR: Dynamic value send through Ajax
input.bind('blur', function(event) {
// Get latest value
var value = input.val();
// AJAX: Send values
$.ajax({
url: action,
type: method,
data: {
val: value,
col: column,
w_col: where_col,
w_val: where_val
},
cache: false,
timeout: 10000,
success: function(data) {
// Alert if update failed
if (data) {
alert(data);
} else { // Load output into a P
$('#notice').text('Updated');
$('#notice').fadeOut().fadeIn();
}
}
});
// Prevent normal submission of form
return false;
})
});
}
})(jQuery);
// JQUERY: Run .autoSubmit() on all INPUT fields within form
$(function(){
$('#ajax-form INPUT').autoSubmit();
});
</script>
<script type="text/javascript" src="materialise/js/jquery-1.8.0.min.js"></script>
<form id="ajax-form" class="autosubmit" method="POST" action="./php_parsers/ajax-update.php">
<div class="row">
<div class="input-field col s8">
<i class="mdi-editor-mode-edit prefix"></i>
<input type="text" name="firstname" >
<label for="firstname">Firstname: * <?php echo $firstname; ?></label>
</div>
</div>
<div class="row">
<div class="input-field col s8">
<i class="mdi-editor-border-color prefix"></i>
<input type="text" name="lastname" value="<?php echo $lastname; ?>">
<label for="lastname">Lastname: *</label>
</div>
</div>
<div class="row">
<div class="input-field col s8">
<i class="mdi-action-accessibility prefix"></i>
<input type="date" name="age" class="datepicker validate">
<label for="age">D.o.B *</label>
</div>
</div>
<div class="row">
<div class="input-field col s8">
<i class="mdi-editor-mode-edit prefix"></i>
<label for="gender"><?php echo $sex; ?></label>
</div>
</div>
<input id="where" type="hidden" name="<?php echo $uname; ?>" value="<?php echo $uname; ?>" />
</form>
update php used
<?php
// DATABASE: Connection variables
include_once("../php_includes/check_login_status.php");
// DATABASE: Clean data before use
function clean($value) {
global $db_conx;
$value = preg_replace('#[^a-z0-9. ]#i', '', $value);
$value = mysqli_real_escape_string($db_conx, $value);
return $value;
}
// FORM: Variables were posted
if (count($_POST)) {
// Prepare form variables for database
foreach($_POST as $column => $value)
${$column} = clean($value);
// Perform MySQL UPDATE
$result = "UPDATE users SET ".$col."='".$val."' WHERE username='$log_username' LIMIT 1";
$query = mysqli_query($db_conx, $result);
}
?>
below is the updated code working on my local...hope it will help you
did it without creating jquery plugin
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$( document ).ready(function() {
$('input').blur(function() {
var input = $(this);
var column = input.attr('name');
// VARIABLES: Form-specific
var form = input.parents('form');
var method = form.attr('method');
var action = form.attr('action');
// VARIABLES: Where to update in database
var where_val = form.find('#where').val();
var where_col = form.find('#where').attr('name');
var value = input.val();
// AJAX: Send values
$.ajax({
url: action,
type: method,
data: {
val: value,
col: column,
w_col: where_col,
w_val: where_val
},
cache: false,
timeout: 10000,
success: function(data) {
// Alert if update failed
if (data) {
alert(data);
} else { // Load output into a P
$('#notice').text('Updated');
$('#notice').fadeOut().fadeIn();
}
}
});
});
});
</script>
</head>
<body>
<form id="ajax-form" class="autosubmit" method="POST" action="./php_parsers/ajax-update.php">
<div class="row">
<div class="input-field col s8">
<i class="mdi-editor-mode-edit prefix"></i>
<input type="text" name="firstname" value="<?php echo $firstname; ?>">
<label for="firstname">Firstname: * </label>
</div>
</div>
<div class="row">
<div class="input-field col s8">
<i class="mdi-editor-border-color prefix"></i>
<input type="text" name="lastname" value="<?php echo $lastname; ?>">
<label for="lastname">Lastname: *</label>
</div>
</div>
<div class="row">
<div class="input-field col s8">
<i class="mdi-action-accessibility prefix"></i>
<input type="date" name="age" class="datepicker validate">
<label for="age">D.o.B *</label>
</div>
</div>
<div class="row">
<div class="input-field col s8">
<i class="mdi-editor-mode-edit prefix"></i>
<label for="gender"><?php echo $sex; ?></label>
</div>
</div>
<input id="where" type="hidden" name="<?php echo $uname; ?>" value="<?php echo $uname; ?>" />
</form>
</body>
</html>
**Here’s the code example of a POST method call and AJAX database update –**
<div id="c">
<input id="text1" type="text" name="text1" />
<input id="submit" type="submit" name="submit" value="SAVE IT" />
</div>
<div id="cn">
</div>``
**Now we declare the JQuery code to make a POST call**
<script type="text/javascript">
$(document).ready(function () {
$('#submit').click(function(){
var ths = this;
var str = $(ths).siblings("#text1").val();
$.post("saveData.php", {t:str}, function(value){
$(ths).parent("#c").fadeOut("fast");
$(ths).parent("#c").siblings("#cn").html(value);
});
});
});
</script>
**This code block receive value and update database**
$t = $_POST['t'];
$link = mysql_connect(servername, username, password);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db(databasename, $link);
// Insert the data
$query2="INSERT INTO p_a_j(scrap) VALUES('$t')";
$results2 = mysql_query($query2, $link)
or die(mysql_error());
if(mysql_affected_rows()>=1){
echo '<span>You entered'.$t.'</span>'.
'Database updated'.
'Try this again'; }
I know this question have been asked many times, but I have tried for hours and nothing worked, I'm a noob with php and ajax so, I might be missing a small thing that I'm not aware of, What I'm trying to achieve here is that, I want the user to select a food group and based on that a list of ingredients will show up.
I tested my process.php file alone and it is working well, I have also tested the script what happens is that the line starting from $.ajax doesn't work when I comment it out and type alert(parent) I actually get the value of the option selected, so what am I doing wrong here? or am I missing an import?
P.S I'm using bootstrap 3.0 for the design
Here is my html code
<!-- field food group-->
<div class ="field form-group">
<label for="food-group"> Food Group * </label>
<div class="input-group input-group-lg">
<select class="form-control" id="food-group-id" name="food-group" onchange="ajaxfunction(this.value)">
<?php
// retreiving the recipe groups
$RecipeGroup = new FoodGroup();
$data = $RecipeGroup->findAll();
foreach ($data->results() as $recipegroup) {
// displaying the options
echo '<option value="'.$recipegroup->food_group_id.'">'.$recipegroup->food_group_name.'</option>';
}
?>
</select>
</div>
</div>
<!-- field Ingredients-->
<div class ="field form-group">
<label for="ingredients"> Ingredients * </label>
<div class="input-group input-group-lg">
<select class="form-control" id="ingredients">
<?php
// retreiving the recipe groups
$ingredients = new Ingrident();
if(Input::exists()){
$data = $ingredients->findByGroup(Input::get('food-group'));
}else
$data = $ingredients->findByGroup(1);
foreach ($data->results() as $ingredient) {
// displaying the options
echo '<option value="'.$ingredient->ingrident_id.'">'.$ingredient->ingrident_name.'</option>';
}
?>
</select>
<br> <br> <br>
<span id="helpBlock" class="help-block center">Ingredient not listed ?
<button class="btn btn-primary center" value="add-ing"> <span class="glyphicon glyphicon-plus"></span> Add New Ingredient </button>
</span>
</div>
</div>
Here is my script
<script type="text/javascript">
function ajaxfunction(parent)
{
$.ajax({
url: 'process.php?food-group=' + parent;
success: function(data) {
$("#ingredients").html(data);
}
});
}
</script>
Here is my process.php file
<?php
mysql_connect('localhost', 'root','');
mysql_select_db("online_recipes");
$result = mysql_query("SELECT * FROM `ingrident` WHERE `food_group_id_fk` = " . mysql_real_escape_string($_GET['food-group']));
while(($data = mysql_fetch_array($result)) !== false)
echo '<option value="', $data['ingrident_id'],'">', $data['ingrident_name'],'</option>';
A list of my imports
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/docs.min.js"></script>
<script src="js/ie10-viewport-bug-workaround.js"></script>
$.ajax({
url: 'process.php',
type:'post',
data: {parent: parent},
success: function(data) {
$("#ingredients").html(data);
}
});
in your process.php
$parent = $_POST['parent'];
echo($parent);