简体   繁体   中英

jquery $.ajax to php problem

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?

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.

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});}

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.

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']}");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM