Unable to fill input value with PHP variable - php

I have two files, landing.php and test.php. Landing.php has a form that is submitted via ajax using the post method to test.php. If the ajax call is successful, the browser loads test.php, at which point I am having an issue. I cannot figure out what I am doing wrong in my attempts to display the value of the post data that is sent to test.php.
The following is the ajax call from landing.php. I am reasonably sure that this is working correctly from having looked at the post data in Firebug.
$('#searchForm').submit(function(e) {
e.preventDefault();
var data1 = $('#checkBoxDiv input').serialize() + '&' + 'barcodeID=' + $('#barcodeID').val();
$.ajax({
url: 'test.php',
data: data1,
type: 'POST',
success: function() {
window.location.href = "test.php";
}
});
});
Here are the contents of test.php.
<?php
$bar = $_POST['barcodeID'];
echo "<html>";
echo "<body>";
echo "<p>*" . $bar . "*</p>";
echo "</body>";
echo "</html>";
?>
If I were to take the asteriks out of the line with the <p> from test.php, I would be presented with a completely blank screen when I arrived at test.php in my browser. With them there, however, I am presented with "**" on my screen. The most confusing part is, however, that if I include
echo $bar;
in test.php, I see the value of $bar (00-00102 - exactly as it should be) in Firebug's response tab on the post data viewer.
After some research, I read that post was the method of choice for when you do not want to display query strings in the URL bar, as well as the method to use when you have a large amount of data to send (which will be the case for me, it'll end up being around five to six hundred characters when all is said and done). I've looked at other stackoverflow posts and articles, attempted to replicate what was recommended, and still cannot get this right.
Am I doing something completely wrong or attempting to use these methods in a way in which they are not intended to be used?

Don't change the window location in the success of your ajax call. The call is posting the data to test.php and you are getting your response back there. Then you are redirecting to the page with a blank post which results in just the asterisks.
If you only want to display the results from test.php change your $.ajax call to the following:
$.ajax({
url: 'test.php',
data: data1,
type: 'POST',
success: function(response) {
$('html').replaceWith(response);
}
});
Or if you do want to change the page, forget about the ajax and just post the form to test.php

You are reloading the window after the AJAX succeeds, there is no POST information at that point.
You can do something like this though:
$('#searchForm').submit(function(e) {
e.preventDefault();
var data1 = $('#checkBoxDiv input').serialize() + '&' + 'barcodeID=' + $('#barcodeID').val();
$.ajax({
url: 'test.php', // <-- POST exists during this call
data: data1,
type: 'POST',
dataType: 'html',
success: function(data) {
$('html').replaceWith(data);
}
});
});

The AJAX POST will be finished in one turn. That means, the values you had posted to test.php
through ajax will be present only through that request. What you are doing is, you are redirecting to test.php upon receiving response from test.php. This is a fresh request, and it does not have any POST values. Hence, there is nothing in $_POST['barcodeID'];
Also, in your code, you are having $('#barcodeID').val() twice. Try removing the last one.:
var data1 = $('#checkBoxDiv input').serialize() + '&' + 'barcodeID=' +
$('#barcodeID').val();
$('#barcodeID').val();

If you are trying to use AJAX to replace the content of the page with the result of the form submission to test.php then you would need to change the AJAX call in landing.php to:
$.ajax({
url: 'test.php',
data: data1,
type: 'POST',
success: function(response) {
$('html').replaceWith(response);
}
});
Otherwise I would suggest not using AJAX and just do a regular form submission using HTML by setting the action attribute of your form as such:
<form method="post" action="test.php">

You are passing the variables to the test.php file as a POST request, which means that the test.php file will get that data and act on it. Then after that request is successfully completed you are redirecting to test.php without passing any variables.
If you really want to submit a form (with the redirect that comes with it), do that using html:
<form action="test.php" method="post">
<input type="text" name="barcodeID" />
</form>
If you don't need the redirect, do what others have suggested and show the output on the same page instead (someDiv is the html element where you would like to display the response from test.php):
$('#searchForm').submit(function(e) {
e.preventDefault();
var data = $('#checkBoxDiv input').serialize() + '&' + 'barcodeID=' + $('#barcodeID').val();
$.post('test.php', data, function(response) {
$('someDiv').html(response);
});
});
If you must do it using JavaScript and a redirect, append a hidden dummy form to the page and submit it:
$('<form action="test.php" method="post">' +
'<input type="hidden" name="barcodeID" value="123456789" />' +
'</form>')
.appendTo('body')
.submit();

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.

jQuery Ajax send to the same page

I want to figure out how jQuery Ajax work when I don't define url for it. So it should send the data to the same page where is the ajax also. How can I get for example the 'GET' data after the ajax has been completed?
<script type="text/javascript">
$(document).ready(function() {
$(".idoszak").change(function() {
var idoszak=$(this).val();
var dataString = 'idoszak='+ idoszak;
$.ajax({
type: "GET", // or POST
url: "statisztika.php", //The page where is also this script
data: dataString,
cache: false,
success: function(html) {
???
}
});
});
});
Now the php:
<select name="idoszak" class="idoszak">
<option value="felev">Félév</option>
<option value="evvege">Évvége</option>
</select>
<div id="statisztika">
.
.
.
<?
$katlag = mysqli_query ($link, "SELECT jegy FROM jegyek WHERE `jegyek`.`osztaly` = '$osztaly' AND `jegyek`.`piros` = '0' AND datum = '$idoszak'");
$katlagok = mysqli_num_rows($katlag);
?>
.
.
.
</div>
This is what is happening:
You type a URL into the address bar (or follow a link or something like that)
Your browser makes a request to that URL
The server sends a response back to the browser
The browser renders the page
You trigger some JavaScript
The JavaScript gets the browser to make an Ajax request to the same URL (well, almost the same URL: you've changed the query string)
The server sends a response back to the browser
The browser makes the response available to JavaScript
You appear to be expecting step 8 to be the browser replaces the page rendered at step 4 with one based on the data from step 7. That doesn't happen.
All that happens is that the response is made available to JavaScript.
The body of that response will be in the html variable of the success function.
If you want to change what the user is seeing in the page, then you will have to write JavaScript to manipulate the DOM of the page (which can use the data from the html variable).

How can I use a jQuery var in some php code?

I know there are a few topics on this subject, but after I spent 2 or 3 hours trying to get something good out of them, I just decided to ask this question on a specific point.
So here is my problem : I have got a table and I am using a jQuery function to select a row of this table. Now what i actually want to do is getting the text content of the div contained in the first td of the row.
I already used a getter on it and I am checking the getted value with an alert as you can see in th following code :
$("#myRow").click(function() {
$(".selectedRow").removeClass("selectedRow").addClass("unselected");
$(this).addClass("selectedRow").removeClass("unselected");
var myValue = $(".selectedRow .firstTd div").text();
alert('myValue');
});
So now, what I am trying to do is to send the myValue variable through an ajax request by replacing my alert by this piece of code :
$.ajax({
type: 'get',
url: 'index.php',
data: {"myValue" : myValue},
success: function(rs)
{
alert(myValue);
}
});
Then, back to my php code, I am tring to observe the obtained variable by using an echo, just like this :
<?php echo $_GET['myValue']; ?>
But there is just no way for me to know if my page got it beacause the echo just prints nothing... So i was wondering if someone could do something for me. Thanks.
PS : Oh, by the way ; I don't really know if this can matter, but my page index.php already receives data by a post.
You can't, but read this, php is on the server, while js usually runs on the client, but your ajax trick can work. Just do some processing in the recieving php.
I usually put my ajax recieving end in a different file, and process the rest by the variables posted.
Just try to put the $_GET['myValue']; into an if, or a switch.
Do a var dump of the request var to see if anything is coming through:
<?php
var_dump($_REQUEST);
If not, do a console.log() on 'myValue' to make sure it exists before sending the ajax request - the issue may lie in your js rather than you php.
If you are POSTing data then adjust accordingly - e.g.
$.ajax({
type: 'post',
url: 'index.php',
data: {"myValue" : myValue},
success: function(data)
{
console.log('successfuly posted:');
console.log(data);
}
});
then:
<?php echo $_POST['myValue']; ?>
If you were using GET your data would be in the url, e.g:
index.php?myValue=something
I'm not sure if you are aware of that, but you should wrap you function in document ready statement as below.
Next, call the AJAX request on some action, in this case we can use a click on the row in table.
$(document).ready(function () {
$("#myRow").click(function() {
$(".selectedRow").removeClass("selectedRow").addClass("unselected");
$(this).addClass("selectedRow").removeClass("unselected");
var myValue = $(".selectedRow .firstTd div").text();
alert('myValue');
$.ajax({
type: 'get',
url: 'index.php',
data: {"myValue" : myValue},
success: function(data)
{
console.log('you have posted:' + data.myValue);
}
});
});
});
Okay so it seems that i totally misunderstanded on the way that the $.ajax function works.
I now do use the $.post function (which is actually the same), this way :
$.post('pageElement.php', { myValue : $(".selectedRow .firstTd div").text() },
function(data) { $("#test").html(data); }
);
The url "pageElement.php" refers to a page containing this code :
<div><?php echo $_POST['myValue']; ?></div>
The function called at the end of the process just puts this code into a div of my original page, so i can use it as a php variable now and then send it to another page through a form.

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.

Using ajax for form submission with multiple forms generated by php on page

I have a page with multiple forms that do the same thing, acting as a like button for each post in the page, and right next to it the number of likes inside a div named "likes".$id, so I can identify where to write the likes count after the ajax call. I was trying to use jQuery ajax function, but I couldn't set what div to write the results of the function.
$.ajax({
type:'POST',
url: 'likepost.php',
data:$('#like').serialize(),
success: function(response) {
$('#like').find('#likediv').html(response);
}
});
And how would I access the data on likepost.php? I am terrible with javascript, so I hope someone could help me and explain how the jQuery function really works, because I've been copying and pasting it without really knowing what I was doing.
Would this work?
$(function () {
$("#likebutton").click(function () {
var id = $('input[name=id]'); // this is me trying to get a form value
$.ajax({
type: "POST",
url: "likepost.php",
data: $("#like"+id).serialize(), // the form is called like+id e.g. like12
success: function(data){
$("#likes"+id).html(data); // write results to e.g. <div id='likes12'>
}
});
});
});
I put this in the code but when the button is clicked, the usual post refreshing page is done. Why is that?
Making a mini-form, serializing it, and POSTing it seems like a lot of heavy lifting when all you really want to do is send the ID to the likepost.php script.
Why not just retrieve the ID and post it to the script?
First let's break down your function:Type is the type of the request we're making, you specified POST here. This means in your PHP file you'll access the data we're sending using $_POST. Next up is URL which is just the url of where you're sending the data, your php file in this case.
After that is data, that is the data we're sending to the url (likepost.php). You're serializing whatever has a ID of "like" and sending it to the php file. Finally success is a function to run once the request is successful, we get a response back from the PHP and use it in the function to output the response.
As for the multiple forms I'd recommend doing something like:
http://www.kavoir.com/2009/01/php-checkbox-array-in-form-handling-multiple-checkbox-values-in-an-array.html
Here's documentation on the stuff we talked about, if you're every confused about jquery just break it down and search each part.
http://api.jquery.com/serialize/
http://api.jquery.com/jQuery.ajax/
you can try :
function submitform(id) {
var jqxhr = $.post('./likepost.php',$("#"+id).serialize(), function(data) {
$("#"+id).find('#likediv').html(data);
}, "json")
return false;
}
in form:
<form method="post" id="likeForm" onsubmit="return submitform(this.id);">
<input..... />
<input type="submit" value="Submit" />
</form>
in likepost.php add first line:
if ($_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest") {
header("location: " . $_SERVER['HTTP_REFERER']);
exit();
}
you can see more : http://api.jquery.com/serialize/
working for me.

Categories