jQuery post to the same PHP page - javascript

I am creating a jQuery search bar, that will asynchronously send the inputted value from a form from the client side to the same page on the server side (in PHP). Then I can search my database with the value. Unfortunately when I send this value, using $.ajax, and attempt to echo out the value, I don't get the value at all. How can I receive my value? I've tried print_r, var_dump, echo but to no avail.
Here is my form:
<form method = 'POST'>
<input id="myInput" type ="text" name ="value"
placeholder="press enter when finished" >
</form>
And here is my script to make the call. I get the value in my console when I press enter (key===13), but it seems to be the furthest my variable (value) seems to go.
$(document).ready(function(){
$('#myInput').bind('keypress', function(e){
if(e.keyCode ===13){
let value = $(this).val().toLowerCase();
console.log(value);
e.preventDefault(); //stops the damn page refreshing
$.ajax({
type: "POST",
data: value
});
};
});
});
I haven't put the URL in the AJAX call for a reason: I'm sending to the same page.
Here is the code (further up the page) that I'm using to echo out the posted value, on the same page.
if(isset($_POST['value'])) { echo $_POST['value']; exit; }
No matter what I seem to do, my value isn't sent to the page! I've tried to add in the URL, I've added "success" to the call.... nothing seems to work.
How can I successfully send my data?

Related

JQuery / AJAX: On Input Field change, create php session, and refresh current page

I have two input fields. One is for show called business and the other is hidden called auto_search_id and goes to server. I have already created an autocomplete functionality. What I want to do is if the user starts typing and decides to click on an autocomplete list item which has already stored businesses, the page takes the id, sends it to update.php page to update the PHP Session id, and then refreshes the page with the current Session id.
Having problems figuring out the correct AJAX coding. My change function for the input field is not working. It pulls up the autocomplete, but when an auto complete list item is clicked, it doesn't send the id and refresh a page. I still new to JQuery/AJAX, but think I am missing something in the on #auto_search_id change function but not knowing what. Please Help...
Javascript / JQuery / Ajax
<script>
$(document).ready(function(){
$("#business").autocomplete({
minLength: 2,
source: function(request, response){
$.ajax({
type: "POST",
url: "/autocomplete-pq.php",
dataType: "json",
data:'keyword=' + request.term,
success: function(data){
response(data);
}
});
},
select: function(event, ui){
$("#business").val(ui.item.label);
$("#auto_search_id").val(ui.item.value);
return false;
}
});
$("#auto_search_id").change(function(){
$.ajax({
type:'POST',
url:"/update.php",
data: { varname: reponse},
success:function(response){
location.reload()
}
});
});
});
</script>
PHP
<?php
session_start();
$_SESSION["id"] = $_POST["varname"];
echo $_SESSION["id"];
?>
HTML
<input type="text" id="business" name="jurisdiction" value="<?php echo $juristiction ?>" required>
<input type="hidden" name="search" id="auto_search_id" />
I cannot reproduce the code but i see 2 things being wrong:
1 Calling $("#auto_search_id").val(ui.item.value); actually sets a new value of an input, however it does not trigger it's change event. You should trigger it like so:
$("#auto_search_id").val(ui.item.value).trigger("change");
2 You are trying to send a response (which is not available yet) to the server. A assume you want to send the hidden field value to the server.
$("#auto_search_id").change(function(){
var newID = $(this).val();
$.ajax({
type:'POST',
url:"/update.php",
data: {varname: newID},
success:function(response){
location.reload()
}
});
});
First you need the check if the change event is been called. Put an alert inside it. To maintain session, you need to pass it's id calling the parameter PHPSESSID, but it has some security implications, please read: http://php.net/manual/pt_BR/function.session-id.php

Trouble passing a variable from javascript page to php page

