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
}
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?
Very brief, this is my php code in myPage.php:
<div class="table-responsive" id="items">
<table class="table" id="myTable">
<thead><tr><th>item<th>status<th>options</thead>
<tbody>
[...]
echo "<tr><td>$item<td>$status<td>to-be-added
[...]
echo "<tr><td colspan='3'>";
echo "<form method='post' id='newitem'>";
echo "<input type='hidden' id='uid' name='uid' value='$uid'>";
echo "<div><button type='submit' class='btn btn-info' id='submitbtn'>new item</button></div>";
echo "</form>";
[...]
And this is my .js file ajax code:
$(document).ready(function () {
$('form').submit(function (event) {
$('#errors').remove(); // remove the error text
$('#success').remove(); // remove the success text
var formData = $("#newitem").serialize();
$.ajax({
type: 'POST',
url: 'process.php',
data: formData,
dataType: 'json',
encode: true
})
.done(function (data) {
console.log(data);
if (!data.success) {
$('form').append('<div id="errors" class="alert alert-warning"></div>');
if (data.errors.validitem) {
$('#errors').append('<p>' + data.errors.validitem + '</p>');
}
} else {
$('#addresses').append('<div id="success" class="alert alert-success">' + data.message + '</div>');
$("#myTable").load("mypage.php #myTable");
}
})
.fail(function (data) {
console.log(data);
});
event.preventDefault();
});
});
I Don't show the process.php function as that is not most likely the problem.
When I first load the page and press submit following things happen:
a new item is created via ajax
table gets populated with new entry w/o page refresh but using the load option: *$("#myTable").load("mypage.php #myTable");*
in conclusion, everything works as expected!
Note: only after I add the table load the problem appears. $("#myTable").load("mypage.php #myTable");
Without this reload of the table after submit, submit always work, just that the table doesn't show real time the changes and I need to do F5 ... which is not the plan.
After the load of the table, when I press the button again, nothing appears to happen, except that my success message disappears.
At this stage I need to press the button twice. Only after I press submit a second time, the ajax executes ok and table shows the new item created.
This behavior is consistent for all next submits. All execute only after second submit.
I need some help here please. What is happening?
I want to reload only a section of the myPage.php, so only the full table #myTable or whole div #items, with all the validation functions I have in myPage.php
I don't want to recreate full table in the process.php and send it over via POST as I have seen some recommend in other forums.
The issue is here : $("#myTable").load("mypage.php #myTable");
mypage.php is your main page. And you load it once. Then, inside the table, you use that .load() to overwrite it all. Which is no good.
You then have a brand new table where no handler is binded to the submit button. So on submit button click (second time), the form is submitted using the "normal behavior" of a <form> element... And the page is fully reloaded.
As a possible solution, I would use .load() on the form... Not the table, like this:
$("#newitem").load("mypage.php #newitem");
But you should try $("#newitem").reset() and just remove #error and #success... Instead of that .load().
EDIT
Second taugth:
Try $(document).on("submit", "form", function (event) {
instead of $('form').submit(function (event) {
That is delegation... So your submit button always will be binded to the function, even if it is overwritten.
This is my code for submit form, when I click on button perform Checkout() function
function postURL(url) {
var form = $('<form action="' + url + '" method="post">' +
"<input type='hidden' name='CheckedData' value='" + JSON.stringify(CheckedArray) + "'/>" +
'<input type="hidden" name="URL" value="CQLandingPage" />' +
'</form>');
$('body').append(form);
form.submit(); }
function Checkout() {
var CheckOutUrl = "https://www.facebook.com/";
postURL(CheckOutUrl);
}
I want to redirect my page on CheckOutUrl but in this case it redirect to same requested page in DNN
i have applied this code in footer of module from
setting > advance setting of specific module
I have two different domain from request and to response and having one form already in html
Mitchel Sellers has a blog post about this:
https://mitchelsellers.com/blogs/2007/04/03/allowing-html-form-submissions-from-dnn
The short version is there's already an html form element on the page. Adding your own form will conflict with this. However, you can use existing the form, and instead just give your "new" form a button or button-type input element with an onClick that uses javascript to change the existing form's action before it submits:
<button onClick="this.form.action='YourUrlHere';this.form.submit();">...</button>
The downside to this is all of the other inputs on the page will submit (you're submitting the whole form). As long as there are no conflicting input names this shouldn't actually break anything; just be aware it may create security or privacy concerns.
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>
UPDATE: I resolved my issue by moving my form submitter script from the Header to the bottom of the jamesmsg.php page (the included one). This way the functions always get re-loaded and attached to the "new" form everytime the div is refreshed.
This is a follow-up to a previous question I had about getting only a div to refresh (and not the entire page) when submitting a form. I've stripped out all the unnecessary javascript and code to just focus on this problem but I'm still stumped.
When I click submit the first time, the data is posted and we're good. When I click submit the second time, the entire page refreshes, the URL now shows POSTed data.. the good news is the data IS inserted to the mysql db, I just need to get this form acting properly like it does for the first click (at least it appears to do so).
My main php file is james.php:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
</head>
<body>
<div id='mainpage'>
<div id='control'>CONTROL DIV 1 ... 2 ... 3</div>
<div id='statusupdates'><? include 'jamesmsg.php'; ?></div>
</div>
</body>
</html>
so you can see I have a "Control Div" which should never change and my statusupdates div which should always be updated with the submitted form data (and a subsequent pull from mysql to show the latest updates).
jamesmsg.php (mysql credentials xxx intentionally for this post):
<?
$xxx = new mysqli("xxx","xxx","xxx",xxx);
$MsgText = $_POST["MsgText"];
if ($MsgText != "") {
$query = "INSERT INTO Messages SET
MsgDate = NOW(),
MsgAuthor = 0,
MsgText = '" . mysqli_real_escape_string(xxx,$MsgText) . "'";
if (!xxx->query($query)) {
print "error! xxxx->error<BR>query = $query<BR>";
}
}
print "<form id=\"statusform\" action=\"james.php?L=1\">
<textarea name=MsgText rows=5 cols=40></textarea><BR>
<input type=submit value=Post id=uhsbutton>
</form>";
?>
<?
print "<BR><BR><pre>POST Variables:<BR>";
print_r ($_POST);
print_r ($_GET);
print "</pre>";
?>
<?
$query = "SELECT * FROM Messages ORDER BY MsgDate DESC LIMIT 5";
$msgq = $xxx->query($query);
if ($msgq->num_rows > 0) {
while ($r = $msgq->fetch_array()) {
print ".......<BR>";
print "msg ID: " . $r["ID"] . " - " . $r["MsgDate"] . " " . $r["MsgAuthor"] . "<BR>";
print $r["MsgText"] . "<BR>";
}
}
else {
print "no messages";
}
?>
<script>
/*************************************
* form submitter
**************************************/
$(document).ready(function() {
$("#statusform").submit(function(e) {
e.preventDefault();
var data=$(this).serialize();
var pUrl="jamesmsg.php";
submitFormSave(data, pUrl);
});
function submitFormSave(data, pUrl) {
$.ajax({
url: pUrl,
type: 'POST',
cache: false,
data: data,
success: function(response) {
$("#statusupdates").html(response);
}
}).success(function(){
});
}
});
</script>
You can see this in action by going to: demo
Viewing this in Chrome's console I get no errors at all.
The problem is with the success callback that you've set for your AJAX call:
success: function(response) {
$("#statusupdates").html(response);
}
This ends up overwriting the entire form and the original submit event handler you set up when the page first loaded is lost. Since there is no event handler present to prevent the default behaviour, the second button click causes the entire page to refresh.
So, what I would do is get your server response to return data in the form of JSON or XML (preferably JSON since it easily integrates with JavaScript).
Right now, your server response is returning HTML back. This is something you want to avoid. The server should serve you data and then on the client side you should dynamically generate your HTML via JavaScript to show data in a readable format.
I solved my issue by moving the javascript from the Header to appear at the bottom of the included page: jamesmsg.php.
I'm now able to post and have the appropriate div refresh without the entire page always refreshing.