PHP if (isset($_POST[''])) +Jquery send in same page [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I would like to send a form so I don't get page refresh when I send a form.
Now when I press submit button I'm running this code:
<?php
if (isset($_POST['send_this_message']) == 'yes')
{
echo "yes this is just example and working";
}
?>
<form method="post" action="">
<input type="submit" name="send_this_message" value="yes">
</form>Now how can send this form but without page refresh with jquery. I have seen several examples but they are all calling external files.. Something like this.
<script>
$(function () {
$("#send").click(function () {
$.ajax({
type: "post",
url: "send.php",
data: $("#myform").serialize(),
success: function (response) {
if (response == "done") {
alert("Form submitted successfully!");
} else {
alert("Form submission failed!");
}
},
error: function (response) {
alert(response);
}
});
});
})();
</script>
This code above is not working for me. I mean I need to somehow execute that isset when pressing on button.

As you want to send data without page refresh, use Ajax to send the data from to your php file: (as example)
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('form').on('submit', function (e) {
$.ajax({
type: 'post',
url: 'post.php', // here your php file to do something with postdata
data: $('form').serialize(), // here you set the data to send to php file
success: function (data) {
alert('form was submitted');
}
});
e.preventDefault();
});
});
</script>

I don't know if I understand very well your question
However you need to set a value for your attribut action in
<form method="POST" action="">
for exemple
<form method="POST" action="responseForm.php">

you are selecting
$("#send")
it does not exist
add the id to the button
<input id="send" type="submit" name="send_this_message" value="yes">
also you need to use preventDefault() for stopping the propagation

Assuming your script is called script.php:
<?php
if (isset($_POST['send_this_message']) == 'yes')
{
// do stuff
echo "done"; // as confirmation for jQuery, see below
die(); // no output the form because ajax function isn't interested in it
}
?>
<form method="post" action="" id="form">
<input type="submit" name="send_this_message" value="yes">
</form>
<script>
$(function () {
$("#form").submit(function (e) {
e.preventDefault(); // prevent the form from being submitted normally
$.ajax({
type: "post",
url: "script.php",
data: $(this).serialize(),
success: function (response) {
if (response == "done") {
alert("stuff done");
} else {
alert("isset wasn't true");
}
},
error: function (response) {
alert("server returned a 500 error or something");
}
});
});
})();
</script>

Related

Confirm a form & display message if form is valid with JQuery

