Having Issues with ajax submit reloading, the anonymous function is not executing - php

I spent quite a bit of time looking for this and maybe I'm not approaching this correctly, but I'm trying to .submit and .post after clicking a submit. In other instances I have been able to get the ajax submit to work properly without the refresh, but when I do it in this manner it just doesn't work. I'm curious to know why.
Form
<form id="search" action="process.php" method="post">
Name: <input id="search_text" type="text" name="name" />
<input type="submit" value="Submit" />
</form>
Ajax
$('#search').submit(function() {
$.post(
$(this).attr('action'),
$(this).serialize(),
function(data){
$('#page_nav').html(data.html_page_nav);
$('#results').html(data.table_html);
},
"json"
);
return false;
});
This works and it will submit without reloading just fine
Below is where I have the problem.
On the php server side I am sending back html that I want to be able to submit, which the initial search will put into the original html page.
$html_page_nav = "
<ul>
";
for($i=1; $i <= get_query_pages(get_query_count($query), 50); $i++) {
$html_page_nav .= "
<li>
<form id='page_".$i."' action='process.php' method='post'>
<input type='hidden' name='action' value='change_page'/>
<input type='hidden' name='page' value='".$i."'/>
<input type='submit' value='".$i."'>
</form>
</li>
";
}
$html_page_nav .= "
</ul>
";
I try to do the same thing as above, but the submit does not work properly
$(document).ready(function() {
$('#page_1').submit(function() {
console.log("this will not display");
$.post(
$(this).attr('action'),
$(this).serialize(),
function(data){
},
"json"
);
return false;
})
...other jquery
});
This submit will not work properly, the function() will not execute and it will submit like the regular submit and go to the url rather then execute without refreshing the entire page.
Any suggestions or approaches would be much appreciated.
Thanks in advance!

Delegate the submit action to execute on content which will be loaded in future. By default the normal event handlers attached to the content loaded on DOM but not the one which will gets loaded in future, say through Ajax. You can use jQuery "on" function to delegate the action on content which will load in future.
eg.
$('body').on('submit', '#page_1', function() {
// do it here
});

I had a similar problem using ajaxForm n all. I jus used $("#Form").validate();
for it and the page doesnt get refresh

Related

Calling php scripts using ajax

