Send string to database with Ajax not working as intended - php

I'm trying to send a simple string to the database. In order to see if I'm half way there, I'm checking to see if $_POST has anything set -- but it doesn't.
Here is my simple form, on an index.php:
<form action="" method="POST">
<input type="text" name="add_item" id="add_item">
<input type="button" value="submit" id="button">
</form>
And here is the AJAX from that form, where the success is triggered:
var add_item;
$('#button').click(function(e){
e.preventDefault();
add_item = $('#add_item').val();
console.log(add_item);
$.ajax({
type: 'POST',
url: 'sendData.php',
data: 'send me!',
success: function(data){
alert('lol');
}
});
});
And on the sendData.php, but there is nothing in the $_POST global:
var_dump($_POST); // returns 0
if (isset($_POST['add_item'])):
$add_item = $_POST['add_item'];
$submit = new Connection();
$submit->connect_db();
$submit->add_to_DB($add_item);
endif;
As you can see, I'm trying to send it to the database; but before that I'm trying to see if anything is in the $_POST global -- but it returns 0.
Would anyone know why? I'm new to this and I can't find any concrete tutorials explaining simply.

Try setting data to something like "testvar=sendme" or simply use a PlainObject
PHP seems to be expecting key-value-pairs for $_POST to work.

Related

$_GET PHP form variable AJAX check 404 then submit form

I have a form on a page that accepts an 'ID', user inputs ID eg; 1026
The form submits to the same page ajax grabs the ID checks it against another site. I need to be able to let the form post if the response is NOT a 404 error and $_GET is true.
Heres what I have
<script>
$(document).ready(function(){
$('form#getid').submit(function(){
var theid = $('input#id').val();
var dataString = "id=" + theid;
$.ajax({
type: "POST",
data: dataString,
success: function(response, status, xhr){
if(status=="success") {
$("#err-404").html(response);
}
else { alert(status+ ' - '+ xhr.status); }
}
}
});
});
return false;
});
</script>
My form
<form id="getid" action="">
<input type="text" name="id" />
<input type="submit" class="button" value="Go">
<div class="error" id="err-404"></div>
I think im on the right track, just not sure how to put it all together.
Firstly, if you don't have to use a string for your data, don't. You can use an array like so:
$.ajax({
type: "POST",
data: {'id': theid },
Which is cleaner and more maintainable.
As for your question, your code is a little unclear, but what you probably should do is return false at the end of the submit() event to prevent the form from submitting, and then in the AJAX event, if it's cleared for submission, do a $('#getid').submit(). You may have to set some kind of flag (a hidden input or a data attribute) that you check on to avoid the AJAX-triggered submit from checking again, resulting in an infinite loop.
A note here: 404s should cause the error() callback in the AJAX handler to fire, so a 404 won't trigger the success callback you have set up.

PHP + AJAX - Pass Current $_GET Variables So Far

I have a page where users fill out $_GET data for some options. I'd like to pass these $_GET variables using AJAX to a .php script. But my issue is how do I pass those $_GET variables they filled out so far, without refreshing the page?
Here is my code so far.
$.ajax({
type: "GET",
url: "serverside script to process on data",
data:{name:youwant}, // Here is where I want to take what the user has filled out so
// far, and place it here all without refreshing the page
success: function(data){
alert("return here if success")
}
})
First of all, drop this task into small ones:
1) Get/process variables in JavaScript
2) Send them to PHP
3) Parse/handle the ones
4) Depending on result send respond back to JavaScript
5) Handle that respond and display a message to user
Take a look at this example,
Let's assume that jquery.js is loaded.
Assume that we want to send the values of the inputs we have - email and password.
<script type="text/javascript">
$("#Send").click(function(){
$.ajax({
type : "GET",
//Look carefully:
data : {
// it'll be PHP vars // This is JS vars
email : $("#email").val(),
password : $("#password").val()
},
success : function(respondFromPHP){
alert(respondFromPHP);
}
});
});
</script>
<input type="text" id="email" />
<input type="password" id="password" />
<br />
<button id="Send">Send to php</button>
In your php script, just handle vars you get, like this:
<?php
print_r($_GET); // will print smth like Array("email" => "foo", "password" => "bar")
// Then create function so that you can simplify handling of the vars.
// Like this:
function validate_password($password){}
function validate_email($email){}
I don't know your code, but you can have a form, but instead of submit it, you put a onsubmit method to a javascript function. In that function you gather all variables and pass it through ajax.
Example: <form name="form1" method="get" onSubmit="return send()">
<script>
function send() {
$.ajax(...);
return false;
}
</script>
You can use seralize function to send in $.ajax data field

