post multi forms with Ajax and php same page - php

i have an easy ajax script which sending data to php file with no problem
index.php
<script type="text/javascript">
$(function() {
$('#submit').click(function() {
$('#container').append('<img src="img/loading.gif" alt="Currently Loading" id="loading" />');
var name = $('#name').val();
var email = $('#email').val();
var comments = $('#comments').val();
$.ajax({
url: 'submit_to_db.php',
type: 'POST',
data: 'name=' + name + '&email=' + email + '&comments=' + comments,
success: function(result) {
$('#response').remove();
$('#container').append('<p id="response">' + result + '</p>');
$('#loading').fadeOut(500, function() {
$(this).remove();
});
}
});
return false;
});
});
</script>
with in the same page i have another form which needed to be submitted so i don't know how to do it without no conflict with in this function i already use ?
btw it won't processed with in the same php file it will use another file

I don't see what's the point. What kind of problems do you have in submitting more than one form? You're referencing elements by id.
Note that you really should change your code to intercept the $('#form-id').submit(), not the $('#submit').click event, because a form could be submitted also with enter key, or via javascript callbacks, not only using the submit button.
In your code what is the problem in doing something like this
$(function() {
$('#other-form-id').submit(function() {
$.ajax({
url: 'other-php-script.php',
type: 'POST',
data: 'name=' + name + '&email=' + email + '&comments=' + comments,
success: function(result) {
// your success handling
}
});
return false;
});
});
This is going to work as far as Dom ID are unique across the document.
BTW I strongly advise you to use this wonderful plugin to manage ajax form to keep your js code cleaner and simple. With that your code could be rewritten as:
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#myForm').ajaxForm(function() {
$('#response').remove();
$('#container').append('<p id="response">' + result + '</p>');
$('#loading').fadeOut(500, function() {
$(this).remove();
});
});
});

Related

JQuery + ajax + json fail to show response

