AJAX not sending user-input from a form to PHP script - php

I've been trying to learn basic AJAX and Javascript by following various tutorials and examples online, but I've hit a wall. I'm trying to write a simple script to take user-input from a form using AJAX and submit it to a PHP script, which then just echos the input.
All I can really tell is that whatever is being entered is not going through, but I'm not at the point yet where I can say why. I've tried with both POST and GET, and with various dataTypes, with the same result. I'm certain that I'm doing something wrong or misunderstanding something, but I'm not sure what.
HTML/ AJAX
<form id="my_form">
word <input type ="text" id="word1"/><br/>
<input type="submit">
</form>
<script>
$(document).ready(function(){
$("#my_form").on(function(e){
e.preventDefault();
var verb = $("word1").val();
$.ajax({
url: "testrun.php",
data: "verb",
type: "POST",
});
});
});
</script>
PHP
if (isset($_POST['verb'])){
$x= $_POST['verb'];
echo $x;
}else {
echo "not working";
}
EDIT: I've tried a few of the suggestions thus far, copying and pasting them directly, and none of them have actually done anything that I can see. I think I'm starting to understand a bit more about how AJAX should work, based on the responses, but it's still not reaching the PHP for some reason. I've tried both with the AJAX/HTML in a separate file that calls to the testrun.php script and with putting everything into the testrun.php file and basically having it call itself with the AJAX, but neither approach has achieved anything.
If the AJAX that I've gotten from the responses is fine, then am I misunderstanding something in how the PHP should be set up in order to actually receive the POST data? I'm still rather lost.

Three changes:-
1.var verb = $ ("word1").val(); need to be var verb = $ ("#word1").val();because its id (word1)
2.data: "verb", needs to be data: {"verb":verb},
3.form submission need to be correct so code given below (missing submit):-
Correct code:-
$(document).ready(function(){
$("#my_form").on('submit',function(e){ // check here you have one missing `submit`
e.preventDefault();
var verb = $("#word1").val(); // remove space between `$` and `(`
$.ajax({
url: "testrun.php",
data: {"verb":verb},
type: "POST",
});
});
});

You can not send data as data: "verb", in ajax. you need to send your data in params.
Second, you can not get the value of word1 input as $("word1").val(); you need to use # for get input by IDs.
Example:
$(document).ready(function(){
$( "#my_form" ).submit(function( e ) { //CHANGED using submit event.
e.preventDefault();
var verb = $("#word1").val(); //CHANGED
$.ajax({
url: "testrun.php",
data: "verb="+verb, //CHANGED
type: "POST",
});
});
});

You forgot # foe id selector of word1.
.on() needs event to bind to. In your case of form submit, it's submit
Data should be passed as object. In your case, you will be able to access it with $_POST['verb']
$(document).ready(function ()
{
$("#my_form").on('submit', function (e)
{
e.preventDefault();
var verb = $("#word1").val();
$.ajax({
url: "testrun.php",
data: {verb: verb},
type: "POST"
});
});
});

you miss to give the # sign in var verb = $("word1").val();
and use a variable just as a variable to the data like data: {"your_var_name" : verb}

Try this ...
$.ajax({
type: "POST",
url: "testrun.php",
data: "paramname=value", // access in php $_POST['paramname']
success: function(data){
// if page request is success
},
error: function(data){
// if page request failes
}
});

You have to do this:
var verb = $("#word1").val(); //Don't forget to add #
$.ajax({
url: "testrun.php",
data: {"verb":verb},
type: "POST",
});
verb is a variable, no need to put in between quotation!
The correct answer is
HERE by Anant

Related

AJAX - PHP how to return a variable to the original AJAX script and alter an input value