php parsing jQuery form serialize wrong way

I have one problem...
These are names of some my html form elements:
name="password"
name="meta[naziv_firme]"
This is my jQuery
var data = {action: 'edit', form: $('input', 'form#edit-klijent-form').serialize()}
console.log(data);
$.get('/index.php/admin-ajax', data,
function(response){
// Success
$('div#edit-klijent-div,.tipsy').hide();
$('div#klijent-edit-success').show();
});
Console.log gives me result:
action edit
form userID=12&password=&password-match=&email=test15%5Bmeta%5Bnaziv_firme%5D=test15&meta%5Bkontakt_osoba%5D=test156&meta%5Bkontakt_telefon%5D=test157&meta%5Bkontakt_email%5D=test158
So everything look OK!
Now in PHP I have var_dump($_GET); and the result is:
string(165) "userID=12&password;=&password;-match=&email=test15&meta;[naziv_firme]=test15&meta;[kontakt_osoba]=test156&meta;[kontakt_telefon]=test157&meta;[kontakt_email]=test158"
Why does PHP put ; after password, in &meta;[... ??
And ideas? What am I doing wrong?
Thank you!
In your HTML form element, add:
<input type="hidden" name="action" value="edit">
And change this line:
var data = {action: 'edit', form: $('input', 'form#edit-klijent-form').serialize()}
Into this:
var data = $('input', 'form#edit-klijent-form').serialize();
Can't really test it since I don't have your HTML or server configuration, but I think it should work.
Update:
To clarify #AnthonyGrist's comment above, let's observe what serialize does:
<form>
<input type="text" name="input1" value="foo">
<input type="text" name="input2" value="bar">
</form>
<script>
var data = $('form input').serialize();
// data is now: 'input1=foo&input2=bar'
</script>
If you assign the value returned above to a query parameter (which PHP accesses using $_GET), you're basically telling PHP that $_GET['form'] equals the string above, which is not what you intended. PHP would not parse the contents of $_GET['form'] to give you $_GET['input1']... The value returned by serialize() should be used as the 2nd argument to $.get() directly.
Change your code from:
var data = {action: 'edit', form: $('input', 'form#edit-klijent-form').serialize()}
To:
var data = "action=edit&" + $('input', 'form#edit-klijent-form').serialize();
I think it is what you're trying to achieve.

Fetch input value from certain class and send with jquery

<input id="u1" class="username">
<input id="u2" class="username">
<input id="u3" class="username">
...
How to fetch input value with "username" class and send with ajax jquery to php page.
i want to recive data like simple array or simple json. (i need INPUT values and not ids)
var inputValues = [];
$('input.username').each(function() { inputValues.push($(this).val()); });
// Do whatever you want with the inputValues array
I find it best to use jQuery's built in serialize method. It sends the form data just like a normal for submit would. You simply give jQuery the id of your form and it takes care of the rest. You can even grab the forms action if you would like.
$.ajax({
url: "test.php",
type: "POST",
data: $("#your-form").serialize(),
success: function(data){
//alert response from server
alert(data);
}
});
var values = new Array();
$('.username').each(function(){
values.push( $(this).val());
});

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:
delete row from mysql where id is 4
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']}");

Categories