PHP javascript problems - javascript

I am totally new in php, so my opology if this question seems weird to you.
I have one php file (index.php) something like,
echo "
<div>
<FORM name='myform' id='myform' method='post' action=''>
// I fetch data from mysql and populate dropdown list. Tha't work fine.
// Then I have one submit button when I click on that
echo "<button id='showButton' type='submit'> Show </button>";
</FORM>
";
Then I have one process.js file something like,
$(document).ready(function() {
$('#showButton').click(function () {
// Here I make one AJAX call to php file (fetch_more_data.php), which fetch more data from database
// This also works fine
});
});
In fetch_more_data.php I fetch more data and display in table using
echo "
<script type = 'text/javascript' src = 'edit.js'></script>
<table ...>
<td>
<button id="myButton"></button>
</td>
</table>
";
This is also work fine. but I want to edit one table cell and for that I need to write some java script code. I want to write on click function for myButton in Javascripr, for that I have written on edit.js file,
$(document).ready(function() {
$('#myButton').click(function () {
alert('Hello');
});
});
The problem is $('#myButton').click(function () never called. I have spent long time but being a beginner my search options are limited.
I would appriciate if someone solve this problem.
Regards,

try calling it like this:
$(document).ready(function(){
$(document).on('click', '#myButton', function(){
alert('hi');
});
});
hope this helped

try with
$('#myButton').live('click',function () {
alert('Hello');
});
});

Try this:
$(document).ready(function() {
$(document).on("click", "#myButton", function () {
alert('Hello');
});
});
Since the html is being added to the DOM dynamically, you need to handle it using Event Delegation in jQuery

I think the problem is that you are not loading the jQuery
Download the jquery on the same folder where is your php file and add this line in your code
<script src="jquery-1.11.0.min.js"></script>

Related

Second button doesn't produce form in same div as first button

I have a php page with two divs. In the first div, users click a button and it brings up a form in the second div. When they submit the form, both divs refresh. All is great. But I want to add a second button to the first div to bring up a different form in the second div. I haven't been able to get this to work, either the first button stops working or the second one doesn't work. I tried making the second button a div and calling it by its ID and that didn't work. I'm an amateur and don't understand jquery very well (I think this is jquery anyway) and this is just for a project for some friends and I, so any help would be appreciated. I may just not be understanding how this works.
<script>
$(document).ready(function () {
$("button").click(function () {
var handle = "<?php echo $_SESSION['name'] ?>";
$("#infoblock").load("createhandle.html");
});
});
</script>
<div id="div1">
<button id="reservename">Reserve A Name</button>
</div>
<div id="div2"></div>
I found a solution here: https://stackoverflow.com/a/20074373/9157720
It ended up being an issue with syntax and using a pound symbol. This is the code that worked in case anyone else has this problem.
<script>
$(document).ready(function(){
var handle = "<?php echo $_SESSION['name'] ?>";
$("#reservename").click(function(){
$("#infoblock").load( "createhandle.html");
});
$("#uploadpic").click(function(){
$("#infoblock").load("uploadpic.html");
});
});
</script>
<button id="reservename">Reserve A Name</button>
<button id="uploadpic">Upload A Picture</button>
Consider the following.
<script>
$(document).ready(function () {
$("button").click(function () {
var handle = $(this).data("ref");
var target = $(this).data("target");
$(target).load("createhandle.html?handle=" + handle);
});
});
</script>
<div id="div1">
<button data-ref="<?php echo $_SESSION['nameA']; ?>" data-target="#infoblock">Reserve A Name</button>
<button data-ref="<?php echo $_SESSION['nameB']; ?>" data-target="#div2">Reserve B Name</button>
</div>
<div id="div2">
</div>
Your example is sort of ambiguous, so I wasn't sure what you were trying to accomplish. It's best to not mix PHP and HTML if you can. You can have a reference point in the HTML so that when you need to load something, in relationship to that button, you can pass that into a stand alone PHP Script and get the HTML you need back with .load().
Remember that PHP is executed before the HTML is presented to the Client. So the Session data must be present in PHP Memory when the page is initially loaded.
Reference:
https://api.jquery.com/data/
https://api.jquery.com/load/
jQuery $(this) keyword

Programmatic Form POST from jQuery doesnt work in document ready

