javascript code is not being executed - php

I am working on this project in which I am trying to get a returned value so I can autofill my input boxes according to what the client selects.
This code however is not executing and I do not know why. When I remove the src="jquery area" $(#dropdown).on is an undefined method; not to sure what to do.
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js">
//$.post(url, [data], [callback], [callback type])
("#dropdown").on('change', function() {//when you select something from the dropdown function run and will switch the data
$.post("backgroundScript.php", {
uid: $(this).val()
},
function(data) {
$("#first").val(data.first);
$("#last").val(data.last);
// etc.;
}, 'json'
);
});
</script>
Here's my full code
try {
# MySQL with PDO_MYSQL
$DBH = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
//$DBH->prepare('SELECT first FROM contacts');
}
catch(PDOException $e) {
echo "I'm sorry, I'm afraid I can't do that.";
file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
}
//get query
$FNresult=$DBH->query('SELECT first FROM contacts');
//set fetch mode
$FNresult->setFetchMode(PDO::FETCH_ASSOC);
$dropdown = "<select name='contacts' id='contacts' >";
while($row =$FNresult->fetch()) {
$dropdown .= "\r\n<option value='{$row['first']}'>{$row['first']}</option>";
// echo getLN();
}
$dropdown .= "\r\n</select>";
echo $dropdown;
//}
/*
// Get last name
function getLN(){
$query = "SELECT last FROM contacts";
$LNresult=mysql_query($query);
$last;
while($row = mysql_fetch_assoc($LNresult)) {
$last = "{$row['last']}";
}
echo $last;
}//end getLN
*/
$DBH = null;
?>
<!-- javascript on client-side -->
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js">
//$.post(url, [data], [callback], [callback type])
("#dropdown").on('change', function() {//when you select something from the dropdown function run and will switch the data
$.post("backgroundScript.php", {
uid: $(this).val()
},
function(data) {
$("#first").val(data.first);
$("#last").val(data.last);
// etc.;
}, 'json'
);
});
</script>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js">
/*("#dropdown").on('connection', function (stream) {
console.log('Ah, we have our first user!');
});*/</script>
<form action="insert.php" method="post">
First Name: <input type="text" id="first" name="first"><br>
Last Name: <input type="text" id="last"><br>
Phone: <input type="text" id="phone"><br>
Mobile: <input type="text" id="mobile"><br>
Fax: <input type="text" id="fax"><br>
E-mail: <input type="text" id="email"><br>
Web: <input type="text" id="web"><br>
<input type="Submit">
</form>
here is my new edited script on output page =
<script type="text/javascript"
src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
//$("#dropdown-parent").on('change','#dropdown', function() { // replace dropdown-parent
$("#contacts").on('change','#dropdown', function() {
$.post("backgroundScript.php", {
uid: $(this).val()
},
function(data) {
$("#first").val(data.first);
$("#last").val(data.last);
// etc.;
}, 'json'
);
});
</script>
here is the php file for backgroundScript.php =
<?
// background script
// retrieve data based on $_POST variable, set to $returnArray
$returnArray = $_POST[array(
'first' => firstName,
'last' => lastName,
)];
/****************************
* the structure of returnArray should look something like
array(
'first' => firstName,
'last' => lastName,
)*/
echo json_encode($returnArray);
?>
this file will send in info so the javascript will then replace form fields with what ever is held in the areas appointed

It would appear that your PHP script is returning some formatted html, which you then try to insert into the dom via .val(). That method is used to set the values of form fields, not insert entire chunks of html. Try using .append() or .html() instead, plus do what Phil suggested above - split your script into multiple blocks.

You need to include your jQuery prior to using it:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
// Your Code Here
</script>
Better yet would be to use external JS:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="js/site.js"></script>
And if you're using HTML5 the type="text/javascript" isn't even needed so:
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="js/site.js"></script>
Even better still would be to use a jQuery CDN:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="js/site.js"></script>
Also, as others have noted, be sure to use $ at the beginning of your jQuery factories. i.e. $('#dropdown')
-- Update --
Further clarification on project tree, most basic project trees look like this:
root/
|--css/
|--images/
|--js/
|--site.js
|--index.html
-- Update 2 --
Example of a $.post
$.post({
'somescript.php', // Script your posting to
{
someParam1: someData1, // $_POST['someParam1']
someParam2: someData2
// etc etc
},
function(response){
// Do something with JSON response upon successful post
alert(response);
},
'json' // Tells the script that JSON will be returned
});
-- Update 3 --
Okay so basically you want to do is...
Javascript:
var dropdown = $('#dropdown');
dropdown.bind('change', function(){
$post.(
'backgroundScript.php',
{
first: dropdown.val()
},
function(response) {
$('#first').val(response.first);
$('#last').val(response.last);
// Repeat for all of your form fields
},
'json'
);
});
Receive POST param:
$firstName = $_POST['first'];
MySQL query would be something like the following:
$sth = $dbh->prepare('SELECT *
FROM contacts
WHERE first = :first');
$sth->bindParam(':first', $first, PDO::PARAM_STR);
$sth->execute();
Then add all of your MySQL fields into associative array array(key => value) and then json_encode and return array.

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$("#dropdown-parent").on('change','#dropdown', function() { // replace dropdown-parent
$.post("backgroundScript.php", {
uid: $(this).val()
},
function(data) {
$("#first").val(data.first);
$("#last").val(data.last);
// etc.;
}, 'json'
);
});
<script>
In your PHP you should have something like this
echo json_encode(array('first' => $some_value, 'last' => "Other value"));

Shouldn't
("#dropdown").on('change', function() {
be
$("#contacts").on('change', function() {

Related

How to send values of Select button from Mysqli database and send to second pages?

I tried to coding it. I am still getting stuck over it. The main goal was if user select value from mysqli database selected it and send the values to other pages. I know people recommend it use by AJAX. I tried to use it. still not working. I'll put details code below.
Main pages Code(main.php)-
<?php
session_start();
$conn=mysqli_connect('localhost','root','','user');
if(!$conn){
die('Please check an Connection.'.mysqli_error());
}
$resultset=$conn->query("SELECT name from newtable"); ?>
<!DOCTYPE html>
<head><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
</head>
<body>
<center>
Select DataBase to Insert it<select name="tables" id="tables">
<?php
while($rows=$resultset->fetch_assoc()){
echo'<option value='.$rows['name'].'>'.$rows['name'].'</option>';
}
?>
</select>
click
</center>
<script type="text/javascript">
$(document).ready(function(){
var search='';
$("#tables option:selected").each(function() {
if ($(this).attr('value') !== '') {
search=$(this).attr('value');
}
});
$("a").click(function() {
$.ajax({
method: 'post',
url: 'database1.php',
data: {key:search},
beforeSend: function() {
$('body').css("opacity", "0.3");
},
success: function(response) {
alert(response);
},
complete: function() {
$('body').css("opacity", "1");
}
});
});
});
</script>
</body>
</html>
as alert box i am getting value of it but second pages get error that key value doesn't exist. here the second one pages (database1.php) -
<?php
$conn=mysqli_connect('localhost','root','','user');
session_start();
if(!$conn){
die('Please check an Connection.'.mysqli_error());
}
$database=$_POST['key'];
echo'You Selected'.$database.'from table';
$sql = "SELECT * FROM $database";
$result=mysqli_query($conn,$sql);
if($result){
echo'Worked';
}else{
echo'ERROR!';
}
?>
so what the problem occurred?
UPDATED ANSWER
Thanks to #swati which she mentioned that use form tag instead of AJAX (i know its simple answer) still by the way thanks for answer. :)
UPDATED CODE FULL -
<body>
<form action="database1.php" method="GET">
<center>
Select DataBase to Insert it<select name="tables" id="tables">
<?php
while($rows=$resultset->fetch_assoc()){
echo'<option
value='.$rows['name'].'>'.$rows['name'].'</option>';
}
?>
</select>
<input type="submit">
</center>
</form>
</body>
SECOND PAGE(database1.php) CHANGES LITTLE -
$database=$_GET['tables'];
You are calling each loop on page load that will give you the already selected value not the value which is selected by user.Also , this loop is not need as you have to pass only one value .
Your script should look like below :
<script type="text/javascript">
$(document).ready(function() {
//no need to add loop here
var search = '';
$("a").click(function() {
search = $("#tables option:selected").val(); //getting selected value of select-box
$.ajax({
method: 'post',
url: 'database1.php',
data: {
key: search
},
beforeSend: function() {
$('body').css("opacity", "0.3");
},
success: function(response) {
alert(response);
},
complete: function() {
$('body').css("opacity", "1");
}
});
});
});
</script>
Also , as you are using ajax no need to give href="database1.php" to a tag because you are calling this page using ajax .i.e: Your a tag should be like below :
<a>click</a>
And whatever you will echo in php side will be return as response to your ajax .So , your alert inside success function will show you that value.

How to filter a JSON page feeding data to Select2?

I'm trying to populate a Select2 box with data from a t-sql query. The query is run on a PHP page which translates the output to JSON and is called in the javascript of the main page.
The main page looks like this:
<?php
header('Content-type: text/html; charset=UTF-8');
require('db.php'); // Bring in the database connection
include("auth.php"); // Make sure the user is logged in to an account
?>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" http-equiv="Content Type" charset="utf-8"/>
<!-- JQuery -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- SELECT 2 -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
</head>
<body style="background-color: #F5F5F5;">
<select class="js-data-example-ajax">
</select>
<script>
$('.js-data-example-ajax').select2({
width: '250px',
ajax: {
url: 'http://10.1.248.41/TFM-Project/ImportINjson.php',
dataType: 'json'
// Additional AJAX parameters go here
}
});
</script>
</body>
</html>
My JSON page looks like this:
<?php
require('db.php'); // Bring in the database connection
include("auth.php"); // Make sure the user is logged in to an account
$search = $_GET['search'];
//JSON Table Stuff
$sql = "SELECT DISTINCT [IN] AS id, Nom as text
FROM dbo.[TFM_NumérosIN2012]
;";
$stmt = sqlsrv_query($con,$sql);
$result = array();
do {
while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$result[] = $row;
}
} while (sqlsrv_next_result($stmt));
sqlsrv_free_stmt($stmt);
$data2 = json_encode($result);
echo '{ "results":' . $data2 . '}';
?>
The data output by the JSON page looks like this:
{ "results":[{"id":2,"text":"SMITH Sean"},{"id":3,"text":"CHARLES charley"},{"id":4,"text":"TFC Madrid"},{"id":5,"text":"VAN DAMME jean claude"}]}
The data is loading into the select list without any problems. However, I've tried to filter the data multiple ways and nothing has worked. I've tried adding a data parameter and passing a search variable to the php/JSON page and referencing in the $sql variable as a where clause, but this doesn't return anything
To try and filter the data I changed the javascript to this:
$('.js-data-example-ajax').select2({
width: '250px',
ajax: {
url: 'http://10.1.248.41/TFM-Project/ImportINjson.php',
dataType: 'json',
data: function (params) {
var query = {
search: params.term
}
// Query parameters will be ?search=[term]&type=public
return query;
}
}
});
But this breaks my select and and it displays a message 'The results could not be loaded.'
Does anyone know what I'm doing wrong here?
Cheers,
At the end of your php file just echo the following line :
echo json_encode($result);
In your html/js file :
<link href='https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css' rel='stylesheet' type='text/css'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js'></script>
<select name='js-data-example-ajax' class='js-data-example-ajax'></select>
$(document).ready(function()
{
$('.js-data-example-ajax').select2({
placeholder: "Search for product",
minimumInputLength: 1,
width: '250px',
ajax: {
url: 'http://10.1.248.41/TFM-Project/ImportINjson.php',
dataType: 'json',
data: function (params) {
var query = {
search: params.term,
type: 'public'
}
console.log("query : "+query.search);
return query;
},
processResults: function (response) {
console.log("response : "+response);
return {
results: $.map(response, function(obj) {
console.log("response obj.id: "+obj.id);
console.log("response obj.text: "+obj.text);
return { id: obj.id, text: obj.text };
})
};
},
cache: false
}
});
});

JSON, PHP & SQL implementation error

I'm trying to work out how to use JSON, php and SQL (initially MSSQL) to populate a type-ahead field of names and, once the name is selected, to also populate a job title and department. This is my first time to use JSON, so I'm starting a bit from scratch here.
I got a partial solution from Experts Exchange (see Fiddle) using static data, but I'm having trouble converting the data I'm pulling from the database to what is being shown in the fiddle.
The code for the fiddle is:-
<!DOCTYPE html>
<html>
<head>
<title>Autocomplete Textbox Demo | PHP | jQuery</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(function() {
var availableTags = [{
empName: "A1",
empTitle: "AAA1 AAAAA"
}, {
empName: "A2",
empTitle: "AAA2 AAAAA"
}, {
empName: "B",
empTitle: "AAA AAAAA"
}, {
empName: "C",
empTitle: "AAA AAAAA"
}];
var empNames = [];
var empTitles = [];
$(availableTags).each(function(ix, v) {
empNames.push(v.empName);
empTitles.push(v.empTitle);
});
$("#empName").autocomplete({
source: empNames,
autoFocus: true,
select: function(event, ui) {
//console.log(event);
//console.log(ui);
//console.log(getTitle(ui.item.label));
$("#empTitle").val(getTitle(ui.item.label));
}
});
$("#empTitle").autocomplete({
source: empTitles,
autoFocus: true,
select: function(event, ui) {
//console.log(event);
//console.log(ui);
//console.log(getName(ui.item.label));
$("#empName").val(getName(ui.item.label));
}
});
function getName(t) {
//console.log("title:" + t);
for (k in availableTags)
if (availableTags[k].empTitle == t) return availableTags[k].empName;
};
function getTitle(n) {
//console.log("name:" + n);
for (k in availableTags) {
//console.log("k:" + availableTags[k].empName + " > " + availableTags[k].empTitle);
if (availableTags[k].empName == n) return availableTags[k].empTitle;
}
};
});
</script>
</head>
<body>
<label>Department Name</label></br>
<input id="empName" type="text" size="50" /><br>
<input id="empTitle" type="text" size="50" />
</body>
</html>
I'm stuck now on implementing the results returned from the database query to work with the fiddle. I believe I've to the data correctly formatted but it's wrong somewhere and I'm not sure where that is.
I'm getting the data from an SQL table with a separate php page called fetchEmpName.php:-
<?php
require('i_PDOConnection.php');
$query = "SELECT empFName + ' ' + empLName as [empName], empTitle, empDept FROM tbl_CouncilStaff WHERE active = 1 AND display = 1 AND (empFName LIKE '%".$search."%' OR empLName LIKE '%".$search."%') ORDER BY empLName";
$stmt = $dbh->prepare($query);
$stmt->execute();
$data = $stmt->fetchAll();
$return_arr = array();
$return_arr['contacts'] = array();
foreach ($data as $row) {
$dataArray['empName'] = $row['empName'];
$dataArray['empTitle'] = $row['empTitle'];
array_push($return_arr['contacts'],$dataArray);
}
echo json_encode($return_arr);
?>
Which (according to the Chrome console log, produces an array like:
{empName: "Bob Smith", empTitle: "Chief Cook and Bottle Washer"}
Which works properly when I replace the fiddle data with the generated data but fails once the static data is replaced by the sql code. So that tells me that the problem lies in the script. At this point, the page has morphed into:
<!DOCTYPE html>
<html>
<head>
<title>Autocomplete Textbox Demo | PHP | jQuery</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(function() {
var availableTags = <?php include('fetchEmpName2.php'); ?>;
var empNames = [];
var empTitles = [];
$(availableTags).each(function(x, y) {
empNames.push(y.empName);
empTitles.push(y.empTitle);
});
$("#empName").autocomplete({
source: empNames,
autoFocus: true,
select: function(event, ui) {
// console.log(event);
// console.log(ui);
// console.log(getTitle(ui.item.label));
$("#empTitle").val(getTitle(ui.item.label));
}
});
$("#empTitle").autocomplete({
source: empTitles,
autoFocus: true,
select: function(event, ui) {
//console.log(event);
//console.log(ui);
//console.log(getName(ui.item.label));
$("#empName").val(getName(ui.item.label));
}
});
function getName(t) {
//console.log("title:" + t);
for (k in availableTags)
if (availableTags[k].empTitle == t) return availableTags[k].empName;
};
function getTitle(n) {
//console.log("name:" + n);
for (k in availableTags) {
//console.log("k:" + availableTags[k].empName + " > " + availableTags[k].empTitle);
if (availableTags[k].empName == n) return availableTags[k].empTitle;
}
};
console.log(availableTags);
});
</script>
</head>
<body>
<label>Department Name</label></br>
<input id="empName" type="text" size="50" /><br>
<input id="empTitle" type="text" size="50" />
</body>
</html>
When I run the page, the jquery library throws an error saying
jquery-ui.min.js:8 Uncaught TypeError: Cannot read property 'label' of undefined"
I hope this is enough for someone to sort out where I'm off track - or if there is a better way to solving the problem of filling additional fields from a type-ahead field.
Thanks in advance - any assistance offered would be greatly appreciated.

jQuery - Pass variable to php

I'm very new to this and I've searched around all day today to get it working but I haven't managed to find a way to use a variable, only hard-coded values work. Here is my code with a hard-coded value:
<script type="text/javascript">
FB.Event.subscribe('edge.create',
function(response) {
$.post("http://www.my-domain.com/fbtest.php", { category: "845" } );
}
);
</script>
What I'd like to have is change that 845 value to a variable called $vpostid. When I change it to that it doesn't work, so I assume I need to get the double quotation marks around the number but I can't see to get the correct combination.
I'm assuming you mean "pass variable from php":
If short hand openings are enabled:
<script type="text/javascript">
FB.Event.subscribe('edge.create',
function(response) {
$.post("http://www.my-domain.com/fbtest.php", { category: "<?=$vpostid?>" } );
}
);
</script>
else:
<script type="text/javascript">
FB.Event.subscribe('edge.create',
function(response) {
$.post("http://www.my-domain.com/fbtest.php", { category: "<?php echo $vpostid; ?>" } );
}
);
</script>
try this code:
<script type="text/javascript">
FB.Event.subscribe('edge.create',
function(response) {
$.post("http://www.my-domain.com/fbtest.php", { category: "<?php echo($vpostid); ?>" } );
}
);
</script>

Ajax Call with Post in PHP

<!doctype html>
<html>
<head>
<title>jQuery Tagit Demo Page (HTML)</title>
<script src="demo/js/jquery.1.7.2.min.js"></script>
<script src="demo/js/jquery-ui.1.8.20.min.js"></script>
<script src="js/tagit.js"></script>
<link rel="stylesheet" type="text/css" href="css/tagit-stylish-yellow.css">
<script>
$(document).ready(function () {
var list = new Array();
var availableTags = [];
$('#demo2').tagit({tagSource:availableTags});
$('#demo2GetTags').click(function () {
showTags($('#demo2').tagit('tags'))
});
/*
$('li[data-value]').each(function(){
alert($(this).data("value"));
});*/
$('#demo2').click(function(){
$.ajax({
url: "demo3.php",
type: "POST",
data: { items:list.join("::") },
success: alert("OK")
});
});
function showTags(tags) {
console.log(tags);
var string = "";
for (var i in tags){
string += tags[i].value+" ";
}
var list = string.split(" ");
//The last element of the array contains " "
list.pop();
}
});
</script>
</head>
<body>
<div id="wrap">
<?php
$lis = $_POST['items'];
$liarray = explode("::", $lis);
print_r($liarray);
?>
<div class="box">
<div class="note">
You can manually specify tags in your markup by adding <em>list items</em> to the unordered list!
</div>
<ul id="demo2" data-name="demo2">
<li data-value="here">here</li>
<li data-value="are">are</li>
<li data-value="some...">some</li>
<!-- notice that this tag is setting a different value :) -->
<li data-value="initial">initial</li>
<li data-value="tags">tags</li>
</ul>
<div class="buttons">
<button id="demo2GetTags" value="Get Tags">Get Tags</button>
<button id="demo2ResetTags" value="Reset Tags">Reset Tags</button>
<button id="view-tags">View Tags on the console </button>
</div>
</div>
</div>
<script>
</script>
</body>
</html>
This code will just transfer the list of items in the dostuff.php but when I try to print_r it on PHP nothing won't come out. why is that?
I am doing an ajax request on this line
$('#demo2').click(function(){
$.ajax({
url: "demo3.php",
type: "POST",
data: { items:list.join("::") },
success: alert("OK")
});
});
and the code in PHP
<?php
$lis = $_POST['items'];
$liarray = explode("::", $lis);
print_r($liarray);
?>
This is just a shot in the dark, given the limited information, but it would appear that you're expecting something to happen with the data sent back from the server.. but you literally do nothing with it. On success, you have it display an alert... and nothing else.
Try changing your success entry to the following:
success: function(data) {
$("#wrap").html(data);
}
This will fill the div with the data from the POST request. The reason it shows up as nothing as it is..., you aren't loading the currently executing page with the data needed for the print_r to actually echo anything.
Edit: How to insert values into database;
Database interaction now-a-days is done with either custom wrappers, or the php Data Object, also referred to as PDO, as opposed to the deprecated mysql_* functions.
First, you prepare your database object, similar to how a connection is done in the aforementioned deprecated functions:
$dbh = new PDO("mysql:host=hostname;dbname=database", $username, $password);
Then, you can begin interaction, preparing a query statement..
$stmt = $dbh->prepare("UPDATE table_name SET column1 = :column1 WHERE id = :id");
Binding a parameter in said statement..
$stmt->bindParam(':column1', $column1);
$stmt->bindParam(':id', $id);
$id = $_POST['id'];
And finally executing the query:
try {
$stmt->execute();
}
catch (Exception $e) {
echo $e;
}
PDO auto-escapes any strings bound in the prior statements, making it save from SQL-injection attacks, and it speeds up the process of multiple executions. Take the following example:
foreach ($_POST as $id) {
$stmt->execute();
}
Since the id parameter is already bound to $id, all you have to do is change $id and execute the query.
Where where you expecting the PHP result of print_r to "come out"?
Try changing your AJAX call to this (only the value of success is different):
$.ajax({
url: "demo3.php",
type: "POST",
data: { items:list.join("::") },
success: function(data, textStatus, jqXHR){
alert(data);
}
});
With this, the output of your PHP template, which you would normally see if you posted to it the old fashioned way (ie. with a form and a full page reload), will display in an alert.
Hope that helps.
Try to add encodeURI for the jQuery part,
$.ajax({
url: "demo3.php",
type: "POST",
data: { items: encodeURIComponent (list.join("::")) },
success: function(response) {
console.log(response);
}
});
And urldecode for the PHP part:
$lis = $_POST['items'];
$liarray = explode("::", urldecode($lis));
print_r($liarray);
3 things:
Set your AJAX's success to show the echos/prints given in your PHP script
success: function(result)
{
$("#somecontainer").html(result);
}
That way ANYTHING that gets printed in a PHP script otherwise, will be put in i.e.
<div id="somecontainer">
Result of PHPcode here
</div>
Second, instead of
var string = "";
for (var i in tags)
{
string += tags[i].value+" ";
}
var list = string.split(" ");
//The last element of the array contains " "
list.pop();
use push(). This adds the value at the next unoccupied index in the array:
var string = "";
for (var i in tags)
{
list.push(tags[i].value);
}
That way you don't have to pop the last element off.
Third point: put your PHP code in a separate file (and your JavaScript/jQuery as well). Have like:
/root/index.html
/root/script/dostuff.php
/root/script/myscript.js
then let your AJAX call to url: "/script/dostuff.php"

Categories