AJAX + PHP Form not passing variables? - javascript

So normally I can get my ajax to work without any issues however for some reason my script isnt passing variables through to my PHP form. Ive been trying to debug for a while and am hoping a fresh set of eyes can point out whatever dumb error I got going on (i stripped it to bare bones for simplicity, this wont pass variable).
AJAX + FORM
$('#formid').on('submit', function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: 'page.php',
data: $(this).serialize(),
success: function(data) {
alert(data);
}
});
});
<form id="formid" method="post">
<input type="text" name="name">
<input type="submit" value="Add">
</form>
PAGE.php
//Get Variables
$name = $_POST['name'];
echo 'Name is: '.$name;
This should display an alert that says 'Name is (whatever the user puts in the form)' However it does not echo back what the user submits in the form. Can anyone see something wrong with this script?
Something is wrong with posting the data back to the php page data: $(this).serialize()

The code looks clean, however there may be an issue with context when doing $(this).serialize() inside the ajax function. It may be better to save your data to a variable first. The result would look something like this:
$('#formid').on('submit', function(e){
e.preventDefault();
var my_data = $(this).serialize();
$.ajax({
type: "POST",
url: 'page.php',
data: my_data,
success: function(data) {
alert(data);
}
});
});
If this doesn't work then it may actually be an issue with the PHP side.
EDIT: Added rest of JS to be more concise and clear.

You should set form method as POST:
<form id="formid" method="post">

Your code seems to be ok. $(this).serialize() should not be the problem, but if you think so, you can give an id to the text input and try data: {name: $('#your-input-id-here').val()}.
An other thing could be that e.preventDefault(); may not be working properly. Try to place it after the ajax call or replace it by return false; after the ajax call.

Thank you for all the responses, I have no idea why but adding the form in front of the id made it work. $('form#formid') I must have duplicate IDs on my page without realizing

Related

AJAX post variable to PHP not working

