I am using the great tutorial provided by Nodstrum. I am attempting to autofill multiple text fields with PHP, MYSQL, and AJAX. I have a PHP script, here is the line of code returning my results:
echo '<li onClick="fill(\''.$result->name.'|'.$result->id.'\');">'.$result->name.'</li>';
Notice that I am seperating my results with a pipestem character.
Here is the function where I am receiving the error 'Undefined or not an object' I am breaking out the values and using the pipestem as splitting the values from mysql.
function fill(thisValue) {
myvalues=thisValue.split('|') {
$('#inputString').val(myvalues[0]);
$('#email').val(myvalues[1]);
}
window.setTimeout("$('#suggestions').hide();", 200);
}
If I 'ok' the error messages, I will eventually see both values displayed in the text fields, so I believe I am retreiving the values properly from MySQL. I appreciate any help anyone can provide to get me steered in the right direction, or a fresh perspective.
Thanks Again,
--Matt
The value you are passing that becomes thisValue is null or undefined. You can test this parameter before blindly trying to .split it (the split function works only on strings).
function fill(thisValue) {
// "value" will always be a string
var value = thisValue ? String(thisValue) : '';
// this line will not generate an error now
var myvalues=value.split('|');
// but these ones might! make sure the length of myvalues is at least 2
if (myvalues.length >= 2) {
$('#inputString').val(myvalues[0]);
$('#email').val(myvalues[1]);
}
// this might need to go inside the above if
window.setTimeout("$('#suggestions').hide();", 200);
}
Try this:
function fill(thisValue) {
myvalues=thisValue.split('|');
$('#inputString').val(myvalues[0]);
$('#email').val(myvalues[1]);
window.setTimeout("$('#suggestions').hide();", 200);
}
Related
I am posting a form to a script with this code:
foreach($_POST as $k=>$v){
if(!is_array($v)){$$k=dbenc($v);} else{$$k=$v;}
$_SESSION["cat"][$k]=$v;
}
$url=vlookup("url","cat","cat=$cat");
// $cat is an integer which originated from the same field value and has been re-posted
"vlookup" is:
function vlookup($field,$table,$criteria){
global $link;
if($table<>""){$from="FROM $table";}
if($criteria<>""){$criteria="WHERE $criteria";}
$r=mysqli_query($link,"SELECT $field as v $from $criteria") or die("VLOOKUP FAILED: $field $from $criteria".mysqli_error($link));
$n=mysqli_num_rows($r);
if($n>0){
$row=mysqli_fetch_assoc($r) or die(mysqli_error($link));
return $row["v"];
}
}
The problem is that
print($cat);exit;
gives the expected result, but $cat does not appear in function output such as
showerror("$cat not found");
and the "vlookup" relying on it produces an error suggesting there is nothing after the =
Printing the query in the error report confirms the absence of the $cat value in the vlookup function.
This makes no sense!
Any thoughts or advice appreciated.
As per my comment above, the problem seems to be the use of false in
if (strpos($value," ")!==false && ...)
after the vlookup using $cat
If I test for spaces without using !==false in combination with other tests, dynamic variables appear as normal. Not sure if this is to be expected?
i want to replace a string with database function if it exists. i am using str_replace in following way but it doesn't work for me, this is returning $numOne as it was. i am beginner in php so help me
function stringreplace($multiple,$numOne){
$multiple=Multiply;
$numOne=a_b_cMultiply;
str_replace($multiple,"abcdfgh('','')::numeric",$numOne);
return $numOne;
}
Your code is not correct as you are not storing the result anywhere and also you are returning $numOne which contains the old value . Use this code:
function stringreplace($multiple,$numOne){
$multiple='Multiply';
$numOne='a_b_cMultiply';
$num_one = str_replace($multiple,"abcdfgh('','')::numeric",$numOne);
return $num_one;
}
I am trying to grasp the concept of PHP functions. I know how to create one.
function functionName()
{
//code to be executed;
}
I also know how to call a function. I am just a little confused as to what a parameter is for. I have read the php manual and w3schools.com's tutorial. From my understanding, you need a parameter to pass a value to the function? If that is correct why not just create it within the function? Why use a parameter?
Like this:
<?php
function num()
{
$s=14;
echo $s;
}
num();
?>
I know you can do:
<?php
function num($s=14)
{
echo $s;
}
num();
?>
or:
<?php
function num($s)
{
echo $s;
}
num($s=14);
?>
Could someone give me a real application of using a parameter, for say maybe a user based dynamic content website? I think it would help me understand it better.
Passing a parameter allows you to use one function numerous times. For example:
If you wanted to write ONE function that sent mail - you could pass the following parameters:
$to = $_POST['to'];
$from = $_POST['from'];
$subject = $_POST['subject'];
Then, in your function:
function sendmail($to, $from, $subject){
//code to be executed
}
Now you can reuse your send function at various points in your web app.
Here is an example, say you have numbers representing colors (this is common in storing data in a database) and you want to output what number represent's what color.
Say you had to do this a hundrend times for a hundred numbers.
You'd get pretty tired writing 100 if statments 100 times.
Here is a function example...
function colorType($type) {
if ($type == 1) {
return "Green";
}
elseif ($type == 2) {
return "Blue";
}
elseif ($type == 3) {
return "Red";
}
// etc
}
echo colorType(1) . "<br>"; // Green
echo colorType(2) . "<br>"; // Blue
echo colorType(3) . "<br>"; // Red
A function does something, and gives a result. It may accept parameters to arrive at that result, it may not. The simple calculator, as aforementioned, is a good one.
The easiest way to understand functions and parameters is to just read the PHP manual—most of the functions in the core PHP language take parameters of some sort. These functions are no different to the functions you write.
Let's assume you want to create a function that will allow people to sum numbers, you can't write needed variables in functions because you want others to input it and your function shows output:
function add($num1, $num2){
return $num1 + $num2;
}
Now anyone can call/use your function to sum numbers:
echo add(5,1); // 6
echo add(2,1); // 3
echo add(15,1); // 16
That's the most simplest example one can give to explain why you need parameters :)
When you specify function name($var=VALUE), you are setting a default.
function doit($s=14) {
return $s + 5;
}
doit(); // returns 19
doit(3); // returns 8
it makes your functions flexible to be reused in various situations, otherwise you would have to write many functions, one for each scenario. this is not only tedious, but becomes a nightmare if you have to fix something in those functions. instead of fixing it in one place, you would have to fix it in many places. you basically never want to have to copy paste code you have already written, instead you use arguments to make one set of the code flexible enough to handle each situation.
Paramaters allow your function to see the value of variables that exist outside of itself.
For example:
function F_to_C($temp) {
$temp = ($temp - 32) / 1.8;
return $temp;
}
$temperature = 32;
$new_temperature = F_to_C($temperature); // 0
echo $temperature;
$temperature2 = F_to_C(212); // 100
echo $temperature2;
Here we take $temperature, which we define in the code, but could be user input as from a form, and then send it to the function F_to_C. This allows us to convert it to Celsius, so we can then display it thereafter. In the next section, we then re-use the function to convert the boiling point, which is sent directly this time as the value 212. If we had embedded $temperature = 32 in the function the first time, then we would still get 0 as a result. However since we're using parameters, we instead get 100 back, because it's processing the value we specified when we invoked the function.
I am new to Jquery and want some help from you guys.
i want to decode json data in jquery as i am able to pass data from php to ajax but after it came back in jquery it is not parsing it says undefined. the code is bellow
JavaSript file
$.post("GetData.php", function(data) {
if(data==false)
var tpl = '<p>no record found<p>'
else
var tpl = DrawTableRowsforSection(data);
$("#result").append($(tpl));
},"json");
function DrawTableRowsforSection(p)
{
alert(p.id[0]);
var o = '<table>';
for (var i = 0; i < p.length; i++)
alert(p.id[i]);
o += '<tr><td>'+p.id[i]+'</td><td>'+p.section_name[i]+'<td></tr>';
o+='</table>'
return O;
}
PHP Script
header('Content-Type: application/json');
mysql_connect('localhost','root','') ;
mysql_select_db('news');
session_start();
$query = 'select id,section_name from section';
if ($result = mysql_query($query)) {
if (!mysql_num_rows($result)==null) {
$myArray = array();
while ($row = mysql_fetch_assoc($result)) {
$id = ToSring($row['id']);
$myArray[] = $row;
}
echo json_encode($myArray);
}
}
The database has a table named section
fields are as follows
id int(11)
section_name varchar(20)
There are total 5 records there.
What I want is to populate a table using returned data.
Can any one guide me where I am making mistake
Regards
Kashif Afzaal
Be sure that mysql returns results and you can take them through ajax.
Also, I've seen the following mistake:
You are using the variable tpl wrong. It is just a js variable, no need to use $ .
Use this way:
$("#result").append(tpl);
OK, from the top in the PHP script:
The MySQL extension is ancient and decrepit. Use MySQLi or PDO.
You never handle a failed MySQL query, so the response will quite possibly be empty. In 99% of cases, any if block should have a corresponding else block.
The result of mysql_num_rows() is never null. Do if (mysql_num_rows($result) > 0), or better yet, just if (mysql_num_rows($result)).
Never do if (!something == something) - it rarely does what you want it to. Do if (something != something)
You never handle mysql_num_rows() failing/giving no rows, so (again) the response will quite possibly be empty.
You never do anything with the $id variable you create.
I'm pretty sure ToSring should read ToString. But there's actually no such function in PHP - you would have either define it or invoke it as a method of a class/object. Indeed, this is likely to be the problem, as it will result in a fatal error.
I use the latest code igniter (2.0.3) and php-active 0.0.1.
All are working fine except save();
Code:
if($_POST)
{
$entry= Customers::find_by_routeid('4');
$entry->routeid=5;
$entry->save();
}
Here's my problem: for some reason that I cannot understand the above code does not work, but if I take the code out of if ($_POST), it works fine.
What I am doing wrong?
EDIT:
Thanks Damien Pirsy $this->input->post() does the trick, but when I uncomment the comments in the code the problems returns.
The code now is:
if($this->input->post())
{
$id = $this->input->post('id');
$oldRoute = $this->input->post('oldRoute');
$newRoute = $this->input->post('newRoute');
$entry= Customers::find_by_routeid($this->input->post('oldRoute'));
$entry->routeid=$this->input->post('newRoute');
$entry->save();
/*
if($oldRoute<$newRoute)
{
for ($i=$newRoute; $i>$oldRoute; $i--)
{
$element = Customers::find_by_routeid($i);
echo $element->routeid -= 1;
$element->save();
}
}
*/
}
The elements new IDs ($element->routeid -= 1;) are echoing right, but I have the same problem as in the beginning and neither of two saves work.
You didn't provide much details or debug info, so I'll just guess: try using the CI's native post handler instead. You should have var_dump()ed the $_POST array, see if isset() or not, also, since you're using it as a condition
if($this->input->post())
{
//...
}
UPDATE:
Since we're talking about Post variables, don't assume they're exactly as you want them. Keep in mind that $this->input->post('field') returns FALSE when the index is not present; that might well brake your if condition.
Assuming you need numbers to do this, you can do a check like
if($this->input->post('newRoute') AND is_numeric($this->input->post('newRoute'))
{
$newRoute = $this->input->post('newRoute');
}
else
{
// give it a default value, or raise an error, for example. If you need this
// variables, and need them to be numbers, you cannot go on in case these
// conditions are not met, right?
}
And the same for $oldRoute.
And yeah, OK, maybe you can write a cleaner code than mine, but you get the picture ;)