I am making a chat script and an hoping to code it so that when a user submits a message, the script will run chat_new.php and then refresh #cbox. I use the code below to try and accomplish this, but unfortunately it won't reload. Just to rule it out, I tested without any jQuery and chat_new.php executes without problems, so it definitely is my ajax script. In addition, getUpdates() works just fine on it's own. I only have a problem when posting new messages through ajax.
<div id="cbox" align="left">
<script>
$(document).ready(function() {
setInterval(function() {
getUpdates()
}, 2000);
});
function getUpdates() {
$("#cbox").load("/lib/chat_post.php");
}
$("#submitmsg").click(function() {
$.ajax({
type: 'POST',
url: '/lib/chat_new.php',
data: {
submitmsg: 'submitmsg',
usermsg: 'usermsg'
},
success: function() {
getUpdates()
}
});
});
</script>
</div>
<form name="message" method='post' id="cbox_input">
<input name="usermsg" id='usermsg' type="text" size="63" maxlength="255" />
<input name="submitmsg" id='submitmsg' type="submit" />
</form>
Several issues:
Your click handler exists before the element it references and is not inside document.ready. Therefore it can't find the element and never gets bound to it
Once that is fixed you need to prevent the default form submit process. Otherwise page will reload on submit
// put this inside ready()
$("#submitmsg").click(function (event) {
event.preventDefault();
//other code
})
This might be a simple as moving }); from the third line of your script, to just before </script> so that your function and your ajax call are inside $(document).ready(... and therefore only get processed once the DOM has loaded, and all HTML elements are on the page.

jQuery Ajax Call inside of PHP

I'm clearly doing something wrong here, but I can't figure out why the Ajax isn't firing and instead insists upon a page load. The newBatable() fires fine, I just can't seem to get the vote to respect the ajax call.
HTML - not sure how to put html in here as code :/ - I feel dumb.
<form class="form-horizontal" id="batable1" action="vote.php" method="GET">
<div id="success-vote-1"></div>
<input type="radio" name="batableResult" value=" include ()" /> include ()<br/>
<input type="radio" name="batableResult" value="require ()" />require ()<br/>
<input type="radio" name="batableResult" value="both of above" />both of above<br/>
<input type="radio" name="batableResult" value="None of above" />None of above<br/>
<button class="btn btn-primary" onClick="vote(1)">Vote</button>
<input type="hidden" name="batableId" id="batable-id" value="1"/>
</form>
JS - the console display everything I want, the php script processes everything nicely and functions perfectly, it is just it has to load the php in the browser so it's not using AJAX
/***************************************/
function newBatable() {
var batableData = $('#new-batable').serialize();
//console.log(batableData);
$.ajax({
url: "process.php",
data: batableData,
success: function(data){
$('#success-new-batable').html(data);
}
});
}
/***************************************/
function vote(poll_id) {
//console.log(poll_id)
var batableId = "#batable" + poll_id;
//console.log(batableId)
var pollData = $(batableId).serialize();
//console.log(pollData);
$.ajax({
url: "vote.php",
data: pollData,
success: function(data){
var batable_success_id = "#success-vote" + poll_id;
$(batable_success_id).html(data);
}
});
}
The submit button fires the JavaScript and then immediately submits the form.
If you are using onclick, then return false to stop that.
You would be better off using a more modern event binding technique though.
how about attaching a click event via jquery to the button?
$(".btn").on('click', function(e){
e.stopPropagation()
e.preventDefault();
vote(1);
});
this would usually be placed in document .ready jquery in an external file or somewhere near the bottom of your page inside script tags.
Does this help?
Since you're already using jQuery, as SubstanceD, you should use jQuery's on() method and stop the event propagation and prevent the default action (submitting the form).
I also noticed a possible bug in your code. It looks like there is a typo. You have
var batable_success_id = "#success-vote" + poll_id;
and <div id="success-vote-1"></div>. You have a dash after vote in the div's ID while you are concatenating batable_success_id into #success-vote1, for example. So even if the AJAX call is made, it probably won't update your HTML like you're expecting.

ajax post but can't prevent refresh

I have a problem with my page refreshing after ajax posts, I've tried like 6 differing variations and at one point I was getting the proper result but couldn't stop the page from refreshing and after searching the net and around on this site now none of it is working and it's still refreshing...
current code is:
$('#submit_btn').click(function() {
/*event.preventDefault();*/
var curPassword = $("input#curPassword").val();
var newPassword = $("input#newPassword").val();
var new2Password = $("input#new2Password").val();
/*var params = 'curPassword='+ curPassword + '&newPassword=' + newPassword + '&new2Password=' + new2Password; */
var params = {
curPassword: curPassword,
newPassword: newPassword,
new2Password:new2Password
};
$.ajax({
type: "POST",
url: "testAjax.php",
data: params,
success: function(msg){
alert(msg);
}
});
return false;
});
the form is:
<form method="post" action="" name="confirmChange" class="confirmChange">
<label for="curPassword">Current Password:</label>
<input type="password" name="curPassword" id="curPassword" value="" />
<label for="newPassword">New Password:</label>
<input type="password" name="newPassword" id="newPassword" value="" />
<label for="new2Password">Confirm New Password:</label>
<input type="password" name="new2Password" id="new2Password" value="" />
<br />
<input type="button" name="confirmChange" class="confirmChange" id="submit_btn" value="Change" />
Appreciate any help in getting this to work =/
Update:
Took out the other non-directly-related code as it kinda cluttered the question. Also updated code to refelect latest revision.
I changed the ajax url to a simple textAjax.php with a simple echo hello world nothing else, where I'm still getting nothing.
Update 2
Tried changing javascript code to:
$('#submit_btn').click(function() {
alert('Button Clicked');
});
And I'm getting nothing... If that is the form below how is it possible the click function isn't working at all?
You don't need to use the type="submit" for your input. Just use type="button" and call the ajax function on the button's click event.
<input type="button" name="confirmChange" class="confirmChange" id="submit_btn" value="Change">
$('#submit_btn').click(function() {
(ajax code here)
});
preventDefault() would also work, but, in my opinion, why prevent an event from naturally occurring when you can just avoid using the submit button altogether?
Update: I just realised that using the submit would allow users to hit enter to trigger your actions, so perhaps there's also some merit in that. In any case, here's a similar question that contains elaborations into preventDefault().
Update 2: You need to fix your parameters in the ajax function. Use an array instead of trying to build a query string:
var params = {
curPassword: curPassword,
newPassword: newPassword,
new2Password:new2Password
};
Encapsulate your AJAX call within the following code block
$('form.confirmChange').submit(function(event) {
event.preventDefault();
#Rest of your code goes in here
});
preventDefault() will prevent the default action of an event from triggering.
Try this
<script>
function refreshpage(){
(ajax code here)
return false;
}
</script>
<form onsubmit="return refreshpage();">
<input type = "submit" value="submit_btn">
</form>
I think I fixed it by using:
$('#submit_btn').live('click', (function() {
I at least started getting a response when clicking, but I'm not updating or getting any echo's back from the php file but hopefully that'll be easier to debug. :)
I had the same problem. Just like you, I had wrapped my <input> tags inside a <form> tag pair. Even though there was no <submit>, I found that when I clicked my button to trigger the Ajax call, it was refreshing the page - and actually submitting the form to the page.
I ended up removing the <form> tags and this behaviour stopped, but the Ajax still works as expected. I hope this helps anyone else that is experiencing this.
Use a loop to run the ajax call only once.
var i;
for(i=0;i<1;i++){
//ajax code here
}
So, then it will not call again and again..

Load php content with jQuery AJAX

My problem:
I have index.html:
<form action="toload.php" method="post">
Input: <input type="text" name="something" value="" /><br />
<input type="submit" value="Submit!" />
</form>
toload.php is something like:
<?php
echo "Your input was: " . $_POST["something"];
?>
The question is quite simple.
When I press the Submit! button, I would like to dynamically load the content toload.php in index.html without the need of a refresh.
Thanks in advance! please comment for any needed clarification.
EDIT, a more verbose explanation:
I'm not sure I'm being clear (or maybe I'm not understanding the answers do to my lack of technical skills) so I'll give it another go. (re-write)
I have an HTML for with a submit button that sends a variable through POST method.
This variable is used by a PHP file and after a certain process, it inserts and update a MySQL database and echoes out some other stuff.
This is working JUST FINE.
But now I want to improve it by avoiding the page "reload" (going to the .php).
I want the HTHL that comes as an output of my HTML file to be dynamically shown in my HTML page.
Is it more clear now?
something like this with jQuery!:
<form action="toload.php" method="post">
Input: <input type="text" id="something" name="something" value="" /><br />
<input type="submit" value="Submit!" onclick="submitme()" />
<div id="something2"></div>
</form>
and function to submit:
function submitme(){
var tosend=document.getElementById("something").value;
$.ajax({
type: 'POST',
url: 'toload.php',
data: 'something='+tosend,
success: function(msg){
if(msg){
document.getElementById("something2").innerHTML=msg;
}
else{
return;
}
}
});
}
You must use AJAX (XMLHttpRequest) for that - http://www.w3schools.com/XML/xml_http.asp.
(You've said simply - as long loading 100KB of jQuery is not simply IMHO, I suggested pure JavaScript solution)
In your case you can use $.post()DOCS. If you gave your form an id="myForm" then you could load the return data into the form's parent in the callback as follows:
$('#myForm').submit(function(e){
e.preventDefault();
$.post("toload.php", $("#myForm").serialize(), function(data) {
$(this).parent().html(data);
});
});

Simple PHP/AJAX question

Ok, so I am fairly new to webdeveloping, so probably a silly question:
I have this search form which does autocomplete for fooditems (gets values from a database column) and that works. Now when I press the submit button I want to load a block of code that displays the food-items' calories etc (also in the database on the same row as the food-item).
How can I accomplish such a thing. I kno this is a fairly broad question, but what i am really asking is, how can I make a small part of my website reload when pressing the submit button and using the input given in the text field as a parameter of some kind.
I don't need whole answers, just any tips getting to the right path would be greatly appreciated!
here my code for the input and button:
in head
<script type="text/javascript" src="jquery.js"></script>
<script>
function ok(){
$.post("test.php", { name: "John", time: "2pm" }, function(data){ alert("Data Loaded: " + data); });
}
</script>
in body:
<form autocomplete="off">
<p>
Food <label>:</label>
<input type="text" name="food" id="food" / >
</p>
<input type="submit" id="submit" value="Submit" onclick="ok()" />
</form>
or:
head:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.4.js"></script>
<script>
$("input[type='submit']").bind("click", function (event) {
event.preventDefault(); // Stop a form from submitting
$.post("/path/to/call", { /* data? */ }, function (data) {
// Process return data here
});
});
</script>
body:
<form autocomplete="off">
<p>
Food <label>:</label>
<input type="text" name="food" id="food" / >
</p>
<input type="submit" id="submit" value="Submit" />
</form>
jQuery and Ajax.
Change that input to a button
<button id="submit">Save</button>
For this I would do something like:
$("button#submit]").bind("click", function (event) {
event.preventDefault(); // Stop a form from submitting
$.post("/path/to/call", { /* data? */ }, function (data) {
// Process return data here
});
});
You need to first catch the click event .bind("click"). Then initiate an ajax call $.post which you will send data to. This data is received on the server via the POST array.
Like Josh said, jQuery is the way to go here.
You'll want to do 3 things:
Attach a click handler to a button like "onclick='doSomething();'"
In that function,use jQuery to do an async post to a script like
$.post("test.php", { name: "John", time: "2pm" },
function(data){
alert("Data Loaded: " + data);
});
When this comes back, you can do something with that data(instead of the alert above), like $('#listnode').append... which would stick the HTML into your list
This is the general pattern, but you'll have to fit it to your scenario.
It is hard to answer your question from what little you have given us, but I will assume little knowledge.
Your input fields have to be inside a form tag. The form tag includes an action and a method. The method must be "POST" to send the data. The action can be any URL.
You simply have to name the URL of your php script that will handle the results.
It will find the data in $_POST['food'] etc. It has to build the reply page - the whole screen, with the food and data and the search form for the next submit if you want.
If you want to use AJAX to replace part of the screen, then you have a whole nother level of problems. The trick is to replace the content of a div tag with the requested data.

Categories