I want to send a string from one php page to another via a JavaScript page.
The string is sent through upon the push of a button. The name of the
button is changed each time it is displayed and the name of the button is
the one that is sent through. The problem is, it is not getting displayed in
next php page but the alert() function outputs the string as required. What
is wrong with the code?
Here is the php code in the first page
echo "<form method = 'post' action = 'passer.php'>
<input type = 'submit' value = 'play' name = '$ball'></input>
</form>";
Here's the javascript code
$(':input').click(function(){
var cat = $(this).attr("name");
alert(cat);
console.log(cat);
$.post("studSport.php",{input: cat}, function(data){
});
});
And the php code in the next page
{
$receiver = "";
if(isset($_POST['input'])){
$receiver = $_POST['input'];
echo $receiver;
} else{
echo " it is empty";
}
}
The output is always "it is empty" even though the alert() displays the right variable. What is wrong with the code, why wont $receiver be displayed?
Your Ajax request never runs. When you click the input you trigger it… but the input is a submit button so the Ajax request is canceled, the form submits, and a new page is loaded.
Since your form doesn't have an input named input, you'll always failed the test if(isset($_POST['input'])). (The Ajax request, which gets canceled, does input input, but you never make that request).
To stop the form submitting you need to capture the event object and prevent the default behaviour that the event would normally trigger.
$(':input').click(function(evt){
evt.preventDefault();
Note, however, that your success handler function:
function(data){
}
… does nothing, so you won't be able to see the result without inspecting the HTTP response using your browser's developer tools.
It is possible that your goal isn't to use Ajax, but is to load a new page - just with additional data in the form.
To do that, you need to modify the controls in the form instead.
$(':input').click(function(){
var cat = $(this).attr("name");
alert(cat);
$(this).append(
$("<input type='hidden' name='input'/>").val(cat)
});
});
But if you just want to tell which submit button was pressed then don't involve JavaScript at all. Just use a submit button with the name and value you want.
<form method='post' action='passer.php'>
<button name="input" value="<? echo htmlspecialchars($ball); ?>'>
play
</button>
</form>

Can't get values from form?

I can't get the value from the form. Due to Firebug the form is submitted tho and when I delete the js it works so it has something to do with it.
$ok= $_POST['ok']; //this doesnt work
if($ok== "ok" ){
echo "works";
}
<script type="text/javascript">
$(document).ready(function() {
var frm = $('#form');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
});
ev.preventDefault();
});
});
function submitForm2() {
$('#form').submit();
}
</script>
<div onclick='submitForm2();'></div>
<form action='' method='post' id='form'>
<input type="hidden" name='ok' value="ok">
</form>
When the form is submitted, your first set of JavaScript kicks in. It:
Stops the normal submission process running
Takes the data from the form and submits it via Ajax
Since the normal form submission doesn't run, the page doesn't reload, so you don't load a new document, so you don't see the document with the ok in it loaded in the main browser window.
Since you don't have a success handler for the Ajax request, you completely ignore the response the server sends back to the JavaScript … so you don't see that document (with the ok in it) either.
If you want to see the results of an Ajax request, then you have to write JS to show you the results (or examine the Net tab of your developer tools).

How does "Add Comment" javascript/AJAX work on stackoverflow?