I have the below script in my code:
<script src="~/Scripts/jquery-2.2.3.js"></script>
<script type="text/javascript">
$(document).ready()
{
$("#hdnTest").text('#ViewBag.Test');
$("#frmRouter").submit();
};
function submitform()
{
$("#frmRouter").submit();
}
</script>
I also have the below html in my mvc view:
<form id="frmRouter" method="post" action="https://localhost/Destination/Index">
<div>
<input type="hidden" id="hdnTest" name="hdnTestName" />
</div>
Click
</form>
When I click on the hyper link, the form is getting posted to the action URL. However, the form submit inside the document.ready doesn't work. Why is it so?
You've written the code in a way that's syntactically correct, but functionally wrong:
$(document).ready(function() {
$("#hdnTest").text('#ViewBag.Test');
$("#frmRouter").submit();
});
is what you want. The .ready() method should be passed a reference to a function. It doesn't have to be an anonymous function (as above), but that's pretty common.
Your code was missing the function, so jQuery just basically ignored the method call. The subsequent block of code was executed, but since the form element didn't exist in the DOM it didn't do anything.
Your document.ready has not the correct syntax.
You have two ways to perform a document.ready function.
$(document).ready(function () {
$("#hdnTest").text('#ViewBag.Test');
$("#frmRouter").submit();
});
$(function () {
$("#hdnTest").text('#ViewBag.Test');
$("#frmRouter").submit();
});
$(document).ready(function(){
$("#id_of_your_anchor_tag").click(function(){
$("#hdnTest").text('#ViewBag.Test');
$("#frmRouter").submit();
});
});
Click
Try this way,
Hope it helps !

Getting Javascript/jQuery and PHP To work together