I am trying to get a jQuery variable to a PHP variable. I have looked it up but can't find a solution. I have the following jQuery:
$('.eventRow').click(function(){
var eventID = $(this).attr('id');
$.ajax(
{
url: "index.php",
type: "POST",
data: {'phpEventId': eventID },
success: function (result) {
console.log('success');
}
});
When I console.log te "eventID" it correctly displays the number.
My PHP code is in the index.php. This is also where the .eventRow class is.
<?php
$phpEventId = $_POST['phpEventId'];
echo "<script>console.log('Nummer: ".$phpEventId."')</script>";
print $phpEventId;
?>
However nothing happens. The console.log just displays: "Number: " Is there something wrong with the code? Thanks for your help!
EDIT: Could it be the problem that the index.php is already loaded before I click on the button? Because this php code is in the index.php and thus the $phpEventId is not yet set.
In your Ajax, the type: "POST" is for jQuery prior to 1.9.0. If you're using the latest jQuery, then use method: "POST".
If you're using the latest jQuery and you don't specify method: "POST", then it defaults to method: "GET" and your PHP needs to capture it with $_GET['phpEventId'];.
After reading your update, let's try one thing. Change your PHP to return something meaningful to Ajax:
<?php
$phpEventId = $_POST['phpEventId'];
echo $phpEventId;
?>
Then try to capture the PHP response in your Ajax:
$.ajax({
url: "index.php",
method: "POST",
data: {'phpEventId': eventID },
success: function (result) {
alert("result: " + result);
}
});
This is just a part of your code, and the problem is somewhere else. In this context your code works just fine:
<div class="eventrow" id="1">This</div>
<div class="eventrow" id="2">That</div>
<script>
$('.eventRow').click(function(){
var eventID = $(this).attr('id');
$.ajax(
{
url: "index-1.php",
type: "POST",
data: {'phpEventId': eventID },
success: function (result) {
console.log('success: '+eventID);
}
});
});
</script>
With the matching index-1.php:
<?php
$phpEventId = $_POST['phpEventId'];
echo "<script>console.log('Nummer: ".$phpEventId."')</script>";
print $phpEventId;
?>
Not sure though why do you print javascript code (console.log) into an ajax response here...
Error Is Visible Even Here
According to WebZed round statistic report, this error was visible over 84% of web-developers.
Failed to post data to PHP via JQuery while both frameworks and codes were updated.
Possible Solutions Available Today
Try using other methods for posting because JQUERY and AJAX libraries are not as efficient as shown in the surveys.
New frameworks are available which can do better with PHP.
Alternative method is to create a post request via $_GET method.
Regular HTML5 supports <form></form> try method="post". For security reasons try using enctype="" command.
Try using React Native https://nativebase.io/

AJAX call returns results, but in a blank page

There are a couple of questions that are somewhat similar to this, but I haven't been able to get their solutions to work for me.
Basically, I am making an AJAX call that is working properly--the result is coming back through. The issue is that instead of processing the result, the result-array is printed back to the screen (and deletes everything else). Clearly, it is not handling the incoming result properly, but I'm not sure why.
This is the form being sent:
<form class="removeAndApply" method="post" action="">
…hidden inputs...
<button type="submit">Use</button>
</form>
The PHP that is processing the AJAX:
case "removeAndApply_PromoCode":
…Get data from $_POST….
…process stuff...
$response = …..;
$finalPrice = ….;
$dataArray = array('response'=>$response, 'finalPrice'=>$finalPrice);
header('Content-type: application/json');
echo json_encode( $dataArray );
exit();
break;
Here is a sample result text, as printed on my screen during failure:
{"response":{"Col1":"13","0":"13","Col2":"PC2","1":"PC2","Col3":"1","2":"1","Col4":"45.89","3":"45.89","col5":null,"4":null,"Col6":"1","5":"1"},"finalPrice":0}
And this is the javascript function that is supposed to handle it:
$('.removeAndApply').ajaxForm({url: this.href, type:'post',
data: this.serialize,
dataType: 'json',
success: function(response){
alert("asdf");
}
});
Thanks.
The problem seems to be in HTML button type attribute. When you have a <button type="submit"> in <form> and you clicked it. The form submits, request is sent to the server, browser opening the new response in new document.
If you make some changes:
HTML:
<form class="removeAndApply" method="post" action="">
…hidden inputs...
<button type="button" id="submit-form">Use</button>
</form>
JS:
$('#submit-form').on('click', function() {
$.ajax({
type: 'post',
url: window.location.href,
data: $('.removeAndApply').serialize(),
dataType: 'json',
success: function(res) {...},
error: function(err) {...}
});
});
Everything should be fine.
This is probably better suited for a comment, but I don't have enough rep for that, so:
This is the type of behavior you'd see if you don't bind the ajax form functionality to that form... the button submits the form as normal and you just see plain json coming from the server as a response to the (non-ajax) post. Are you sure that ajaxForm() statement is being executed?

JQuery Form No reload : how to pass the $_POST info after success?

First the code below works, but truth be told i don't know why :) it just worked after many trial and errors
I need the $_POST data submitted through the #filter-form, for loading the page as action1 function will require $_POST data.
If i remove +data or .html(data) it doesn't work anymore.
Also if i change url:"..." it does not work anymore either and i don't understand why as i don't need to to anything here, all i need is to load this page.php page and pass the $_POST so that it can output properly.
My QUESTION is, WHY does it work ? (i want to understand why putting +data or html(data) is so important to make sure $_POST is passed) and how can i make it more proper ?
Thanks for your help
<script type="text/javascript">
$("#filter-form").submit(function(event) {
$.ajax({
type: "POST",
url: "includes/page.php?action=action1",
//Specify the datatype of response if necessary
data: $("#filter-form").serialize(),
success: function(data){
alert("succeess");
$("#tableresult").load("includes/page.php?action=action1"+data).html(data);
}
});
event.preventDefault();
return false;
});
</script>';
You don't need to use .load() at all. It should be:
success: function(data) {
alert("success");
$("#tableresult").html(data);
}
This takes the response that the AJAX server returned, which should be HTML code, and puts it into the tableresult element.
The way you had it written, you're calling the server twice, which doesn't seem right.

How to pass form data to PHP via AJAX call (CodeIgniter Framework)

I have the following HTML structure:
<form method="POST">
Name : <input id="asgname" type="text"> <br>
Description : <input id="asgdescription" type="text"> <br>
Save
</form>
I want that on clicking the save button, the form values are sent to the server via AJAX call.
For that, I've attached the click event via following command
$("#asgsave").click(save_assignment);
save_assignment is also a javascript function defined as follow:
function save_assignment() {
return $.ajax({
type: "POST",
url: "<?php echo base_url();?>index.php/user/save_assignment",
data: $('form').serialize(),
success: function(response) {
alert('Form was submitted');
},
error: function(error) {
alert("Error");
}
});
}
The above is not working. So I tried the following approach as well:
function save_assignment() {
var formvalues = {
name : $('#asgname').text(),
descripion : $('#asgdescription').text(),
};
return $.ajax({
type: "POST",
url: "<?php echo base_url();?>index.php/user/save_assignment",
data: {values : formvalues},
success: function(response) {
alert('Form was submitted');
},
error: function(error) {
alert("Error");
}
});
}
But this is also not working.
Can anyone please guide me as to why are the above methods not working and what is the correct way to do so ?
EDIT-1 :
By not working, I mean: in the first case ($('form').serialize() approach) the data is not being sent to the server. I checked it via chrome and firefox debugger that there was no post data sent corresponding to the form.
And in the second case, empty values are being sent. i.e. the post data sent to server is like following:
values[name]
values[description]
i.e. the above values are empty.
EDIT-2:
By logging on firephp, I have confirmed that the save_assignment PHP script is BEING EXECUTED. Thus ajax call is working fine but it is NOT passing the data correctly.
Try to use event.preventDefault() like,
$("#asgsave").on('click',function(e){
e.preventDefault();
save_assignment();
});
or use return false after ajax call like,
function save_assignment() {
//ajax code
return false;
}
you have to use callbacks in the success function, cause ajax is asynchronously
edit
have you already tried console.log('foo'); in your function? so you are able to test if the function is called ;)
edit 2
add the following line to your ajax options
dataType: "json"
You could just serialize your form values:
http://api.jquery.com/serialize/
However, looking over your code, I'll take a stab and guess that you are not getting and sending your values properly. Using jQuery, you grab a value from input like so:
$('#idofInput').val();
http://api.jquery.com/val/
You are doing: $('#asgname').text()
Format your data properly: data : { foo : 'bar', bar : 'foo' }
One last guess, make sure your CodeIgniter config has CSRF protection disabled, otherwise you would need to pass: $this->security->get_csrf_token_name() & $this->security->get_csrf_hash();

Posting with ajax not working

So i have a form like so:
<form>
<input type="submit" value="X" id="deleteButton" onclick="ConfirmChoice(<?php echo $id; ?>)" />
</form>
and a function like this:
<script type='text/javascript'>
function ConfirmChoice(theid)
{
var dataString = 'id=' + theid;
answer = confirm("Are you sure you want to delete this song?");
if (answer !=0) {
$.ajax
({
type: "POST",
url: "deleteSong.php",
data: dataString,
});
}
}
</script>
So basically I want it to delete whatever they click on from my database which deleteSong will take care of.
It gives the id of the song and as far as I know should confirm deletion then delete it right?
Any help would be appreciated.
Thanks
change it from
input type="submit" to
input type="button"
Also because your are not setting it, the request to the server is in json which in your case is badly formed.
Try something like this:
var dataString = "{'id'= '"+ theid + "'}";
this should make it work :)
It's hard to answer this without knowing where exactly the problem is. Is deleteSong.php working correctly?
Like others have said you should change the input type to button or return false from your function, otherwise the browser will try and submit the form in the normal manner but as you haven't specified an action within the <form> tag it won't work properly.
Personally, I would do things quite differently:
HTML:
<input type="button" value="<?php echo $id ?>" id="deleteButton">
Javascript:
$(document).ready(function () {
$('#deleteButton').click(function () {
var answer = confirm("Are you sure you want to delete this song?");
if (!answer) {
return false;
}
var data = 'id=' + $(this).val();
$.ajax({
type: 'POST',
url: 'deleteSong.php',
data: dataString,
success: function (response) {
// response will contain the output from your php script.
// Do something with it here. If you just want to see what it
// says, do something like:
console.log(response);
// then look in the console (view > javascript console in chrome)
}
});
});
});
Just to explain what I'm doing here (sorry if I'm telling you things you already know, I want to be as explicit as possible for anyone who might be reading this in the future:)
I enclose the whole thing in $(document).ready(function() { ... } ); so it only gets run when the page is finished loading, other wise you might end up trying to bind functions to the click action on a button that doesn't exist yet.
if (answer !=0) is redundant, you can just write if (!answer) as any positive integer will evaluate to true
I included a success callback above which might help you in debugging.
Is there only going to be one 'delete' button on the entire page? Or is there going to be a delete button next to every song? If it's the latter, you'll have to give each button a different ID, not just deleteButton because all IDs must be unique.
If the above doesn't work, are you sure that jQuery has loaded correctly? To check, type jQuery in the console, if you don't get an error then you're fine. The other possibility is that something's wrong with your deleteSong.php script but I can't help you there without seeing it.

Categories

Resources