Simple ajax post Uncaught ReferenceError - javascript

Hello I have a simple ajax call but I can not see the result. What am I doing wrong ? Thank You.
index.php
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
function prova(SelectedFriend){
$.post("result.php", {Selected:Selected});
return false;
}
</script>
</head>
<body>
<?
$user="name1";
?>
<div onclick="prova(<? echo $user; ?>)" style="cursor:pointer;">
<? echo $user; ?>
</div>
<?
$user="name2";
?>
<div onclick="prova(<? echo $user; ?>)" style="cursor:pointer;">
<? echo $user; ?>
</div>
<?
$user="name3";
?>
<div onclick="prova(<? echo $user; ?>)" style="cursor:pointer;">
<? echo $user; ?>
</div>
<div id="Result"></div>
</body>
</html>
and result.php
<?
echo $_POST['Result'];
?>
The console of my browser says "Uncaught ReferenceError: name1 is not defined" when I click on name1.

The $user must be placed inside simple quotes:
<div onclick="prova('<? echo $user; ?>')" style="cursor:pointer;">
Also your function is not using the parameter as it should:
function prova(SelectedFriend){
$.post("result.php", {SelectedFriend:SelectedFriend});
return false;
}
And the result.php file must be corrected as well:
<?php
echo $_POST['SelectedFriend'];

Related

How to save multiple dynamic data in database