I'm trying to do something like user click on button, it sends request to json, and i want it shows the response of json, but i have some errors that i can't figure it out how to solve it.
HTML:
<a class="backLink" id="target_button" onclick="insertText('target_', 'AA', 'NN')"><div class="fa fa-external-link"></div>Show</a>
JS + ajax:
<script type="text/javascript">
function insertText(elemID, text, text2) {
$.ajax({
url: "https://myserver.com/jsons.php?request=getTargets&tar="text"&bar="text2"",
beforeSend: function (xhr) {
xhr.overrideMimeType("text/plain; charset=x-user-defined");
}
})
.done(function (data) {
if (console && console.log) {
console.log(data);
var getValue = $("#" + elemID).val() == "" ? data : "";
$("#" + elemID).val(getValue);
}
});
}
</script>
I'm not sure if im doing it in the better way.
It is something simple. User click on button, call the function with that parameters, make a request to json , receive answer and display it on the elemID.
Thanks
EDIT:
changes i made
<script>
console.log('called');
function insertText(elemID, product, country) {
"use strict";
console.log('called2');
$.ajax({
url: 'https://myserver.com/jsons.php?request=Targ&country=" + country + "&product=" + product +".",
beforeSend: function (xhr) {
xhr.overrideMimeType("text/plain; charset=x-user-defined");
}
})
.done(function (data) {
if (console && console.log) {
console.log(data);
}
});
console.log('called3');
}
console.log('called4');
</script>
result on console:
called
called4
it looks like i can't enter on function
Write console.log('called'); in your insertText() function right before the line contains $.ajax({
So you can see the function is called on click or not.
If the Console tab of the Developer Tools throws JavaScript errors, this could brake further JavaScript execution too.
Replace your double quotes with single quote.
URL should be
url: 'https://myserver.com/jsons.php?request=getTargets&tar='+ text +'&bar='+ text2
How I did it:
<script type="text/javascript">
function insertText(elemID, p, c) {
var server = window.location.hostname;
$.ajax({
url: "https://" + server + "/jsons.php?request=Target&c=" + c + "&p=" + p +"",
beforeSend: function (xhr) {
xhr.overrideMimeType("text/plain; charset=x-user-defined");
}
})
.done(function (data) {
console.log(data)
var tmp = data.replace('"',"");
var tmp2 = tmp.trim();
var getValue = $("#" + elemID).val() == "" ? tmp2 : "";
$("#" + elemID).val(getValue);
});
}
</script>
HTML:
<a id="t_button" onclick="insertText('t_d', '<?php $c ?>', '<?php $p ?>');" > show</a>
Hope it helps someone another !

Form loaded via ajax wont append data to parent window

So I am basically creating a Restaurant Menu editor for their website. The issue I am having is when the click a category named Brunch, I load the file edit_cat.php via ajax onto the page. All data is passed correctly, but on success of the form being filled out I would like to post a success message on the parent window and am having no luck. Coincidentally, upon success the alert(data) does popup with the response.
edit_cat.php both handles the form submission and is the form
$(document).ready(function(){
$('.editBtn').on('click', function(e) {
e.preventDefault();
var $this = $(this),
id = $this.data('id'),
type = $this.data('type');
if (type == 'cat') {
data = "&cat=" + id;
$.ajax({
data: data,
type: 'POST',
url: 'edit_cat.php',
success: function(data) {
$('#contentLeft').html(data);
}
});
}
});
$('#contentLeft').on('click', 'input[type="submit"]', function(e) {
e.preventDefault();
var $this = $(this),
frm = $('#edit-cat-frm'),
id = $('form').data('id'),
name = $(frm).find('input[name="name"]').val(),
desc = $(frm).find('textarea[name="desc"]').val(),
send = $(frm).find('input[name="submit"]').val();
data = "&cat=" + id + "&name=" + name + "&desc=" + desc + "&submit=" + send;
$.ajax({
data: data,
type: 'POST',
url: 'edit_cat.php',
success: function(data) {
window.parent.$('.left-container-head').innerHtml(data);
}
});
});
});
Can you please try this as simply,
$('.left-container-head').html(data);
Try this:
$(".left-container-head", window.parent.document).html(data);

Submit form after success return after ajax call

I validate my form with both client and sever side scripting. First I validate it with jQuery then it goes to php validation and if it returns success or something like that I want to submit the form but some how the condition does not work. However in html err_msg I get success text but its not working.
jQuery.validator.setDefaults({
submitHandler: function () {
var name = $na('#inf_field_FirstName').val();
var password = $na('#inf_field_Password').val();
var cpass = $na('#cpass').val();
var email = $na('#inf_field_Email').val();
var age = $na('#inf_custom_Age').val();
$na.ajax({
type: "POST",
url: '<?php bloginfo('
template_url ')?>/user_create.php',
data: 'name=' + name + '&email=' + email + '&password=' + password + '&cpass=' + cpass + '&age=' + age,
cache: false,
success: function (result) {
jQuery('.err_msg').html(result);
if (jQuery('.err_msg').html == 'sucess') {
jQuery("#inform").submit();
} else {
alert('error');
}
}
});
}
});
use jQuery("#inform")[0].submit();
otherwise, if u have submit button in your form just trigger that button
jQuery("#submit_btn_id").trigger('click')

jQuery, ajax multiple checkboxes into $_POST array

I'm trying to send $_POST data to another page to add sessions for a simple shopping cart.
I have a multiple forms within a PHP while loop each with multiple checkboxes, everything works apart from the checkboxes.
My question is how do I change this piece of code to change "item_extras" into an array?
if(this.checked) item_extras = $(this).val();
I have tried the following but, this just creates one line with all the values instead of another row within the array. If this is too confusing I could create a sample if it helps.
if(this.checked) item_extras += $(this).val();
$('form[id^="add_item_form"]').on('submit', function(){
//alert("On Click Works");
event.preventDefault();
addItem($(this));
});
function addItem(ele) {
//alert("I'm in the addItem Function");
var item_id = ele.parent().parent().find("input[name=item_id]").val(); // get item id
var item_name = ele.parent().parent().find("input[name=item_name]").val(); // get item name
var item_options = ele.parent().parent().find('#options').val(); // get selected option
var item_extras = "";
$item_extras = ele.parent().parent().find('input[name^="extra"]'); // find all extras
$item_extras.each(function() {
if(this.checked) item_extras = $(this).val(); // how do i make this into an array???
});
alert("BEFORE AJAX");
var dataString = 'item_id=' + item_id + '&item_name=' + item_name + '&item_options=' + item_options + '&item_extras[]=' + item_extras;
alert(dataString);
$.ajax({
type: "POST",
cache: false,
url: "includes/cart.php",
data: dataString,
success: function () {
$.ajax({
url: 'includes/cart.php',
success: function(data) {
$('#cart').html(data);
alert("AJAX SUCCESS");
}
});
}
});
return false;
}
you can use serialize method. Form.serialize()
$( "form" ).on( "submit", function( event ) {
event.preventDefault();
var data = $(this).serialize();
});

Rebind dymanically created forms after jQuery ajax response

I'm kinda new to jQuery but understand it for the most part. My problem is that when my ajax call which refreshes the entire div is done, all my dynamically created forms don't work. If you try and submit them, the event doens't work properly and just tries to do a normal form submit. I have all the other items such as links bound using the .live() which seem to work great. Just the form dies.
How do I rebind the dynamically created forms after the ajax call? They all have id of formname_id. I tried to use bind but it doesn't work as below. Any help is appreciated.
Here is the code
jQuery(document).ready(function(){
jQuery("form[id^='commentform_']").each(function(){
var id = parseInt(this.id.replace("commentform_", ""));
jQuery(this).bind('submit', function(e) {
var action = jQuery('#action_' + id).attr('value');
var act_id = ('1');
jQuery.ajax({
type: "POST",
url: "ajax/modify.php",
data: "action="+ action +"& act_id="+ act_id,
success: function(response){
jQuery('#CommentsContainer_' + id).html(response);
jQuery('#commentform_' + id)[0].reset();
}
});
return false;
});
});
});
Try doing something like this:
jQuery("form[id^='commentform_']").live('submit',function(){
var id = parseInt(this.id.replace("commentform_", ""));
var action = jQuery('#action_' + id).attr('value');
var act_id = ('1');
jQuery.ajax({
type: "POST",
url: "ajax/modify.php",
data: {"action": action, "act_id": act_id},
success: function(response){
jQuery('#CommentsContainer_' + id).html(response);
jQuery('#commentform_' + id)[0].reset();
}
});
return false;
});
No need to loop over the forms to bind to them. If you can use delegate instead of live do so.
Why don't you over-ride the normal form submit:
function addNewitem() {
$('#new_item_form').submit(function() {
$.get("includes/ItemEdit.php", {
newItem: true
},
function(msg) {
isNewItem = true;
$("#new_item").hide();
$('#item_list').hide();
$("#item_edit").html( msg );
$("#item_edit").show();
editActiveEvent();
});
return false;
});
}
Don't forget to return false. or do a .preventDefault
I have gotten this to work adding the event in the function call and using event.preventDefault(); BUT of course only in FF. Doesn't work in IE7..
jQuery("form[id^='commentform_']").live('submit',function(event){
var id = parseInt(this.id.replace("commentform_", ""));
var action = jQuery('#action_' + id).attr('value');
var act_id = ('1');
jQuery.ajax({
type: "POST",
url: "ajax/modify.php",
data: {"action": action, "act_id": act_id},
success: function(response){
jQuery('#CommentsContainer_' + id).html(response);
jQuery('#commentform_' + id)[0].reset();
}
});
event.preventDefault();});
But IE7 still tries to sumbit the action. arrgggh.. Anything I'm doing wrong??

Categories