views:

74

answers:

4

hi.i have two problems with jquery $.ajax. first problem is ihave a php file named action.php and here the code:

if($_GET['action']=='add'){
    //rest of the code here
}

And i use jquery $.Ajax function to call that when form fills:

$.ajax({type:"POST", url:"action.php?action=add", data:$("#form").serialize(), cache:false, timeout:10000});

this works but i wanted to know is there anyway to send the action=add code with data and not the url?

and the second problem that i have is that i have a link:

<a href="#" onclick="delete(4);">delete row from mysql where id is 4</a>

and a jquery function:

    function deleteUser(id){
    $.ajax({type:"POST", url:"action.php?action=delete", data:"id="+id, cache:false, timeout:10000});}

and of course the action.php code:

if($_GET['action']=='deletestudent'){
    mysql_query("DELETE FROM `students` WHERE `student_id` = {$_POST['id']}");
}

but it doesn't work.what should i do?

+1  A: 

You have a function deleteUser() and you are using delete() even you're sending post action is delete while you're php script is looking for deletestudent

make your onclick onclick="deleteUser(4);"

and change your action from

$.ajax({url:"action.php?action=delete&id="+id, cache:false, timeout:10000});}

to

$.ajax({url:"action.php?action=deletestudent&id="+id, cache:false, timeout:10000});}
x4tje
A: 

For the first problem:

You can add to your form a hidden input with the name/value you need. Example:

<input type="hidden" name="action" value="add" />

For the second problem:

According to your code, it seems that you are send "delete" but in the condition you are testing if equal to "deletestudent", maybe that's your problem.

Soufiane Hassou
A: 

chnage the type to GET o remove it, $.ajax default type is GET

$.ajax({url:"action.php?action=delete&id="+id, cache:false, timeout:10000});}

in php change your

....WHERE `student_id` = {$_GET['id']}");
Puaka
I'm sorry, I *had* to vote this down. GET requests should be idempotent, **period**. http://www.w3.org/2001/tag/doc/whenToUseGet.html
Peter Bailey
+3  A: 

First part: Yes

var postData = $("#form").serialize();
postData.action = 'add';
$.ajax({
    type:"POST"
  , url: "action.php"
  , data: postData
  , cache: false
  , timeout:10000
});

For the 2nd part: that isn't working because your "action" values are not congruent: delete vs deletestudent. Nor are your function names: delete() vs deleteUser()

Also, I'd recommend applying some SQL injection protection in that query as well.

Peter Bailey
ew. whats up with your commas? thats gross.
David Murdoch
Gross? I don't like postfixed separators. Seeing them at the start of the line makes it abundantly clear that I'm dealing with a new value/parameter/whatevever. Also makes editing easier.
Peter Bailey