I am making a survey question portal in which certain questions will appear on certain conditions like if age-band='18-25' and residential status='Homeowner' then questions like what brand is your washing machine and Do you have any mortgage will appear. If age-band = 26-30 and residential-status ='Rent Council' then question "Do you have a life insurance?" This will appear. Now I have written the code to display the questions but I am unable to save the respective questions and answers in the database.
This is what I have tried so far.
(//Code for first.php)
<?php
include 'connect.php';
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<form method="POST" action="display1.php">
<select name="age_id">
<?php
$query = mysqli_query($con,"select * from age");
while ($rows = mysqli_fetch_array($query)) {
?>
<option value="<?php echo $rows['id']?>"><?php echo $rows['age']; ?></option>
<?
}
?>
</select><br>
<select name="res_id">
<?php
$query = mysqli_query($con,"select * from residential");
while ($rows = mysqli_fetch_array($query)) {
?>
<option value="<?php echo $rows['id']?>"><?php echo $rows['residential_status']; ?></option>
<?
}
?>
</select><br>
<input type="submit" name="sub" value="SUBMIT">
</form>
</body>
</html>
(//code for display1.php)
<?php
include 'connect.php';
$age_id = $_POST['age_id'];
$res_id = $_POST['res_id'];
$res = mysqli_query($con,"select * from parent_questions where age_id ='$age_id' && residential_id = '$res_id'");
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
<style type="text/css">
#new{display: none;};
</style>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.1/dist/css/bootstrap.min.css">
<script src="https://cdn.jsdelivr.net/npm/jquery#3.6.0/dist/jquery.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.6.1/dist/js/bootstrap.bundle.min.js"></script>
<!-- cdn link for ajax -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<form method="POST" action="submit.php">
<tbody>
<?php
while($rows=mysqli_fetch_assoc($res)){
$opt_arr=explode("|",$rows['qoption']);
?>
<tr id="div_<?php echo $rows["qid"]; ?>">
<td><?php echo $rows['question']; ?></td>
<td>
<select class="form-control" name="<?php echo $rows['qid']; ?>">
<option value="">Select</option>
<?php
foreach($opt_arr as $v){
?>
<option value="<?php echo trim($v); ?>"><?php echo $v; ?></option>
<?php
}
?>
</select>
</td>
</tr>
<?php
}
?>
</tbody>
<input type="submit" name="sub" value="SUBMIT">
</form>
<script type="text/javascript">
function newfun(datavalue){
document.getElementById('new').style.display='block';
$.ajax({
url: 'backend.php',
type: 'POST',
data: { datapost : datavalue},
success: function(result){
$('#getdata').html(result);
}
});
}
</script>
</body>
</html>
Now I can't use a static name for select because it will keep changing so I am just confused how will I be able to insert the respective question's option in the database like the washing machine question's option in washing machine field and insurance and mortgage options in mortagage field respectively.
You can use array based names like:
<select class="form-control" name="Rows[<?php echo $rows['qid']; ?>]">
and in php get it as $_POST['Rows']['mortagage'] or anything else.
all inputs will available in $_POST['Rows'] array
you can use <?= "s.th" ?> instead of <?php echo "s.th" ?>

Cannot update html text from script in php echo

I have some code like this:
<?php
echo "<script> alert('hello world!!!'); </script>";
echo "<script> document.getElementById('updatetext').innerHTML='heyatest'; </script>";
?>
<html>
<head>
</head>
<body>
<p id="updatetext">Some Text Here</p>
</body>
</html>
I need it to work this way and update the text at certain point through PHP code. In above the alert popup shows, but my text does not get updated with "heyatest"
You're calling the javascript that tries to find your id updatetext before that object exists. It cannot find it. Call the php after the html object you're looking for.
<html>
<head>
</head>
<body>
<p id="updatetext">Some Text Here</p>
</body>
</html>
<?php
echo "<script> alert('hello world!!!'); </script>";
echo "<script> document.getElementById('updatetext').innerHTML='heyatest'; </script>";
?>
The Javascript isn't calling an initiated object. Try it like this:
<html>
<head>
</head>
<body>
<p id="updatetext">Some Text Here</p>
<?php
echo "<script> alert('hello world!!!'); </script>";
echo "<script> document.getElementById('updatetext').innerHTML='heyatest'; </script>";
?>
</body>
</html>

jquery ajax not sending data in code igniter

I'm new to Codeigniter MVC framework. when i send data through ajax from views to controller this error shows click here to view the image
here is my code :
views/ajax_post_view.php :
<!DOCTYPE html>
<html lang="en">
<head>
<title>Ajax Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
$(document).ready(function(){
$(".submit").click(function(e){
e.preventDefault();
var user_name = $("input#name").val();
var password = $("input#pwd").val();
//alert(user_name);
//alert(password);
$.ajax({
type:'POST',
url:'<?php echo base_url();?>'+'index.php/ajax_controller/submit',
dataType:'json',
data:{name:user_name,pwd:password},
success:function(data){
console.log(data);
}
});
});
});
</script>
</head>
<body>
<div class="main">
<div id="content">
<h2 id="form-head">Pavan Code Igniter Ajax</h2>
<hr>
<div id="form_input">
<?php
echo form_open();
echo form_label('User Name');
$data_name = array(
'name'=>'name',
'class'=>'input_box',
'placeholder'=>'Please enter name',
'id'=>'name'
);
echo form_input($data_name);
echo "<br>";
echo "<br>";
echo form_label('Password');
$data_name = array(
'type'=>'password',
'name'=>'pwd',
'class'=>'input_box',
'placeholder'=>'Please enter Password',
'id'=>'pwd'
);
echo form_input($data_name);
?>
</div>
<div id="form_button">
<?php echo form_submit('submit','Submit','class="submit"');?>
</div>
<?php
echo form_close();
?>
</div>
</div>
</body>
</html>
controller : controllers/Ajax_controller.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Ajax_controller extends CI_Controller {
// Show view Page
public function index(){
$this->load->helper('form');
$this->load->helper('url');
$this->load->view("ajax_post_view");
}
// This function call from AJAX
public function submit() {
$data = array(
'username' => $this->input->post('name'),
'pwd'=>$this->input->post('pwd')
);
echo json_encode($data);
}
}
?>
KINDLY HELP ME THANKS IN ADVANCE
In the controller, set Access-Control-Allow-Origin at the top of your php script :
header('Access-Control-Allow-Origin: *');

JQuery form validation does not work for me

I have tested this code in http://jsfiddle.net/gLpHY/92/, in there it runs fine but when I run it in my computer it does not work. (I have tested two versions of this code once using just html and jquery and the next time I use them with php, both of them did not work for me.)
<html>
<head>
<link rel="stylesheet" href="<?php echo base_url()?>css/style.css">
<link rel="stylesheet" href="<?php echo base_url()?>css/tableCss.css">
<script type="text/javascript" scr="<?php echo base_url()?>js/jquery-1.12.0.js"></script>
<script type="text/javascript" scr="<?php echo base_url()?>js/projs.js"></script>
<script type="text/javascript" scr="<?php echo base_url()?>js/jquery.validate.min.js"></script>
<title>Questions</title>
</head>
<body>
<div class="frm"><?php $a=array("id"=>"myForm","name"=>"myForm");
echo form_open('site/search',$a); ?>
<div>
<?php echo form_label('Question:','question'); ?>
<?php echo form_input('question', set_value('question', #$_GET['question']), 'id="question"', 'name="question"'); ?>
</div>
<div>
<?php echo form_label('Category:','category'); ?>
<?php echo form_dropdown('category', $category_options, set_value('category', #$_GET['category']), 'id="category"', 'name="category"'); ?>
</div>
<div>
<?php echo form_label('Score:','score'); ?>
<?php echo form_dropdown('score_comparison', array('gt' => '>', 'gte' =>'>=' , 'eq' => '=', 'lt' => '<', 'lte' => '<='), set_value('score_comparison', #$_GET['score_comparison']), 'id="score_comparison"', 'name="score_comparison"'); ?>
<?php echo form_input('score', set_value('score', #$_GET['score']), 'id="score"', 'name="score"'; ?>
</div>
<div>
<?php echo form_submit('action','');?>
</div>
<?php echo form_close();?>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#myForm").validate({
rules: {
question: {
required: true
}
},
messages: {
question:{
required: "Please enter some text"
}
}
});
});
</script>
</body>
</html>
First off all, replace you <?php echo base_url()?> with just /. You can use relative path for resources from your site. Path should be like this: scr="/js/jquery-1.12.0.js" for all you scripts.
For second replace your string $().ready(function () { with $(function () {
Hope this helps.
Try typing in the full URL instead of using <?php echo base_url()?> as I have seen that cause problems with printing the URL twice and then the page obviously not being able to find it. Also, the way you have written .ready() is not recommended. You might want to consider adding document inside the parenthesis like this:
$(document).ready(function(){});
.ready() source

Using Javascript to load image into a div onClick

I've been trying for two days to figure out what I am doing wrong. I really think that this code should work, but it doesn't. If I swap out the variable on line 57 it will bring up a file onClick. So logically the problem is the variable. But when I trace the variable on line 60, the variable is returning the correct value. So why won't the image load correctly? When I click on the button, simply nothing happens.
++EDIT++
I've tried a bunch of things, and the problem is absolutely with the variable $file. No matter how I test it, $file corresponds to the id number of the item on the list. But when I hit the button, it always pulls item 1. I even went back and edited the code to read:
<img id="loadingImage" src="../maps/<?php echo $name['id']?>.gif" style="visibility:hidden"/>
There is no reason on earth that I can find that this isn't working. 'id' is iterating properly. So why does it think 'id'=1 only after I hit the button?
Here's the code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org /TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<html lang="en">
<head>
<meta charset="utf-8">
<title>List of Parks</title>
<link href="guide.css" rel="stylesheet" type="text/css">
<style type="text/css"></style>
<script type="text/javascript" src="../jQuery/jQuery.js"></script>
<script type="text/javascript">
<!--
function showImage() {
document.getElementById('loadingImage').style.visibility = 'visible';
}
-->
</script>
</head>
<body>
<div id="container">
<div id="state"></div>
<div id="list">
<?php foreach ($datas as $name):
{
if ($name['state'] == 'PA')
{
?>
<input type="hidden" name="id" value="<?php echo $name['id']; ?>">
<h2><?php echo htmlspecialchars($name['name'], ENT_QUOTES, 'UTF-8');?></h2>
<?php htmlspecialchars($name['site'], ENT_QUOTES, 'UTF-8');?>
<?php $link = $name['site']; ?>
<ul id="link">
<li class="l1"><?php echo "<a href=$link>$link</a>" ?></li>
</ul>
<br>
<?php echo htmlspecialchars($name['description'], ENT_QUOTES, 'UTF-8');?>
<?php echo htmlspecialchars($name['street'], ENT_QUOTES, 'UTF-8');?>
<br>
<?php echo htmlspecialchars($name['city'], ENT_QUOTES, 'UTF-8');?> ,
<?php echo htmlspecialchars($name['state'], ENT_QUOTES, 'UTF-8');?>
<?php echo htmlspecialchars($name['zip'], ENT_QUOTES, 'UTF-8');?>
<?php $file = $name['id'];
$image = '../maps/'.$file.'.gif';?>
<input type="button" value="click for map" onclick="showImage();" />
<div id="trailmap">
**<img id="loadingImage" src="<?php $image ?>" style="visibility:hidden" />**
</div>
<?php echo $image?>
<hr width="100%" size="3" black />
<?php
}
}
endforeach; ?>
</div>
</div>
<div class="fixbox">
<div id="statemap"></div>
<div id="home"></div>
<div id="guide"></div>
</div>
</body>
</html>

Categories

Resources