jquery ajax not submitting - javascript

I have this code:
<script>
$(document).ready(function() {
$("#edit-my-username").click(function() {
$("#my-username").html('<input type="text" id="new-username" value="<?php echo $my_username; ?>"> <button class="my-button small-btn" id="submit-my-username">Submit</button>');
});
$("#submit-my-username").click(function() {
var user = "<?php echo $userid; ?>";
var edit_field = "username";
var edit_content = $("#new-username").val();
if(edit_content !== ''){
$.ajax({
type: "POST",
url: "edit-user.php",
data: {user: user, field: edit_field, content: edit_content},
cache: false,
success: function(html){
$("#my-username").html(html);
}
});
}return false;
});
});
</script>
I can't figure out why it doesn't submit. Firebug see's no XHR when the button is clicked. I'm not exactly confident with JS/jQ.. where am I going wrong?

Since you are dynamically adding #submit-my-username the click handler is not binded on page load.
$("#submit-my-username").click(function() {
Change the click handler to following
$("body").on( "click", "#submit-my-username", function() {

When you add html via javascript, in your case jquery, the click event (and any other trigger events) do not works.
You have to use on event, or live event, but the last one is deprecated.
For example:
$("#submit-my-username").live('click'. function()
$("#submit-my-username").on('click', function()

When page load,jquery ready funciton executed.The section 'Submit' does not exist,so '$("#submit-my-username").click(function() {}' script not works.
I think you should add onclick event in 'Submit' distinctly.
such as :
<button class="my-button small-btn" id="submit-my-username" onclick='func()'>Submit</button>

In your case, you should use .live() method, however it is now deprecated. instead of that you can use .on()
$("#my-username").on('click', '#submit-my-username', function(event) {}

Sorry for mis-interpreting your question.Below code can be user to submit form using jquery.
$("form").submit(function(){
//your code
});
Hope this is the answer to your question.

Related

Button and AJAX not responding

Im working on trying to get a button to run a php script with AJAX. To be clear I am really new to javaScript and PHP so my code might be completely wrong. I think that the problem is in my button click code not so much the ajax code. Any help is great
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(".submit").click(function myCall() {
var subdata = $("#form").serializeArray();
var request = $.ajax({
url: "construct_new.php",
type: "GET",
data: subdata
});
return false;
});
</script>
<div>
<form id="form">
Name of Product: <input type="text" name="productName" value="Enter Here">
<input type="button" name="submit" value="Submit" class="submit">
</form>
</div>
You need a DOM ready wrapper around the jQuery because it executes before the element exists (or is rendered by the browser).
You can use either $(function(){ }) or $(document).ready(function(){ });.
$(function(){
$(".submit").click(function myCall() {
var subdata = $("#form").serializeArray();
var request = $.ajax({
url: "construct_new.php",
type: "GET",
data: subdata
});
return false;
});
});
In this case, you don't need serializeArray() but simply serialize().
There is no success or complete function defined and so you wouldn't see anything when submitting this, unless of course you watch the developer console/net tab.
Also, using a form's submit event is preferred to the submit button's click event.
$(function(){
$("#form").submit(function myCall() {
var subdata = $(this).serialize();
var request = $.ajax({
url: "construct_new.php",
type: "GET",
data: subdata,
success : function(response){
console.log("success!");
}
});
return false;
});
});
Put your jQuery inside a document ready like this, and prevent the default action (to submit the form):
<script type="text/javascript">
$(document).ready(function(){
$(".submit").click(function(e) {
e.preventDefault();
var subdata = $("#form").serializeArray();
$.get("construct_new.php",{data: subdata}, function(){
console.log(data); // whatever returned by php
});
});
});
</script>
Document ready makes sure page has finished loading everything. e.preventDefault() stops the default action (for a form, submission, for an a tag, following the link).

How do i submit a hidden form using ajax when the page loads?

How can i submit a hidden form to php using ajax when the page loads?
I have a form with one hidden value which i want to submit without refreshing the page or any response message from the server. How can implement this in ajax? This is my form. I also have another form in the same page.
<form id = "ID_form" action = "validate.php" method = "post">
<input type = "hidden" name = "task_id" id = "task_id" value = <?php echo $_GET['task_id'];?>>
</form>
similar to Zafar's answer using jQuery
actually one of the examples on the jquery site https://api.jquery.com/jquery.post/
$(document).ready(function() {
$.post("validate.php", $("#ID_form").serialize());
});
you can .done(), .fail(), and .always() if you want to do anything with the response which you said you did not want.
in pure javascript
body.onload = function() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","validate.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("task_id=" + document.getElementById("task_id").value);
};
I think you have doubts invoking ajax submit at page load. Try doing this -
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
"url": "validate.php",
"type": "post"
"data": {"task_id": $("#task_id").val();},
"success": function(){
// do some action here
}
})
})
</script>
If you're using jQuery you should be able to get the form and then call submit() on it.
E.g.:
var $idForm = $('#ID_form');
$idForm.submit();
Simple solution - jQuery AJAX post the value as others have suggested, but embed the PHP value directly. If you have multiple forms, you can add more key:value pairs as needed. Add a success/error handler if needed.
<script type="text/javascript">
$(document).ready(function(){
$.post( "validate.php", { task_id: "<?=$_GET['task_id']?>" } );
})
</script>
As others have said, no need for a form if you want to send the data in the background.
validate.php
<?php
$task_id = $_POST['task_id'];
//perform tasks//
$send = ['received:' => $task_id]; //json format//
echo json_encode($send);
JQuery/AJAX:
$(function() { //execute code when DOM is ready (page load)//
var $task = $("#task_id").val(); //store hidden value//
$.ajax({
url: "validate.php", //location to send data//
type: "post",
data: {task_id: $task},
dataType: "json", //specify json format//
success: function(data){
console.log(data.received); //use data received from PHP//
}
});
});
HTML:
<input type="hidden" name="task_id" id="task_id" value=<?= $_GET['task_id'] ?>>

CodeIgniter Javascript form submission

I would first want to say that I am very new to javascript and jQuery.
Its a very silly and simple problem I suppose, and I am aware there are plenty of questions on this, and I did try all of them. Though I cant seem to solve my problem.
I have an input field and a submit button. On clicking submit I would like to save the content of the input filed into the database, and continue to remain in the same page with content on page as is.
My Javascript code is as follows:
<script type="text/javascript">
$(document).ready(function()
{
$('#submit').submit(function(e)
{
e.preventDefault();
var msg = $('#uname').val();
$.post("c_test/test_submit", {uname: msg}, function(r) {
console.log(r);
});
});
});
</script>
And my html code as follows ( I use codeigniter):
$this->load->helper('form');
echo form_open();
$data =array ('name'=>'uname','id'=>'uname');
echo form_input($data) . '<br />';
$data=array('name'=>'submit','id'=>'submit','value'=>'Submit');
echo form_submit($data);
echo form_close();
I would be very grateful if anyone could point out my stupidity. Thanks!
You are using
$('#submit').submit(function(e){ ... });
In this case submit is the button/input's id and it has no such an event like submit, instead you can use click event, like
$('#submit').click(function(e){ ... });
or
$('#submit').on('click', function(e){ ... });
Otherwise, you can change the following line
echo form_open();
to
echo form_open('c_test/test_submit', array('id' => 'myform'));
and instead of
$('#submit').click(function(e){ ... });
you can use
$('#myform').submit(function(e){
e.preventDefault();
var msg = $('#uname').val();
var url=$(this).attr('action');
$.post(url, {uname: msg}, function(r) {
console.log(r);
});
});
or
$('#myform').on('submit', function(e){
e.preventDefault();
var msg = $('#uname').val();
var url=$(this).attr('action');
$.post(url, {uname: msg}, function(r) {
console.log(r);
});
});
It seems like the element with an id of "submit" is the submit button for the form - <input type="submit">. However, the submit event is fired by the form, not the submit button, so your bound event handler won't fire.
Either move the "submit" id onto the form, or change the selector when binding the submit event handler:
$('form').submit(function(e) {
// handle submit event from the form
});
You have to do it like this:
<?php
$this->load->helper('form');
echo form_open('', array( 'id' => 'myform'));
..
and:
$('#myform').submit(function(e)
{
e.preventDefault();
var msg = $('#uname').val();
$.post("c_test/test_submit", {uname: msg}, function(r) {
console.log(r);
});
return false;
});
The submit event always goes to the form and not to the form button.
perhaps like this:
$data=array('name'=>'submit','id'=>'submit','value'=>'Submit','onsubmit'=>'return false;');
This will stop the form from posting which will in turn stop the page from refreshing. However, it will require that you submit the form via ajax.

jquery problem with live

I have code like this:
$(".delete").live('click', function() {
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = 'id='+ id ;
$.ajax({
url: "<?php echo site_url('messages/delete') ?>",
type: "POST",
data: string,
cache: false,
success: function(){
commentContainer.slideUp('600', function() {$(this).remove();
$('.messages').fadeOut('2000', function(){$(this).remove();
$('#messages').load("<?php echo site_url('messages/show') ?>", function(){
$(this).fadeIn('2000')
});
});
});
}
});
return false;
});
$('.delete').confirm(
{
msg: 'You are about to delete this message. Are you sure?<br>',
buttons: {
separator: ' - '
}
});//message deleting
When activated for the first time it is working (when I try to delete message, question is asked and if I say yes, message is deleted). When data again shown, when I click delete it is deleting message without asking. What is the problem?
It looks like you'll have to register the confirm plugin after every ajax load as it isn't using live internally.
Easiest way would be to move the code into its own function and call that inside the load callback and on page load.
function deleteConfirmSetup() {
$('.delete').confirm(
{
msg: 'You are about to delete this message. Are you sure?<br>',
buttons: {
separator: ' - '
}
});//message deleting
}
$(".delete").live('click', function() {
$.ajax({
url: "<?php echo site_url('messages/delete') ?>",
type: "POST",
data: string,
cache: false,
success: function(){
commentContainer.slideUp('600', function() {$(this).remove();
$('.messages').fadeOut('2000', function(){$(this).remove();
$('#messages').load("<?php echo site_url('messages/show') ?>", function(){
$(this).fadeIn('2000');
deleteConfirmSetup(); // Add function call here
});
});
});
}
});
return false;
});
deleteConfirmSetup(); // Also call function here to setup initially
Clearly the "confirm" plugin doesn't operate with live and instead is using bind.
When the element is added, it doesn't have the confirmation bindings but does have the live ones, so it'll just delete.
You could attempt to re-call the confirm plugin in your success function after the new content is loaded, modify the plugin, do it yourself manually, or find a new plugin that's a bit better thought-out.
I haven't used the confirm plugin, but a slightly irritating hack to make this work as you want might be to do this:
var bindBackup = jQuery.fn.bind;
jQuery.fn.bind = jQuery.fn.live;
before you run .confirm(). Then just restore it afterwards:
jQuery.fn.bind = bindBackup;
I haven't tried it, but the live function doesn't implement bind in it's source, so I don't see a reason why it won't work.

using jquery to make ajax call and update element on form submit

Here is my html form
<div id=create>
<form action=index.php method=get id=createform>
<input type=text name=urlbox class=urlbox>
<input type=submit id=createurl class=button value=go>
</form>
</div>
<div id=box>
<input type=text id=generated value="your url will appear here">
</div>
Here is the javascript im trying to use to accomplish this;
$(function () {
$("#createurl").click(function () {
var urlbox = $(".urlbox").val();
var dataString = 'url=' + urlbox;
if (urlbox == '') {
alert('Must Enter a URL');
}else{
$("#generated").html('one moment...');
$.ajax({
type: "GET",
url: "api-create.php",
data: dataString,
cache: false,
success: function (html) {
$("#generated").prepend(html);
}
});
}return false;
});
});
when i click the submit button, nothing happens, no errors, and the return data from api-create.php isnt shown.
the idea is that the new data from that php file will replace the value of the textbox in the #box div.
i am using google's jquery, and the php file works when manually doing the get request, so ive narrowed it down to this
Because you're binding to the submit click instead of the form's submit.. try this instead:
$('#createForm').submit(function() {
// your function stuff...
return false; // don't submit the form
});
Dan's answer should fix it.
However, if #createurl is not a submit/input button, and is a link styled with css etc., you can do this:
$('#createurl').click(function () {
$('#createForm').submit();
});
$('#createForm').submit(function () {
// all your function calls upon submit
});
There is great jQuery plugin called jQuery Form Plugin. All you have to do is just:
$('#createform').ajaxForm(
target: '#generated'
});

Categories