I was just looking at the code in firebug and I can't follow it. I can't figure out how clicking "add comment" calls the jquery function that shows the comment form. On my site I am trying to mimic this behavior. I have a registration form and I want a link such as "Fill in my data" which then displays a text input below the link where they enter a code, and then a submit button that through AJAX populates the fields. I am new to js and AJAX, but am a quick learner so I was hoping to get some clarity here on the details of implementation. Seems to me the displaying of the input field should not be AJAX, but just js. And then submit would trigger the AJAX function. I know AJAX is fairly involved, in terms of having to create an xml that describes the server side data that needs to be collected and then somehow submit button will trigger call to server side php script or something. Conceptually I understand, but mechanically I don't... Thanks! Brian
I just tried implementing as described, but the url is not triggering the js. Here is what I have:
<script type="text/javascript">
$(function(){
$(".previousreg-link").on("click", function( event ){
event.preventDefault(); // Prevents browser following #hash
$(this).hide(); // hide the button
$(".previousreg-form-container").show(); // Show the form parent
});
$(".previousreg-form-container form").on("submit", function( event ){
event.preventDefault(); // Don't send headers
alert( $(this).serialize() +"\nWILL BE SENT TO PHP" );
// $.ajax stuff
});
});
</script>
<a href=# class=previousreg-link>Use previous registration data</a>
<div class="previousreg-form-container dno">
<form>
<textarea name=previousreg></textarea>
<input type=submit>
</form>
</div>
Because my site already loads jquery I didn't add the script declaration for jquery. Is anything above obviously wrong? Thanks.
Here in StackOverflow, the form is already present, but hidden initially (to save valuable space).
(StackOverflow uses a .dno class to hide elements.)
The click on the add a comment button does simply:
hide the clicked add a comment button
show the DIV holding the form
A simple way to do it:
$(function(){
$(".comments-link").on("click", function( event ){
event.preventDefault(); // Prevents browser following #hash
$(this).hide(); // hide the button
$(".comment-form-container").show(); // Show the form parent
});
$(".comment-form-container form").on("submit", function( event ){
event.preventDefault(); // Don't send headers
alert( $(this).serialize() +"\nWILL BE SENT TO PHP" );
// $.ajax stuff
});
});
.dno{display:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href=# class=comments-link>add a comment</a>
<div class="comment-form-container dno">
<form>
<textarea name=comment></textarea>
<input type=submit>
</form>
</div>
Regarding the $.ajax
since by submitting the form we don't want the page to refresh, AJAX is used to POST data to a PHP (let'ssay: saveComment.php page) which than stores to database. AJAX returns than a message response from the PHP code:
$.ajax({
type : "POST",
url : "saveComment.php",
data : $(this).serialize(), // `this` is our form
success : function( response ) { // Response is the PHP echo
alert("PHP says: "+ response);
// Using jQuery append the message to
}
});
The PHP stuff
in the code above AJAX will POST a serialized data to PHP like:
comment=Please, show what you tried!
The saveComment.php than might look like:
<?php
if ($_SERVER['REQUEST_METHOD'] != 'POST') exit; // Don't allow anything but POST
$response = "";
if ( isset($_POST["comment"]) ) {
$commment = htmlspecialchars( $_POST["comment"] );
// TODO: $userId = retrieve here the user ID from the session;
// Sanitize(!!!!!) and save to database $comment and $userId
$response = $commment;
} else {
$response = "Please, enter a comment";
}
echo $response; // This will be sent/returned to AJAX
exit;
above, whatever you put in the echo, it will be returned by AJAX into the response argument.

Sending dynamic POST data with Javascript

So basically, I'm trying to send some data to a remote PHP page, via POST, with 4 static parameters and one random parameter, a number.
So far what I have done is created an HTML page with a form with 4 hidden fields and 1 empty field, in which a random number is inserted as the value via Javascript (using Math.random). Now whenever I submit this form, it takes me to the remote PHP page, and so I have to click back again (in the browser) and then submit.
So, I decided to load this form in an iFrame in another HTML Page, so after clicking submit, I can just hit refresh, and then submit again.
I want to know, is there a way I can use Javascript in the parent HTML to automatically submit the form in the iFrame, then create a new random value and submit it again?
Here is my code so far
a.html
<html>
<body>
<form method="post" action="http://awebsite.com/remotefile.php">
*some hidden fields with the static values*
<input type="text" id="mytext" name="mobile_no">
<input type="submit">
</form>
<script>//don't remember the exact code, use javascript to generate a random number which is put in the value for mytext via getElementById</script>
</body>
</html>
now this was the form which was to manually send data to the server
this is to load an iframe:
b.html
<html>
<body>
<iframe src="a.html">
</body>
</html>
Can I use javascript in b.html to resend the form multiple times, but with the value of mobile_no different each time?
Or can I simply send POST data with the parameters to the server via simple Javascript (or PHP)
You question isn't 100% clear, but it sounds like you want to asynchronously post form data. You could easily do this with a JavaScript library like jQuery without the need for an iframe. First you should add an ID attribute to your form to make it easier to reference in your jQuery code. Then you can attach an event listener to the form's submit event where you can customize the form before submission and handle the response
$('#myForm').submit(function(e) {
// prevent default form submit action from occuring
e.preventDefault();
// load values need to make AJAX request
var method = $(this).attr('method');
var action = $(this).attr('action');
// Process Ajax request
$.ajax({
type: method,
url: action,
dataType: 'html',
data: $(this).serialize(),
beforeSend: function() {
// generate and assign per form submit random number
// show loading gif
},
success: function(response) {
// AJAX POST success, insert the HTML response into the DOM
},
error: function(jqXHR, textStatus, errorThrown) {
// console.log any errors for debugging here
},
complete: function() {
// Post completion tasks, such as hide loading gif
}
});
});

Categories