I am trying to execute a specific query where I search for the name that i get using javascript. I have this HTML:
<a onmouseover="showDef(textContent)" href="aLinkHere.com">myWord</a>
The function showDef gets the myWord and I'm trying to execute my query after that.
<script type="text/javascript>
function showDef(txt) {
var myWord = txt;
//Some code here to execute the query?
}
</script>
The query I want to have is as follows:
mysql_query("SELECT * FROM defs WHERE name='myWord'");
Now I have to replace the 'myWord' with the word stored in the javascript variable. Is there any way to this? I already tried the following, but that didn't work..
document.write('<?php $data = mysql_query("SELECT * FROM defs WHERE name=\''+ myWord + '\'"); ');
I am relatively new in javascript and php, so any help is very much appreciated!
Javascript is client side language and you need php (server side) lang to execute query.
Create ajax request with that variable and use that variable in your query.
return that response from your remote php file and catch response in javascript. And enjoy with response.
IF you are searching name only(exact) then use = else use LIKE or REGEXP for better performance
This is an example that uses the jQuery library.
var dataString = 'searchVar='+ myWord;
$.ajax({
type: "POST",
url: "ajax.php",
data: dataString,
cache: false,
success: function(data){
alert(data)
}
});
IN php code you jst get variable with $_POST['searchVar'] and execute your query
$qry = "SELECT * FROM defs WHERE name LIKE '%".'$myWord."%'";
and in while loop jst echo you response.
You're relatively new indeed, this is basic strings 101.
1) do NOT use document.write, it's not meant for you to be used, it's an API from a decade ago and doesn't do what you think it does. Find the element you want to set the content of (using document.getElementById or the like) and then use .innerHTML = ... to set its content.
2) To get your value in your query on the PHP side, just put it in there, it's one of the basic features of PHP:
$myword = sanitize_the_hell_out_of_this($_POST['myword'];
mysql_query("SELECT * FROM defs WHERE name='$myword'");
You can pick whatever method you like for sanitization, there are a few baked into PHP but do NOT, under ANY circumstance, pass the posted value straight to your database, unless you like people deleting your database because they can. Someone can just edit the html, change the single word to "'; drop table words; 'lo" and now your table will get dropped. fun times =)
In order for it to actually work, remember your page runs on the client's computer, and PHP is a server technology. So the javascript will have to ask the server for the data by literally asking the server: you'll need an AJAX get or post operation, and then work with the data that get back. You can't inject PHP code and then have it run on the user's computer.
Related
I am trying to use jQuery/AJAX to run a PHP script that do a delete query of table in database using predefined id. Here's the code
<script type="text/javascript">
$(document).ready(function(){
$("#clear").click(function(){
$.post("action.php?module=cart&act=del&id=$_GET[id]");
});
});
</script>
And the action.php code is:
if ($module=='cart' AND $act=='del'){
mysql_query("DELETE FROM orders_temp WHERE id_pro='$_GET[id]'")
header('Location:list.php?id=$_GET[id]');
}
But it not work. How to make it work?
First, the user Ghost pointed correctly, look to your function $.post, you are mixing post with get.
If you want send id parameter by get (url) then try something like this (i don't tested this code but if you understand and solve your question i can improve this answer):
<script type="text/javascript">
$(document).ready(function(){
$("#clear").click(function(){
var id = 2;//put here the id, may be via jquery for example
var url = "action.php?module=cart&act=del&id="+id;
$.ajax({
type: 'GET',
url: url,
data: dados,
success: function(response) {
//here you decides if you want make something with response
}
});
});
});
</script>
In your php file you get the parameter and do what you want:
$id = $_GET["id"];
if ($module=='cart' AND $act=='del'){
mysql_query("DELETE FROM orders_temp WHERE id_pro='".$id."'");
header('Location:list.php?id='.$id);
}
P.S.: Remember that you needs verify input from users, implement, prepared statements, use of issets in php variables and etc.
You have two problems:
You are mixing PHP syntax with JavaScript syntax here:
$.post("action.php?module=cart&act=del&id=$_GET[id]");
If you view the source of this page, you will find that the end of this line has not been parsed into anything useful.
As other users have pointed out, you are sending this request via POST, not GET, but you are passing this parameter in a querystring so it should still be there.But, because of the problem above, you will find that $id does not contain the ID, but a string containing "$_GET[id]". However, since you don't appear to be POSTing any parameters, better to just send this as a GET in my opinion.
I assume you want something like this:
$.get("action.php?module=cart&act=del&id=<?php echo $_GET['id']; ?>");
That way, assuming that the page on which this is being run is being parsed as PHP and assuming that id is being set to something in the querystring, that value will be parsed and added into the JavaScript.
Good luck!
Hello stackoverflow developer,
First of all, sorry if I couldn't find a solution, but I've been trying for a while now.
I'm not sure if my approach is the best one, so, if there's an alternative to AJAX and/JSON, please feel free to suggest it.
I'm creating a tourist guide website where registered users will include their resorts, restaurants and tourist attractions according to region and state. I'm using Joomla! and Seblod for this (with some custom PHP, MySQL, Javascript and AJAX). Since I don't want to manually create 27 dynamic selects, I've been trying selecting the list of registered beaches (to which resorts and tourist attractions must be related to) with PHP/AJAX/JSON/JQuery.
Everything works except populating the beach list, and I don't know what the problem is. I've tried multiple ways to append, create or add the options but nothing happens.
The PHP/JSON result is :
`
[{"id":"17","title":"Porto+de+Galinhas"},{"id":"18","title":"Serrambi"},{"id":"19","title":"Tamandar%E9"}]
`
It's the result of this PHP script:
`
if($_GET['q'] == 'beaches'){
$praiaSQL = sprintf("SELECT * FROM vp_content AS c LEFT JOIN vp_cck_store_item_content AS v ON c.id = v.id WHERE c.catid = 10 AND v.cck = 'praia' AND v.venue_state = '%s' ORDER BY c.title ASC;", $_GET['s']);
$query = mysqli_query($connection, $praiaSQL);
$praia = array();
while($results = mysqli_fetch_assoc($query)){
array_push($praia, array('id' => $results['id'], 'title' => urlencode($results['title'])));
}
echo json_encode($praia);
}
`
I also need a solution to handle accented characters. I'm trying urlencode here and decode in the JQuery, but may be the problem. When I left it as the original data, when there were accented characters the result item was empty.
This is the relevant JQuery that handles the result (where x = the select and u = the URL to get the AJAX JSON result - I've commented where the problem is in the code):
`
function setBeachList(x,u){
var theDiv = "#cck1r_" + x;
var theSelect = "#" + x;
$j(theSelect).children("option:not(:first)").remove();
$j.ajax({
url: u,
contentType: "application/json;charset=UTF-8",
success: function(data){
if(data.length){
/****
This is where I'm stuck, as I can't find a way to make sure the
data is actually being treated/handled.
I've tried alerts and all sorts of other options to populate the
select.
I know it's being called because the before: and after: functions
are working.
*****/
/*
$j.each(data, function(k, v){
var o = new Option();
var newTitle = urldecode(v.title);
$j(o).html(newTitle).val(v.id);
$j(theSelect).append(o);
});
*/
var htm = '';
for (var i = 0; i '+urldecode(data[i].title)+'';
}
$j(theSelect).html(htm);
}
},
beforeSend: function(){
$j(theDiv).hide();
},
complete: function(){
$j(theDiv).show();
},
dataType: 'json',
});
}
`
Thank you for the time and patience, I'm not an expert at any of this (not exactly a newbie, but close...).
urldecode is not a javascript function,
you can use decodeURIComponent instead of it.
it's working when you change it,
http://jsfiddle.net/MzMPK/1/
UPDATE:
I think your problem is about trying to encode accented chars, It should work without encoding them, if your all encodings are set as UTF-8.
This is a common JSON parsing silent error.
If the JSON is not well formatted, the ajax request will fail silently.
The second most common cause of this problem is the encoding. Make sure you are using UTF-8 in the page you're calling the AJAX and on the script that returns the data.
Your problem with accented data can be resolved by not encoding the data on the server side, thus not needing to unenconde on the client side.
To answer my own question:
Since I'm not and AJAX/JSON expert, I don't know if it's the expected behavior, but the responding page, which generates the AJAX result, cannot have different data than the one expected. Since I had left a regions' output, the requesting page had problems dealing with it somehow. Once I removed the unnecessary data, the select list got updated fine.
That was something I forgot to mention in my post, because I assumed that it was fine to have more than one result in the page. Using Firebug to check the code, the request was being brought fine.
Thank you all for your time, and sorry for the inconvenience...
I had to add htmlentities to the responding page, as accents returned null, although I explicitly have UTF-8 on every file...
So I have a PHP backend that pulls some data from SQL, let's just say its a list of user ID numbers.
I want to be able to display that list in an html select, via jquery, after a button click.
In an attempt to partially answer my own question, I assume that I could either have a jquery function perform an ajax request, grab the data from PHP/SQL, and then somehow spit out the select with jquery. Or, I could perhaps do the SQL query via PHP right there on the page, and somehow have the jquery function grab the output from that and put it into a select.
How would you do it?
a fill-in-the-blanks code example follows:
idea 1:
function button_click() {
$.ajax({
url: "PHP_backend.php", // this does the sql query and returns the results
type: 'POST',
data: 'returnquery',
success: function(result) {
//????? put the result array or whatever into a submit, perhaps with a foreach or something similar..??
}
}); // end ajax
}
Or idea 2:
$result = mysql_query("SELECT userIDnumbers FROM users",$db);
while ($row = mysql_fetch_array($result)){
/// throw these results into an array or similar, $userIDarray[]
/// maybe I could have this PHP create hidden html fields for each row, and insert its value, and then get that via jquery
}
function button_click() {
/// create the html select, displaying the values from the sql query
/// get values from hidden html fields?
}
if you are sure that the button will be clicked always or very most of time, idea2 is better becouse overhead of send/receive Ajax (trafic) and its delay (time) will be removed
if the web page is "public" (not for an intranet, behind a vpn), I strongly advise to not use any sql in jquery. It's simplistic to call the php ajax response file with arbitrary sql (ie what I want), and even modify anything in the data or database.
I have an ajax call made with jQuery, something like this:
$.ajax({
type: "POST",
url: ajaxurl,
data: data,
success: function(response){
alert(response);
}
});
I get data from PHP like this:
$data_array = get_data();
foreach($data_array as $data)
{
echo $data;
}
PHP to slow
The PHP data function call is slow because it gets very much data from the database, might fetch images, make some json calls and other slow things.
One loop round at the time
Therefor I need to get the PHP code just do one round, then Javascript and then do the next round in the loop.
More than one way to solve it?
There might be more than one way to do it. Which one is prefered? Javascript foreach-loop, JSON and global Javascript variables comes to mind.
You can set the return type in your ajax function as xml or json, and then return you array in either of these types. I feel that JSON js the preferred one for your solution.
I'm slightly against storing actual images in the database. I prefer to only keep a unique link for them and then return that instead of the actual image. This would speed the query up a fair bit. I agree with mad_programmer that the JSON js would be preferred for your situation.
You could manipulate your query to do a limit. So something like:
var total_count = ajax_get_sql('select statement with count');
var curr_count = 0;
var set_number = 10;
var select_statement_without_limit = 'statement';
setTimeout('fetch_data()',0);
...
function fetch_data()
{
if(curr_count < total_count)
{
ajax_get_sql(select_statement_without_limit with limit appended);
curr_count = curr_count + set_number;
setTimeout('fetch_data()',0);
}
}
With all your ajax calls set to wait for a response instead of continuing. I would keep the sql logic in PHP, but use javascript to query the server many times. This will prevent your JS script from giving long execution errors. I haven't really taken into account data manipulation, but you can probably figure it out!
im trying to adapt this little snippet:
$("#checkbox_id").change(function(){
/* CODE HERE */
});
I have a series of checkboxes that are dynamically generated and their id's are always like "hug3443" were "hug" is the column in the DB and "3443" is the unique id for each row.
My objective would be that every time the checkbox changes state to update it own state in the DB.
Can it be accomplished with jQuery?
Thank you.
I just found a script for this stuff and thought to post it here as I was checking this page a while ago until I finally came across to this script. Tested it and worked like a charm and I have inserted it in my coding library. Enjoy, folks.
http://www.jooria.com/Tutorials/ajax-20/jquery-live-checkbox-inputs-with-animation-effects-158/
Yes. Use live events to attach the change event handler to your checkboxes (so that dynamically added checkboxes will be handled also). Then simply do a AJAX request inside the event handler passing your script the new state and the name/id of the checkbox (you can then "parse" the id and column name in the script).
Not without a server side script that would deal with the data changes.
jQuery is a client side javascript framework and doesn't have direct access to mysql, which is a server side daemon.
Have a look into pairing jQuery with php and mysql.
Code in javascript you write with the use of jQuery is executed on the client-side in a browser. A solution is from your script to make a call to a server page that will execute a MySQL update . For example like this.
$("#checkbox_id").change(function(){
$.ajax({
type: "POST",
url: "/page-that/makes/update.php",
data: {param1:value1}
});
});
You should write some server-side code for managing database (php, ruby, whatever).
You should create something like API, which means, that server-side script needs to get some variables, which sended to it from clients (id's of rows, name and value of columns for example).
And after that you should write your jQuery frontend script, which will request server-side script for managing database tables. For requests you can use AJAX technology, something like this:
$.ajax({
url: 'http://somesite.com/path/to/server/side/script',
type : 'POST',
success: function (data, textStatus) {
alert('yahoo! we get some data from server!' + data);
}
});
You can get the value of the id of the checkbox using javascript you can then split the name into the field name and id value. For this example I've added a - into id to give a seperator
(I think you may need to use the click event rather than change, think change may only work for drop down menus)
$("#checkbox_id").click(function(){
var checkbox_id = $(this).attr("id");
var id_bits = checkbox_id.split("-");
// this would split hug-3443 into hug and 3443 setting id_bits[0] = hug and id_bits[1] = 3443
$.post("update,php",
{
row: id_bits[0],
id: id_bits[1]
}
);
});