I'm developing my Django application and I would like to use JavaScript in order to improve my website.
I have a form and I would like to display 2 things :
Confirm the form before submit
If form is well submitted, display a message : 'Form is saved'
It's the first time I'm using JS and I need help to make this process.
This is my code :
<form class = "form" method='POST' action=''> {% csrf_token %}
<br></br>
{{ form.as_p}}
<br></br>
<button type="submit">Valider</button>
</form>
<script>
$('#form').submit(function() {
var c = confirm("Click OK to continue?");
return c; //you can just return c because it will be true or false
});
</script>
And if my form is valid and saved :
<script type="text/javascript" >
$(document).on('Valider', 'form.form', function(form) {
var $form = $(form);
$.ajax({
url:"/path_to_my_html_file/BC_form2.html",
type: "POST",
success: function(form) {
alert("Form is saved");
}
});
});
</script>
Could you help me ?
Thank you
You can try to adopt by your purpose this code:
$('#form').submit(function(e) {
// Prevents form to be submitted by default post request with page reloading
e.preventDefault();
if (confirm("Click OK to continue?")) {
// Here you can call your AJAX request
callAjax($('input[type=text]').val())
}
});
function callAjax(value) {
// Making AJAX request to your endpoint
// GET ipify just for example
$.ajax({
url:"https://api.ipify.org?format=json",
type: "GET",
success: function(form) {
alert("Form is saved");
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form">
<input type="hidden" value="MOCK FOR CSRF TOKEN" />
<br></br>
<input type="text" required />
<br></br>
<button type="submit">Valider</button>
</form>
Use .valid() in submit function
$('#form').submit(function() {
var isValid=$("#form").valid();
if (isValid) { //If there is no validation error
var c = confirm("Click OK to continue?");
if(c){
$.ajax({
url:"/path_to_my_html_file/BC_form2.html",
type: "POST",
success: function(form) {
alert("Form is saved");
}
});
}
}
else {
alert('form is not valid');
}
});
</script>

PHP validation for Javascript

I have a new problem. My whole website is written in PHP as well as all validations. Is there a way to do validations in php and then execute javascript like the example bellow?
if (#$_POST['submit']) {
if ($txt == "") {
$err = "No comment";
}
else {
echo "<script type='text/javascript'>
function myFunction() {
var txt' = '$txt';
var dataString = 'txt=' + txt;
$.ajax({
type: 'POST',
url: 'ajaxjs.php',
data: dataString,
cache: false,
success: function(php) {
alert(php);
}
});
}
</script>";
}
}
<div id="text">
<form action="" method='POST'>
<textarea maxlength="2000"></textarea>
<input type='button' onclick="myFunction()" name='submit' value='post' />
</form>
</div>
This doesn't work. So I'm wondering how should I do it?
I guess forms don't work with javascript, but how do I do it without a form?
You don't need to use php at all. You can post your textarea data like in the below example.
HTML
<div id="text">
<textarea id="txtArea" maxlength="2000"></textarea>
<button id="btnSubmit" name='submit'>post</button>
</div>
Javascript/jQuery
$("#btnSubmit").on('click',function(e) {
e.preventDefault();
var txtValue = $("#txtArea").val();
if(txtValue.length==0) {
alert("You have not entered any comments");
} else {
$.ajax({
type: 'POST',
url: 'ajaxjs.php',
data: {txt:txtValue},
cache: false
})
.done(function() {
alert( "success" );
})
.fail(function() {
alert( "error" );
});
}
});
The solutions is:
1. add function for submit event.
2. call ajax with form fields values as data.
3. do vildation inside php called with ajax request and return status code (valid/not valid)
4. analyse code in js and output error/success message.
First of all: Your code has a couple of errors.
You are asking if $txt == "" whilst $txt was not visibly set.
Your text area has no name
Your if doesn't ask if empty($_POST["submit"])
Second of all: You mentioned that you want the code to be executed on submit of the form. Therefore you can simple do this:
<form onsubmit="formSubmit();">
...
</form>
<script>
function formSubmit()
{
if(...)
{
return true; // Valid inputs, submit.
}
return false; // Invalid inputs, don't submit.
}
</script>
The return false is important because if it would miss, the form would be submitted as usual.

assign php output (ajax) to javascript variable

This is my first time using javascript please be respectful. I have a form which is submitting data via ajax. Everything works as intended, however I'm trying to assign what recd.php is echoing to recresponse so the correct error code is displayed in an alert. Any help or examples would be appreciated.
Form:
<form action="recd.php" method="post" id="GAMEAPPID">
<input type="text" name="GAMEAPPID" id="GAMEAPPID" />
<input type="submit">
</form>
Javascript:
<script>
$(function(){
$("#GAMEAPPID").on("submit", function(e){
// prevent native form submission here
e.preventDefault();
// now do whatever you want here
$.ajax({
type: $(this).attr("method"), // <-- get method of form
url: $(this).attr("action"), // <-- get action of form
data: $(this).serialize(), // <-- serialize all fields into a string that is ready to be posted to your PHP file
beforeSend: function(){
$("#result").html("");
},
success: function(data){
$("#result").html(data);
if(recresponse === "0") {
alert("Incomplete.");
}
if(recresponse === "1") {
alert("Duplicate.");
}
if(recresponse === "2") {
alert("Failed");
}
if(recresponse === "3") {
alert("Thanks");
}
document.getElementById("GAMEAPPID").reset();
refreshMyDiv();
}
});
});
});
</script>
I try to answer. in your "recd.php", you should assign the recresponse to a element like <input type="hidden" id="myRS" value="<?= $myRS ?>" />
and then you can access the element in your javascript.

Ajax form submit on current page

I want to submit a form by ajax and send it to my current page to prevent a refresh.
This my HTML:
<form id="suchForm" method="post" action="<?=$PHP_SELF?>">
<input type="text" id="suche" name="suche" placeholder="Suchen"/>
<input type="submit style="display:none;" />
</form>
By the way the submit button is hidden, so I am submitting the form by pressing return on my keyboard.
This is my PHP Script:
if ( $_SERVER["REQUEST_METHOD"] == 'POST' ) {
$suche = $_POST['suche'];
if (!empty($suche)) {
<?php echo $suche ?>
}
}
And finally, this is my current Ajax script:
var frm = $('#suchForm');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert('ok');
}
});
ev.preventDefault();
});
The form is submitting by Ajax successfully. The Problem: The Ajax Script prevents a refresh of the site, so nothing is shown by the PHP script (<?php echo $suche ?>). Do you have any solution to send the form with Ajax, preventing the refresh (cause some javascript should happen after the submit) and show the PHP echo?
Try replacing alert('ok'); with the code to display the ajax response. Something like this should work -
var frm = $('#suchForm');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
$('<NAME_OF_YOUR_CONTAINER_TO_DISPLAY_RESPONSE>').html(data);
}
});
ev.preventDefault();
});
If $suche is not empty, php will echo it. So if you could view the page at the time, you would see what you expect, but in this case, you have AJAX doing the submit for you, so AJAX is the one who can "see" that. If you want to display what AJAX can "see", then simply do whatever you want inside success: function()... that received the data.
You could alert(data) instead of alert("OK") to get more clues.

