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>
Related
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?
Please note this is not a duplicate question. This question involves submitting a form and refreshing a div on a change event - not a click event. FYI.
I have a form to allow users to upload an image. I have removed the submit button and added a javascript on change event to submit the form automatically when the user inputs an image.
This works fine and the image is uploaded.
However, I am also pulling through the image to display this to the user. At the moment, the user does not see the image change until they refresh the page or sometimes not even until they clear their cache.
The div containing the images should refresh upon the form being submitted, and the page itself should not refresh. At the moment the div is not refreshing and I think the form is submitting and refreshing the page.
Please can someone show me where I am going wrong? Thanks
Code:
<!-- Commence Photo Upload A -->
<?php
if(isset($_FILES['image6'])){
$dir = $image .'/F/';
$file_name = $_FILES['image6']['name'];
$file_name = $dir. 'sub_img.jpg';
$file_size = $_FILES['image6']['size'];
$file_tmp = $_FILES['image6']['tmp_name'];
$file_type = $_FILES['image6']['type'];
$tmp = explode('.',$_FILES['image6']['name']);
$file_ext=strtolower(end($tmp));
$extensions= array("jpeg","jpg","png","gif");
if(in_array($file_ext,$extensions)=== false){
$errors[]="extension not allowed, please choose a GIF, JPEG or PNG file.";
}
if($file_size > 2097152) {
$errors[]='File size must be excately 2 MB';
}
if(empty($errors)==true) {
move_uploaded_file($file_tmp, $file_name);
}else{
}} ?>
<script>
$('#uploads6').submit(function(){
var data = $(this).serialize();
$.ajax({
url: "upload_6.php",
type: "POST",
data: data,
success: function( data )
{
//here is the code I want to refresh the div(#container)
$('.image6').html(data);
},
error: function(){
alert('ERROR');
}
});
return false;
});
</script>
<form id="uploads6" action = "" method = "POST" enctype = "multipart/form-data">
<label class="profile_gallery_image_in"><input type="file" name="image6" id="image6" onchange="form.submit()"/><p class="label"></p><img class="myImg" src="<?php echo $image.'/F/sub_img.jpg'; ?>" height="100%" width="100%" /></label>
</form>
For image caching you can try the age old "cachebuster" method.
All it is is put something unique into the url query.
www.example.com/image.jpg?cachebuster=somethingunique
The browser will see this as a new request because it doesn't know what the query string does, it could be a search form for all it cares. So it will not pull it from the cache.
Good choices for the something unque is any time based component, as you know its never been used before. Ive used filesize($file) before when doing image edits.
$url = "www.example.com/image.jpg?cachebuster=".microtime(true); //as a float
$url = "www.example.com/image.jpg?cachebuster=".time(); // only 1 second granularity
$url = "www.example.com/image.jpg?cachebuster=".filesize($file); // based on the size of the file
$url = "www.example.com/image.jpg?cachebuster=".hash_file($file); //based on file contents
And so on. You can even do it in JavaScript if you want to.
For the form
$('#uploads6').submit(function(e){
e.preventDefault();
//.. other code
return false;
});
One note is using $.post how you are will probably prevent the file from being uploaded.
Here is another SO question on that:
jQuery Ajax File Upload
If you want a non-javascript way to upload without refreshing page, you can also do it though an iframe but the onLoad even may not work in Chrome for that, so it can be hard to tell when the file is uploaded from the client side.
Here is a SO question I answered on that back in 2014
How can I upload files asynchronously?
To prevant default form submission try:
e.preventDefault();
To stop event bubling try:
e.stopPropagation();
Also try to add a ‚#‘ or ‚javascript:void(0)‘ in your HTML action-attribute.
You need to use
$('#uploads6').submit(function(e) {
e.preventDefault();
// your code
}
to prevent the submit event from directing to the page that is given in the action value. This is right now the same page since the value of the action attribute is an empty string and therefor the page is refreshed.
I have a form which contains many drop-down and numeric slide-bar.
I am using post method to pass the selected variables to another page. Where I am getting the variables in the next page by $_POST() method.
And I am updating the variables passed into the database, after updation giving javascript pop-up as "you have saved successfully".
So my problem is when I click on browser back button, the values are getting updated in the database again and again. How can I prevent this by disabling browser back button.
You can have your post method open up a new tab so that there is no back navigation to go to:
<!DOCTYPE HTML>
<html>
<body>
<form action="www.google.com" method="post" target="_blank">
<input type="submit">
</form>
</body>
</html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$('#theSubmit').on('click', function () {
setTimeout(function(){
window.close();
}, 500);
})
</script>
The target generates the new window
And if you would like to close the old window add the two scripts that close the previous tab 500ms after the new tab is opened.
Instead of disabling the back button, you could redirect the user if he gets back to the page using sessions.
page1.php
session_start();
if (isset($_SESSION['block'])) {
header('Location: page2.php');
}
page2.php
session_start();
$_SESSION['block'] = true;
Another option:
This is how you could set values of all your input fields back, if the user clicks back:
page1.html
var block = localStorage.getItem("block");
window.addEventListener("beforeunload", function() {
if (block === 1) {
const block = true;
}
});
if (block) {
const inputs = document.getElementsByTagName('input');
for (input of inputs) {
input.value = '';
}
}
page2.html
localStorage.setItem("block", 1);
In this case, if you don't want your values get updated in your database, use:
if (!empty($_POST['my_value']) { // Add to database })
Don't disable the back button, fix the problem that the data is saved multiple times instead. You could use pass the users to a separate page with message "you have successfully...".
Then if the user tries to go back you look at $_SERVER['HTTP_REFERER'] if that is "successful.php" then don't save the data.
Disabling back buttons is a big reason for me to block a page so that I can't visit it again.
I truly hate when they do that or add several pages that you have to click back to get out of a page.
Whenever you post your data then you should check your post data that this is empty or not
<?php
if(isset($_POST) && !empty($_POST) ){
//your code for update
//Then after run update query and success message ,do empty the post
$_POST=array(); // empty the post
}
?>
I have a form and when you submit it, a JavaScript message appears.
$message = "Want to insert?";
echo "<script type='text/javascript'>window.confirm('$message');</script>";
And what I want to do is, if the person clicks 'OK' it inserts values in the database, if not it cancels it.
$titulo = $_POST['titulo'];
$mensagem = $_POST['mensagem'];
$ano = $_POST['ano'];
$mes = $_POST['mes'];
$dia = $_POST['dia'];
$link = " ";
Use <form> tag, and handle the onsubmit event. once he clicked 'OK' on message box submit the form.
Once the form gets submitted, In server side (PHP) write a code to get the data ( either by GET/POST which ever way you are sending) and insert into the table.
In simple words, PHP executes first, and then client side JavaScript executes. If you want it to be interactive, you must use AJAX, which will allow you to send PHP command controlled by JavaScript.
If I were you, I would do this way:
if (confirm("Are you sure?"))
$.post("path/to/php.php", {data: you_need_to_send}, function (response) {
if (response == "OK")
alert("All Done!");
});
else
alert("You cancelled the insertion.");
Note: Here, $.post() is a jQuery implementation of AJAX POST method. Just for ease of explanation I gave this. Please don't shout at me for answering a jQuery way for a JavaScript question.
Update
You can use onsubmit of the form to make this possible. Make sure you give a return inside the event:
<form method="post" action="http://example.com/" onsubmit="return confirm('Are you sure?');">
<input />
<input type="submit" value="Send" />
</form>
Run the above snippet and check it out.
You need to pass data using a request to your server. You cannot use JavaScript to write in you database directly since you already use PHP
But to confirm the user before you send your request or you can use this in your JavaScript code before you send your request.
if (confirm('Your Message')) {
// User click OK
// Send your data to server using a Request
} else {
// User click cancel
}
I have a page which loads content from a different file (content.php) into a div and reloads it every 5 seconds.
In the content.php file I am using a form (simple HTML without javascript). When I access the file directly (example.com/content.php) the form works, but when I load it into a div of a different page with ajax, I cannot click the button.
How can I modify the form that the button is clickable when the file is loaded into a div?
Thats the form in content.php:
echo ("<form action='submit.php' method='GET'>");
echo ("<input type='hidden' name = 'value' value = '".$value1."'>");
echo ("<input type='hidden' name = 'value2' value = '".$value2."'>");
echo ("<button class='button-1' type='submit'>".$button_text."</button></form>");`
This form code is in a for-loop, so there are several buttons.
From my understanding of your question, you are loading a form from page contact.php on to a different page using ajax and that is working correctly. However, clicking the submit button on the form created in this second page doesn't do anything?
Have you tried assigning an onclick event to the submit and console logging the data? If you're testing in chrome, are there an errors that pop up in the inspect element?
Are you passing the php response as JSON or just echoing out all the input elements? I'm assuming that the form is being passed by echoing out the elements like so:
echo "<input type='submit' value='Submit'/>";
You could try in your php
echo "<input type='submit' value='Submit' onclick='testFunc()'/>";
and in your javascript create the function:
function testFunc() {
alert('Submit button clicked');
//log whatever input values you want passed to the server replace sampleInput1 with whatever id you are using for the inputs
console.log(document.getElementById('sampleInput1').value);
}
If the alert pops up and the input logs ok, from there just create another ajax call to submit your form, if you want to stay on that page. Alternatively, check the <form> tag what is the action and method?
Alright after rereading your code add id='hidVal1' and id='hidVal2'to your hidden inputs like so:
echo("<input type='hidden' id='hidVal1' name = 'value' value = '".$value1.
"'>");
echo("<input type='hidden' id='hidVal2' name = 'value2' value = '".$value2.
"'>");
I am assuming that you know how to make an ajax function, so to create the values to send use the testFunc() I suggested and make it like so:
function testFunc() {
alert('Submit button clicked');
var hidVal1 = document.getElementById('hidVal1').value;
var hidVal2 = document.getElementById('hidVal2').value;
//log for testing
console.log("value of hidden 1 " + hidVal1 + "value of hidden 2 " + hidVal2);
//url for ajax
var url = "submit.php?hidVal1=" + hidVal1 "&hidVal2="+
hidVal2;
//call to ajax function
}