UPDATED:
Okay, Thanks to OneSneakyMofo's Help below, I have managed to use ajax to call a submit.php form and have it return for example an echo statement. My problem is that none of my $post values are being carried over, for example if my start my php script with if (isset($_POST['pizzacrustformid'])) { the javascript will return blank, also when I do a var_dump($_POST);, Nothing is being saved into it which means the data is not being carried over, the php script is just being called. Please let me know if there is something I need to do in order to get the POST information to get carried over from the form as it would with a
< Submit > Button traditionally.
I Have Updated my code on Github to reflect my progress. https://github.com/dhierholzer/Basiconlineordering Thanks Again!
ORIGINAL POST:
I am new to using jquery and having forms be submitted without loading a newpage /refreshing the page.
In my Code I have multiple forms on one page that display one at a time via fade in and out effects by hitting the next button.
My problem is now that I do this, I cannot seem to get a PHP script to activate when hitting the next button to save those form options into sessions.
So here is an example:
<!--First Pizza Form, Pick Pizza Crust Type-->
<div id="pizzacrust">
<form method="post" name="pizzacrustform" id="pizzacrustformid">
<div id="main">
<div class="example">
<div>
<input id="freshpizza" type="radio" name="pizzacrust" value="1" checked="checked"><label style="color:black" for="freshpizza"><span><span></span></span>Fresh Dough</label>
</div>
<div>
<input id="originalpizza" type="radio" name="pizzacrust" value="2"><label style="color:black" for="originalpizza"><span><span></span></span>Original</label>
</div>
<div>
<input id="panpizza" type="radio" name="pizzacrust" value="3"><label style="color:black" for="panpizza"><span><span></span></span>Deep Dish Pan</label>
</div>
</div>
</div>
</form>
</div>
<div><button href="#" id="btn">Show Pizza Size</button></div>
So this Is my First Form, One thing to pay attention to is that instead of a < Submit > button, I am using a normal button and using javascript to do the submitting part.
Here is that Javascript:
<!--Controls All Button Fades-->
$('#btn').click(function(e){
$('#pizzacrust, #btn').fadeOut('slow', function(){
$('#pizzasize, #btn2').fadeIn('slow');
$('#pizzacrustformid').submit();
});
});
and Then:
$(document).ready(function () {
$('#pizzacrustformid').on('submit', function(e) {
e.preventDefault();
});
});
Now Traditionally being a php programmer, I just had a button in my form and then my php activated by having something like:
if (isset($_POST['submitted'])) { //MY Code To save values into sessions}
I cant seem To Get a function like that working when the form is submitted via a javascript function as I have it.
Here is my full code in my GitHub which may make it easier to see more so how these forms are working together right now.
https://github.com/dhierholzer/Basiconlineordering
Please Let me know any solutions that might be possible
Thanks again.
Edit:
OP, it looks like you are wanting to do AJAX, but you don't have anywhere to submit your AJAX to. Firstly, you will need to create a file that accepts the form.
Let's call it submit.php.
With that in place, you can start working on the AJAX call. To begin, you will need to separate your code from index.php.
Take this out of index.php and put it in submit.php:
if (isset($_POST['pizzacrustformid'])) {
// use a foreach loop to read and display array elements
echo '<p>hello!<p>';
}
In your Javascript, you will need to do something like the following:
$('#btn').click(function(e){
$.ajax({
method: "POST",
url: "some.php",
data: $('#pizzacrustformid').serializeArray()
})
.done(function(data) {
alert(data); //should be "Hello world"
$('#pizzacrust, #btn').fadeOut('slow', function(){
$('#pizzasize, #btn2').fadeIn('slow');
});
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "complete" );
});
});
What is happening here is is on submit, your form data will pass over to the submit.php page, and it will generate the PHP code. That code will hit the done function (if it's successful), call an alert, then fade out to the next section.
That should get you on the right path. I would create another branch and strip out all of the forms and work on getting this done before continuing.
Also, I would set this all up in one single form and show the first section, do some validation, and then move on to the next section before finally submitting eveyrthing you need.
Hope this helps.
I recommend you do requests via ajax, here a tutorial and examples:
http://www.w3schools.com/jquery/jquery_ajax_get_post.asp
delete all jquery functions about submit
create a file called blu.php with the php code
add the jquery code in index.php
with this you only do once request at the end. I hope this helps you.
<?php echo 'tus datos son: ';
echo ' '.$_POST["data1"];
echo ' '.$_POST["data2"];
echo ' '.$_POST["data3"]; ?>
<script>
$(document).ready(function(){
$("#btn5").click(function(){
var pizzacrust= $('input[name="pizzacrust"]:checked').val();
var pizzasize= $('input[name="pizzasize"]:checked').val();
var pizzatoppings= $('input[name="pizzatoppings"]:checked').val();
$.post("blu.php",
{
data1: pizzacrust,
data2: pizzasize,
data3: pizzatoppings
},
function(data,status){
alert("Data: " + data);
});
});
});
</script>
I think you need to using click() func call ajax, dont use on() submit. Submit action makes current page will refresh. I will review your code later, but you should to try this solution above.

Post a form and put results in a div

I can't get my form to submit correctly using jquery. I have tried using the tips here: https://api.jquery.com/jQuery.post/ and http://api.jquery.com/submit/ but can't figure out what I am missing to have the form submit and return the results to the div instead of reloading the page. It is supposed to call an external php page to get processed and return the results.
<script>
// On click "button.submit"
$("input[id^=formsubmit]").submit(function( event ) {
// Stop form from submitting normally
event.preventDefault();
$.get( "functions.php?do=adminmenu", function( data ) {
$( \".contentarea\" ).html( data );
});
return false;
});
</script>
<form action="#" name="submitForm">
<input type="textbox" name="test">
<input type="submit" value="Save Settings" id="formsubmit">
</form>
<div class="contentarea"></div>
Try to wrap your code inside DOM ready handler $(function() {...}); to make sure your DOM elements have been properly loaded.
Also, you can remove return false here as well as there's no need to escape the $(".contentarea" ) using \. So try this code:
$(function () {
$("input[id^=formsubmit]").submit(function (event) {
// Stop form from submitting normally
event.preventDefault();
$.get("functions.php?do=adminmenu", function (data) {
$(".contentarea").html(data);
});
});
});
The problem is that you're not passing the data to the php file. Furthermore you have not specified the type of data handled. And if you want to use POST you should use $.post(); and not $.get();
Try it like this: I've changed the function from .get to .post, added the data you want to send to the php file and specified a data type.
<script>
$(document).ready(function () {
$('#formsubmit').click(function () {
$.post("functions.php?do=adminmenu",{test_val:$('#test_input').value},function (data) {
$('.contentarea').html(data);
},"json");
});
});
</script>
<input id="test_input" type="text" value="">
<input id="formsubmit" type="submit" value="Save Settings">
<div class="contentarea"></div>
Last point: What is the php file returning? Is it only a string or what? Depending on this you need to modify the function writing the returned content in the '.contentarea'.
And by the way: When submitting the information via AJAX you don't need a form around it, as it just creates the need to escape the default behaviour when submitting a form.
If it still doesn't work let me know, I'll help you.

javascript:void(0) in jquery

I have an jsp page with html and js like below. Now I want to keep the js function test() to another js file. I m trying to write that using jquery.
<div class="class1">
<a href="javascript:void(0)" onclick="test();" id="add_another" ><b>Add another user</b></a>
</div>
JS function
function test(){
alert("I am here");
//other code
}
I tried to write like this
$(function() {
$('#add_another').click(test);
});
But its not working. I am not sure if its because its having href="javascript:void(0)"
When the user clicks Add Another User link, it show display another div. That is the test() doing. But the alert itself is not coming.
Can somebody please help me in this?
To replicate javascript:void(0) you can use event.preventDefault() in js like this.
$(function () {
$('#add_another').click(function (e) {
e.preventDefault();
test();
});
});

Categories