Issues with JQuery/AJAX Form Handling [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I have two files. This is my main file - index.php which has javascript in the head, here's the javascript:
<script
src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<script>
$(function () {
$('form#revisionnotes').on('submit', function(e) {
$.ajax({
type: 'post',
url: 'submits/updatenotes.php',
data: $('form').serialize(),
success: function () {
alert('You have successfully saved the revision notes.');
}
});
e.preventDefault();
});
});
</script>
So when my form:
<form id="revisionnotes" name="revisionnotes" method="post">
<textarea style="width:100%;height:290px; padding:10px;" id="notes" > <?php echo $db->result("SELECT * FROM revision_notes", "notes");?></textarea><br/>
<input type="submit" value="Save" name="submit" id="submit" class="btn btn-primary">
</div>
</form>
From there in my updatenotes.php I was going to do a database INSERT, however that didn't work so I then tried adding a javascript alert to see if that'd work either:
<script type="text/javascript">
alert("hi");
</script>
And that didn't work either, I'm completely stumped. Could somebody please explain to me where I'm going wrong? I've never used this type of form-submitting before.
Thanks.
You do not say where exactly the trouble lies, so this is an incomplete answer:
$(function () {
alert("Alpha - jQuery is called");
$('#revisionnotes').on('submit', function(e) {
alert("Bravo - submit received");
var data = $(this).serialize();
alert("Charlie - data serialized");
$.ajax({
type: 'post',
url: 'submits/updatenotes.php',
data: data, // $('form').serialize(),
success: function (data, textStatus, jqXHR) {
alert("Delta - POST submission succeeded");
}
});
e.preventDefault();
});
});
The above should allow you to see where (if) the workflow fails to follow the plan.
At this point the POST should have been fired, and using Firebug or WebDev you should be able to inspect the results. Otherwise, temporarily convert the POST to GET, copy the URL and paste into another browser window.
Note: do not put Javascript in the POST-receiving script, since chances are that it won't be executed. You're not "going" to that page, just doing a submit; that's why you don't see your alert.
Ordinarily you would return some information from the submission page in JSON format and let success() extract it from the data variable. Note that "success" only means that the target script received the submission, not that it did handle it properly.
Example of success function (and how to "talk" to it)
success: function(data, textStatus, jqXHR) {
if (data.status != 'OK') {
alert("ERROR " + data.message);
return;
}
if (data.message) {
alert(data.message);
// do not return
}
// other
}
So you'd start with a submit script like this (I repeat, this is awkward. You really want to do this with proper logging and Firebug!), commenting the various jqExit's once you check they code is working up to any given point:
<?php
function jqExit($status, $message = false) {
$packet = array('status' => $status);
if (false !== $message) {
$packet['message'] = $message;
}
exit(json_encode($packet));
}
jqExit('ERROR', "Alpha - got POST");
// Connect to database
jqExit('ERROR', "Bravo - connected to DB");
// Decode and validate POST
jqExit('ERROR', "Charlie - data ready");
// Perform update
if (...update failed...) {
jqExit('ERROR', "reason why it failed");
}
// Finally everything is OK
jqExit('OK');
?>

Categories

Resources