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!
Related
I want to know how to send variables from javascript to php so i can create a variable that contains dynamic sum of rows.
More specific:
When I search in my search box, i want to get the number of rows (1 match is 1 row, 2 matches is 2 rows and so on
I tried to implement this: document.getElementById("i1").value = allCells.length; so i later could call in the php, but i did not work.
This is my javascript, by the way the javascript works perfectly.
<script language="javascript" type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function()
{
$('#search').keyup(function() {
searchTable($(this).val());
});
});
function searchTable(inputVal)
{
var table = $('.table');
table.find('tr').each(function(index, row)
{
var allCells = $(row).find('td');
if (allCells.length > 0) {
var found = false;
allCells.each(function(index, td)
{
var regExp = new RegExp(inputVal, 'i');
if (regExp.test($(td).text()))
{
found = true;
return false;
document.getElementById("i1").value = allCells.length;
}
});
if (found == true)
$(row).show();
else
$(row).hide();
}
});
}
$(function()
{
$('#table a').click(function(e)
{
e.preventDefault();
$('#result').val($(this).closest('tr').find('td:first').text());
});
});
</script>
I wanted to spit the dynamicelly sum of rows her in my table header.
<h3>Total: (<?php print_r($_GET["i1"])?>) </h3>
I hope you can help me.
You probably have never learned the difference between javascript and php
Javascript is clientsided, which means everything is processed by your local system. PHP is server sided which means everything is processed by the server and parsed into html.
You can't send a value from javascript into plain php like you did.
You can however send a post or get to the same script and let that reload a part of your script
http://api.jquery.com/jQuery.get/
http://api.jquery.com/jQuery.post/
You're not the first to want this, and not the first to be told it is impossible the way you imagine. When you browse to a PHP page things go basically like this:
Browser sends HTTP request to server
Server determines what page to send to the browser
Server discovers you want a PHP page
Server executes PHP
Server sends what is returned by PHP to the browser
Browser doesn't know about the PHP and displays HTML
Browser executes Javascript.
Now the important part is that the browser doesn't know what PHP is, but can execute JavaScript, while the server doesn't know what JavaScript is (for simplicity's sake) but can execute PHP. Bottomline: it is hard to communicate between the two because they are executed in different places. You'll most probably want to use AJAX, so here is a supersimple sample:
The PHP page we're going to fetch:
<?
// We're on the server
// We're going to output something:
echo "Yay! You can see me!"; // So the browser sees only "Yay! You can see me!" (without quotes).
?>
JavaScript (with jQuery) to fetch the PHP page:
$("#anElementID").load("thePHPPageWeWantToFetch.php"); // It's that simple! The element with the ID #anElementID now contains "Yay! You can see me!" (without quotes).
I suggest too, use AJAX or something to pass your javascript values to PHP.
You can create a AJAX call, add the data from your javascript, and catch the data in your PHP file.
var value = "Jan";
$.ajax({
url: "/form.php",
type: "post",
data: "name=" + value
});
in your PHP file you can do:
<?php
$catchedName = $_POST["name"];
?>
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.
I'm doing a online exam tool. I want to minimize the number of database requests. So I am requesting all the questions in the test at one go. After this I have to remember all the questions user has attempted and their answers. My plan is to save the answers in a php session variable like this
$('input[type=radio]').click(function()
{
var id = ($(this).parent().attr('id'));
id = id.slice(4);
$('#nav'+id).css('color','red');
<?php $_SESSION['ques['id']']= ?> $(this).val() <?php ;?>
});
In the above code the following lines are to change the color of attempted questions.
var id = ($(this).parent().attr('id'));
id = id.slice(4);
$('#nav'+id).css('color','red');
Here id is the id of the question. Problem is I'm getting the following error
Parse error: syntax error, unexpected ';' in /var/www/sites/onlinetest/test.php on line #x
Also I'm pretty sure the following is wrong
$_SESSION['ques['id']']
since id is the javascript variable here. Please help me. Also I appreciate if any other better solution than 'storing in the session variables' is posted
1) Your problem lies in the last line of click block. I'm not entirely sure what you're trying to do, but you have <?php ; ?> and the semicolon is causing your script to fail to parse. The first part
<?php $_SESSION['ques['id']']= ?>
doesn't do anything either. It looks like you're trying to assign a Javascript value $(this).val() to the PHP SESSION global, which you can't do. You'll need to make an AJAX call back to your server to update your session var.
2) Use double quotes when nesting arrays like so:
$_SESSION["$ques[id]"]
Hope this helps.
Just store the answers in JS, and send them to the server when last question is answered.
Here's a really basic example of storing to an array:
var answers=[];
$('input[type=radio]').click(function()
{
var id = ($(this).parent().attr('id'));
id = id.slice(4);
$('#nav'+id).css('color','red');
answers.push($(this).val());
});
Sending it serverside:
$.ajax({
type: 'POST',
data: {answers : answers},
url: '/path/myfile.php',
success: function(data) {},
error: function() {}
});
Catching it in PHP:
if (isset($_POST['answers'])) {
$answers = $_POST['answers'];
}else{
die('error');
}
This is the way I would do it, just show/hide the questions with javascript.
If you are refreshing the page for every question you could just store the answers in PHP on every new page load, should be pretty straight forward as long as you're not trying to use PHP code inside your JS file.
I think we never get any client side script variable to server side script language
Solution store in some hidden form variable then at the form submit time you can get in GET or POST variable
Thanks
The code seems will not work as you expected even though you clear the errors.So use the ajax in jquery
The problem with PHP is that it gets executed before the javascript so you can't just add php and try to assign a javascript variable into php varivable.
You will have to use ajax to solve your problem.
Do a ajax request and send all values trough GET. After this you can use all variables in your php file where you did the ajax request.
Iterate trough all variables and insert them into the Session
i am new to php and mysql.
How can i extract a VALUE from a JAVASCRIPT VARIABLE(i set) then send it to a PHP page that can read it and process it , the PHP will then insert the value into a table in MySQL database.
var A = "somevalue"
I have been researching but none of it give me a simple and direct answer . I saw some people uses JSON(which i am unfamiliar with) to do this.
Hopes someone can give me an example of the javascript/jquery , php code to this. Thanks!
You've asked for... a lot. But, this tutorial looks like it could help you.
(FYI -- I swapped out the original tutorial for one on ibm.com. It's better but far more wordy. The original tutorial can be found here)
I'm not pretty sure if it works but just try this. Your jQuery script shoul be like this:
$(function(){
var hello = "HELLO";
$.post(
"posthere.php",
{varhello: hello},
function(response){ alert(response); }
)
});
and "posthere.php" is like this:
$varhello = $_POST['varhello'];
echo $varhello . ' is posted!';
you should then get an alert box saying "HELLO is posted!"
What you need is Ajax. This is an example jQuery to use:
function sendData(data) {
$.ajax({
type: 'POST',
data: data,
url: "/some/url/which/gets/posts",
success: function(data) {
}
});
}
This will send post data to that url, in which you can use PHP to handle post data. Just like in forms.
If you have a form:
<form id="theformid">
<input type="text">
</form>
Then you can use jQuery to send the form submit data to that sendData function which then forwards it to the other page to handle. The return false stops the real form from submitting:
$("#theformid").submit(function(){
sendData($(this).serializeArray());
return false;
});
If you though want to send just a variable, you need to do it like this:
function sendData(data) {
$.ajax({
type: 'POST',
data: {somekey: data},
url: "/some/url/which/gets/posts",
success: function(data) {
}
});
}
Then when you are reading $_POST variable in PHP, you can read that data from $_POST['somekey'].
Inside the success callback function you can do something with the data that the page returns. The whole data that the page returns is in the data variable for you to use. You can use this for example to check whether the ajax call was valid or not or if you need to something specific with that return data then you can do that aswell.
i make a Jquery function that (for the moment) call a function dinamically and print it with an alert. with firefox, chrome : it works! when i try on IE7 (the first time), it fails. If i reload the page (F5) and retry , it works! o_O
I FINALLY understand why that's happen. In my old website i used the jquery-1.3.2.min.js library. On this i use the jquery-1.4.2.js and in fact it doesnt work. So what's up? A bug in this new version?
cheers
EDIT
actual functions (with Bryan Waters suggestions):
// html page
prova
// javascript page
function pmNew(mexid) {
var time = new Date;
$.ajax({
type: 'POST',
cache: false,
url: './asynch/asynchf.php' + '?dummy=' + time.getTime(),
data: 'mexid='+escape(mexid)+'&id=pmnew',
success: function(msg) {
alert(msg);
}
});
return false;
}
// ajax.php
if($_POST['id']=="pmnew") {
echo "please, i will just print this";
}
Fiddler result : if i use http://localhost/website fiddler doesnt capture the stream. if i use http://ipv4.fiddler/website it capture the stream, but at the ajax request doesnt appair. if i refresh the page, yes it works. mah...i really don't know how resolve this problem...
Best way to debug is to download Fiddler and see what the HTML traffic is going on and if the browser is even making the ajax request and what the result is 200 or 404 or whatever.
I've had problems with IE cacheing even on posts. And not even sending out the requests. I usually create a date object in javascript and add a dummy timestamp just to make the url unique so it won't be cached.
ok, I'm not exactly sure what the issue is here but I think you could probably fix this by simply letting jquery handle the click instead of the inline attribute on the tag.
first change your link like this to get rid of the inline event
<a class="lblueb" href="./asynch/asynchf.php?mexid=<?$value?>"><?=value?></a>
then in your javascript in the head of your page add a document.ready event function like this if you don't already have one:
$(function(){
});
then bind a click event to your link inside the ready function using the class and have it pull the mexid from the href attribute, then call your pmNew function like so:
$(".lblueb").click(function(e){
e.preventDefault();
//your query string will be in parts[1];
parts = $(this).attr("href").split("?");
//your mexid will be in mexid[1]
mexid = $parts[1].split("=");
//call your function with mexid[1] as the parameter
pmNew(mexid[1]);
});
Your final code should look like this:
<script type="text/javascript">
function pmNew(mexid) {
$.ajax({
type: "POST",
url: "./asynch/asynchf.php",
data: "mexid="+mexid+"&id=pmnew",
success: function(msg){
$("#pmuser").html('<a class="bmenu" href="./index.php?status=usermain">PANEL ('+msg+')</a>');
}
});
}
//document.ready function
$(function(){
$(".lblueb").click(function(e){
//prefent the default action from occuring
e.preventDefault();
//your query string will be in parts[1];
parts = $(this).attr("href").split("?");
//your mexid will be in mexid[1]
mexid = $parts[1].split("=");
//call your function with mexid[1] as the parameter
pmNew(mexid[1]);
});
});
</script>
I believe you have an error in your SQL code. Is userd supposed to be userid?
Gaby is absolutely right that your SQL code is wide open for injection. Please consider learning PDO, which will reduce the likelihood of SQL injection significantly, particularly when using placeholders. This way you will have query($sql) and execute($sql), rather than the code going directly into your DB.
As a matter of habit you should deal with your request variables early in your script, and sanitize them to death -- then assign the cleaned results to new variables and be strict in only using them throughout the rest of the script. As such you should have alarm bells ringing whenever you have a request variable in or near an sql query.
For example at the very least you should be stripping any html tags out of anything that will get printed back to the page.
That is in addition to escaping the quotes as part of the sql string when inserting into the database.
I'm all for coding things up quickly -- sure, neaten up your code later... but get security of request vars right before doing anything. You can't tack on security later.
Anyway sorry for harping on.... as for your actual problem, have you tried what Gaby suggested: change your html to:
<a class="lblueb" href="#" onclick="return pmNew('<?php echo $value; ?>')"><?php echo $value; ?></a>
And then update your JS function to:
function pmNew(mexid) {
$.ajax({
type: 'POST',
cache: false,
url: './asynch/asynchf.php',
data: 'mexid=' + escape(mexid) + '&id=pmnew',
success: function(msg) {
$('#pmuser').html('<a class="bmenu" href="./index.php?status=usermain">PANEL (' + msg + ')</a>');
}
});
return false;
}
Also, with IE -- check the obvious. Clear the browser cache/history
I didn't understood the "fail", but here's another example..
function pmNew(mexid) {
$.post("./asynch/asynchf.php", {mexid: mexid, id: "pmnew"},
function(msg) {
$("#pmuser").html('<a class="bmenu" href="./index.php?status=usermain">PANEL ('+msg+')</a>');
}
});
}
It appears that this issue is faced by several people.
One of them had luck with clean installation of browser:
http://www.geekstogo.com/forum/topic/22695-errorpermission-denied-code0/
Check to make sure the content returned to the DOM is valid for the DOCTYPE specified.
I've had a similiar problem with Chrome, FF and Safari all working just fine, but finding the ajax result broken in IE. Check to make sure you don't have any extra divs or spans in the ajax result breaking your markup.