I am protecting my forms with a captcha code to prevent using bots submitting loads and loads of forms.
This form works with AJAX and won't refresh the page like it usually does.
I have everything set now and it is working. but..
So this is the form im talking about to help understand.
When you click on request a new password, i need the code to change on the input field.
I do change the code after requesting a password like this in newpass.php
$_SESSION['capcode3'] = $capcode3;
This is my javascript code:
<script>
$("#formoid").submit(function(event) {
event.preventDefault();
var form_data = $(this).serialize(); //Encode form elements for submission
$.ajax({
type: "POST",
url : "data/newpass.php/",
data : form_data
});
document.getElementById("captcha").value = "<?php echo $_SESSION['capcode3']; ?>";
});
</script>
So by using document.getElementById it would change the input value but, instead of setting the new value, it sets the old value.
So if the code is ABC123 and the new code is DEF456 it wont change to DEF456
Is there a better way to send the new code back to the input field?
Note: I have tested if $_SESSION['capcode3'] will change it's value with a positive result.
You did not specify a success handler in your ajax. Ajax is handled async, thus needs a callback to where the data will be passed when the request is succesfuly handled
$.ajax({
type: "POST",
url : "data/newpass.php/",
success: function(data) {
//change UI here
document.getElementById("captcha").value = data;
},
});
Please add code in success of ajax because may be session value will be changed on ajax success.
$.ajax({
type: "POST",
url : "data/newpass.php/",
data : form_data,
success :function(data){
document.getElementById("captcha").value = data;
}
});
Please try with this.

AJAX Form duplicate entries on submission

I've got a PHP form set up and it works fine on it's own but now that I've hooked it up with AJAX I'm getting duplicate submissions when someone submits the form so even though they've only submitted the form once it's added the details to the database multiple times.
From my testing it seems as though its sending the data twice but looking at the submissions from other people it's possible that it's doing it more than twice under certain circumstances but I haven't been able to replicate that.
Here is the code I was using initially:
$("#email-gather").submit(function(e) {
var url = "https://www.ruroc.com/emailgather.php";
$.ajax({
type: "POST",
url: url,
data: $("#email-gather").serialize(),
complete: function(data) {
$('.email-win input.button').val("submitted").attr('disabled', 'disabled').css({'background-color' : '#b34c4c','text-shadow' : 'none'});
}
});
e.preventDefault();
});
I have had a look around to find a solution and I saw a few people with similar issues saying that .live should be used instead of .submit so I amended my code this this:
$( "#email-gather" ).live( "submit", function() {
event.preventDefault();
var url = "https://www.ruroc.com/emailgather.php";
$.ajax({
type: "POST",
url: url,
data: $("#email-gather").serialize(),
complete: function(data) {
$('.email-win input.button').val("submitted").attr('disabled', 'disabled').css({'background-color' : '#b34c4c','text-shadow' : 'none'});
}
});
});
However this also resulted with the same issue so I'm hoping you might have a solution to this issue. I appreciate any help you can provide on the matter.
In the second part of code (that should work), you have event.preventDefault but event is not defined. try to add function(event) and it must work.
Else in the first one, you can put the prevent default before ajax call and take away the second submit. You need to add a return true in the ajax function to tell you script that the submit was successfull.

Send data with ajax but empty $_POST in php

I'm trying to save a data attribute of a div on click into a variable PHP. So I used $.ajax to send data with POST but it return an empty array.
However, the POST is visible in the console with good data.
AJAX
$('.get-thumbnail-id').click(function() {
var thumbnail_id = $(this).data('id');
$.ajax({
type: "POST",
url: "gallery.php/",
data: {thumbnail_id: thumbnail_id}
});
});
GALLERY.PHP
var_dump($_POST['thumbnail_id']);
I must have done something wrong but I really don't know what... any help is appreciated, thanks.
You should be doing
var_dump($_POST['thumbnail_id']);
Because the POST variable you are passing in the AJAX call has name thumbnail_id not just id
and check it with
$.ajax({
type: "POST",
url: "gallery.php/",
data: {thumbnail_id: thumbnail_id},
success : function(data){console.log(data);}
});
Check whether is prints anything in the console.

How to properly pass a jquery value to php using ajax?

I want to pass a value from my jquery code to a php variable after a user inputs through a textbox, but I don't receive any value at all in the PHP side through POST.I'm using .change and .post, does anyone here knows how to do it properly?
here's my code:
$(document).ready(function(){
$("#packagename").change(function(){
var packagename = $('#packagename').val();
var url = '{{url}}'; //localhost/test/test.php
$.ajax({
type: 'post',
url: url,
dataType:html,
data:{'val':packagename},
});
});
});
try it
$(document).ready(function(){
$("#packagename").change(function(){
var packagename = $('#packagename').val();
var url = '{{url}}'; //localhost/test/test.php
$.ajax({
type: 'post',
url: url,
dataType:text,
data:{'val':packagename},
success:function(result){
alert(result);
}
});
});
});
The only problem that I can see offhand is that the html in dataType:html, needs to have quotes around it like this: dataType: 'html',. Otherwise your code will look for the variable html, not find it, and throw an error.
http://api.jquery.com/jQuery.post/
dataType
Type: String
The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html).
change dataType: html, to dataType: 'html',
Have you tried just putting the url into the url field instead of whatever that object is you are trying to use?
I will assume you are not trying to ajax to the page you are currently on and expecting the php variable to display on the current page.

Ajax & Jquery form submission

I'm about to pull the hair out of my head with this one.
I'm sure the problem is simple, I'm new to Ajax with Jquery and I'm just overlooking something. But Man this is annoying. Every time the form is submitted, the page refreshes and .ajax throws error:. What could be causing this? I know I'm getting my form values to the Jquery for sure. And newcomment.php is working. I can post regular forms to it, but not with jquery.
function postPhotoComment() {
var comment = $("#comment").val();
var album = $("#album").val();
var photo = $("#photo").val();
var dataString = "comment="+comment+"&album="+album+"&photo="+photo;
$.ajax({
type: "POST",
url: "/includes/actions/photo-gallery/newcomment.php",
data: dataString,
success: function(res) {
alert("Posted!");
}
error: function(res) {
alert("Error!");
}
})
}
EDIT: Here's my html form:
<form>
<textarea id="comment" placeholder="Post Comment..."></textarea>
<input id="album" type="hidden" value="<?php echo "$a"?>"/>
<input id="photo" type="hidden" value="<?php echo "$p.$ext"?>"/><br/>
<button id="photo-comment-submit" onclick="postPhotoComment()">Post</button>
</form>
I also noticed that if I give the inputs names, Chrome puts them into the url bar like GET variables. And after every page refresh, it adds the ? at the end of the url. So, it seems like its trying to submit the form regularly.
Are you returning false to stop the browsers default action?
$('form').submit(function(){
var dataString = $(this).serialize(); // shortcut
$.ajax({
type: "POST",
url: "/includes/actions/photo-gallery/newcomment.php",
data: dataString,
success: function(res) {
alert("Posted!");
}
error: function(res) {
alert("Error!");
}
});
return false;// cancels the default action
});
If the function where you're calling the AJAX form submission code is the onSubmit method of the form, you'll need to stop the default action from happening -- that is, you want to stop normal submission.
To accomplish this, use the preventDefault method of the event object:
function postPhotoComment(evnt) {
evnt.preventDefault();
// existing code continues...
}
You may also return false from your event, but be aware that doing so has different effects in different browsers, and that it is not as explicit or reliable as calling preventDefault or stopPropagation directly.
Edit
Also, the error handler is probably getting called because your code initiates the XHR request, but when the browser starts the default action (submitting the form), it cancels any pending XHR requests. This is causing the error handler to be triggered.
Edit 2 I have created a jsFiddle with a working demonstration: http://jsfiddle.net/wXrAU/
Documentation
event.preventDefault method on MDN - https://developer.mozilla.org/en/DOM/event.preventDefault
Make sure that you return false; to the form when submitting, otherwise it will still submit as a "normal" form without using Ajax and reload the page.
EDIT: After reading the comments I think that this would be most appropriate for you:
<form action="url.php" onsubmit="return false;"></form>
jsFiddle with appropriate code: http://jsfiddle.net/SO_AMK/ZVgNv/
The PHP messes things up a little, but it works.
I actually fixed this by simply removing the <form> tags. I didn't need them anyways. But everything seems to work now.
Make sure you write a valid, HTTP-accessible url instead of just a path to a script, e.g.
function postPhotoComment() {
var comment = $("#comment").val();
var album = $("#album").val();
var photo = $("#photo").val();
var dataString = "comment="+comment+"&album="+album+"&photo="+photo;
$.ajax({
type: "POST",
url: "http://yoursite.com/whatever/newcomment.php", // here
data: dataString,
success: function(res) {
alert("Posted!");
}
error: function(res) {
alert("Error!");
}
})
}
Because JavaScript is a client-side language. It knows nothing about your filesystem structure or anything of that kind. And AJAX request is based on HTTP protocol.

Categories