Sorry but I know something similar to this has already been posted. I have tried every single resource out there and did my research and I still couldn't find out what is wrong with my code. I am using a Ajax Post with php. Everything seems to be working fine except for the fact that the div is not reloading on submit. After I refresh the page what I posted came up. Can someone please tell me what I am doing wrong.
js code:
$(function() {
$('.error').hide();
$('input.text-input').css({
backgroundColor: "#FFFFFF"
});
$('input.text-input').focus(function() {
$(this).css({
backgroundColor: "#C0DDFA"
});
});
$('input.text-input').blur(function() {
$(this).css({
backgroundColor: "#FFFFFF"
});
});
$(".button").click(function() {
// validate and process form
// first hide any error messages
$('.error').hide();
var email = $("input#email").val();
if (email == "") {
$("label#email_error").show();
$("input#email").focus();
return false;
}
var dataString = '&email=' + email;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "../EdinburgCISD/Gorena/Gorena.php",
data: dataString,
success: function(data) {
$("#email").val('');
$("#div").fadeOut(1000);
// Change the content of the message element
$("#div").html(data);
// Fade the element back in
$("#div").fadeIn(1000);
}
});
return false;
});
});
html code:
This is where I have my div.
<div id="div"> <?php \\database select query ?> </div>
I am new to this website sorry if I posted something wrong...
did you get any error in console (firebug/developer tools) ?
otherwise you can try below
check with alert
$.ajax({
type: "POST",
url: "../EdinburgCISD/Gorena/Gorena.php",
data: dataString,
success: function(data) {
alert(data);//what you get here? are you getting "object" in alert? then you need to specify property or mention dataType
$("#email").val('');
$("#div").fadeOut(1000);
// Change the content of the message element
$("#div").html(data);
// Fade the element back in
$("#div").fadeIn(1000);
}
});
modified your code a bit see the comments, you should specify dataType:html (see the ajax part).
$(function() {
$('.error').hide();
$('input.text-input').css({backgroundColor:"#FFFFFF"});
$('input.text-input').focus(function(){
$(this).css({backgroundColor:"#C0DDFA"});
});//focus ends
$('input.text-input').blur(function(){
$(this).css({backgroundColor:"#FFFFFF"});
});//blur ends
$(".button").click(function() {
// validate and process form
// first hide any error messages
$('.error').hide();
var email = $("input#email").val();
if (email == "") {
$("label#email_error").show();
$("input#email").focus();
return false;
}
//var dataString = '&email=' + email; commented out
var dataString = email; //try insted this
//alert (dataString);return false;
$.ajax({
type: "POST",
dataType:'html', //or the appropiate type of data you are getting back
url: "../EdinburgCISD/Gorena/Gorena.php",
data: {email:dataString}, //in the php file do $email = $_POST['email'];
async:false, //not a good practice but you can try with it and without it
success: function(data) {
$("#email").val('');
$("#div").fadeOut(1000);
// Change the content of the message element
$("#div").html(data);
// Fade the element back in
$("#div").fadeIn(1000);
}
}); //ajax ends
return false;
});//click ends
});//document ready ends
update
see this fiddle you will get the idea http://jsfiddle.net/3nigma/LuCQw/ and the delay function is optional i have used it so that the effect is prominent
Related
I'm working on my first php/SQL database project and my goal is to store an array of checkbox values into a database.
On clicking the submit on the checkbox form, i am trying to post the array of checkbox values from my jquery doc to index.php
The success response is my index.php page, which i think is correct, so it all seems correct for me and i'm having a hard time figuring why
My array is generated from a series of .push() calls that update to determine when a box is checked it not and only submitted when i click my form submit, which should trigger the ajax post.
var checkArr =
[
{id: "CB1", val: "checked"},
{id: "CB3", val: ""},
{id: "CB5", val: ""},
{id: "CB4", val: "checked"},
{id: "CB2", val: ""}
];
//SUBMIT CHECKBOX VALUES TO PHP
$('#submitCheck').on('click', function(){
$.ajax({
url: 'index.php',
type: 'POST',
data: {checkArr:checkArr},
cache: false,
success: function(response){
alert("ok");
console.log(response);
}
});
});
Here however when i check to see if the post worked i only return 'is not set'.
if(isset($_POST['checkArr'])){
$arr = $_POST['checkArr'];
echo $arr;
} else {
echo 'Is not set';
}
I know there are many similar questions but i haven't found a solution in any of them unfortunately.
I found one thread that mentioned it might be redirecting me before the post can be processed so i removed the action from my form and nothing changed. I tried to stringify my output as json and still the same problem (even if stringify is redundant because of jquery).
Edit: Full code snippet
var checkArr = [];
//COLOUR ITEMS ON PAGE LOAD
$(document).ready(function(){
var box = $(':checkbox');
if(box.is(':checked')){
box.parents("li").removeClass('incomplete');
box.parents("li").addClass('complete');
} else {
box.parents("li").removeClass('complete');
box.parents("li").addClass('incomplete');
}
});
//DELETE ITEM
$(document).on('click','.delete', function(){
console.log('DELETED');
var id = $(this).attr('id')//get target ID
var item = $(this).closest('li');//targets the li element
//AJAX
$.ajax({
url: 'delete.php',
type: 'POST',
data: { 'id':id },
success: function(response){
if(response == 'ok') {
item.slideUp(500,function(){
item.remove();
});
} else if(response == 'error') {
console.log("error couldn't delete");
} else {
console.log(response);
}
}
});
});
//CREATE ARRAY OF CHECKBOX VALUES
$('#checkform').on('click','.boxcheck', function(){
var check = $(this).prop("checked");
var val = "";
var tempId = $(this).attr('id');
if(check === true){
val = "checked";
console.log(val);
var tempArr = {
"id": tempId,
"val": val
};
checkArr.push(tempArr);
} else if (check === false){
val = "";
console.log(val);
for (var i = checkArr.length - 1; i >= 0; --i) {
if (checkArr[i].id == tempId) {
checkArr[i].id = tempId;
checkArr[i].val = val;
}
}
}
console.log(checkArr);
});
//CHANGE COLOUR OF ITEMS
$(':checkbox').change(function(){
var current = $(this);
if(current.is(':checked')){
current.parents("li").removeClass('incomplete');
current.parents("li").addClass('complete');
} else {
current.parents("li").removeClass('complete');
current.parents("li").addClass('incomplete');
}
});
//SUBMIT CHECKBOX VALUES TO PHP
$('#submitCheck').on('click', function(e){
e.preventDefault();
console.log(checkArr);
$.ajax({
url: 'index.php',
type: 'POST',
data: {checkArr:checkArr},
cache: false,
success: function(response){
alert("ok");
}
});
});
I tried your code and it's working perfectly for me.
Now the only thing I can think of is your url in your ajax request. make sure you are really submitting to index.php.
You can use JSON.stringify() to submit the array from ajax to php
Posting here to update just in case anyone has a similar problem, the code itself was correct(sort of), after a lot of digging and asking around, it turns out the local server i was using, XAMPP, had too small a POST upload limit hence the empty array on the php side, increasing the php.ini upload limit from 2mb to 10mb finally fixed it!
I've got a variable that I want to send to my PHP code that is on top of the code but I keep getting an error and undefined. dTotaal is the variable name and it contains a number. All this code is in the same page, so i am posting to the same page.
$('#emailVerzenden').click(function() {
$.ajax({
url: "content.php",
type: "post",
data: ({
totaal: dTotaal
}),
success: function(msg) {
alert('Data saved: ' + msg);
},
error: function(error) {
alert("couldnt be sent " + error);
}
});
On top of my page I've got this code. I'm not sure if it's correct, I am new at this.
if(isset($_POST['emailVerzenden']))
{
$totaal = $_POST['totaal'];
var_dump($totaal);
}
What I wanted was to put the value of the totaal data in $totaal but that is not working. The data is not being sent. I keep getting the error alert().
In your PHP code, you are checking the presence of a variable to use another. For me it should be:
if(isset($_POST['totaal']))
{
$totaal= $_POST['totaal'];
var_dump($totaal);
}
You are on right track but seperate PHP codes with jQuery codes then you will have full control of processing data asynchronously.
index.php
$('#emailVerzenden').click(function()
{
$.ajax
({
url: "content.php",
type: "post",
data:{totaal: dTotaal},
success: function(msg)
{
alert('Data saved: ' + msg);
},
error: function(error)
{
alert("couldnt be sent ".error);
}
});
And in your php file first check whether $_POST data is set
content.php
if(isset($_POST))
{
$totaal= $_POST['totaal'];
var_dump($totaal);
}
Mention your data which you wanna send in html & give it an ID.
<div id="total"> HERE COMES THE VARIABLE YOU WISH TO SEND </div>
Then pick up the data in that <div> by its ID document.getElementById('total').value like below:
var total=document.getElementById('total').value;
<script> var total=document.getElementById('total').value;
$.post('content.php',
{'total':total},
function(response){
if(response == 'YES'){}
});
</script>
Hope this will resolve your problem. Good Luck!
Kind of look like i didnt use preventDefault() thats why it wasnt working.
$('#emailVerzenden').click(function(e)
{
cms=$('#sCms').val();
templates= $('#templates').val();
onderdelen = $('input:checkbox:checked').map(function() {
return this.value;
}).get();
email = $('#email').val();
e.preventDefault();
$.ajax
({
type: "POST",
url:"test.php",
data:{postEmail : email,postOnderdelen : onderdelen,postCms : cms,postTotaal : postTotaal, postTemplates : templates},
success: function(rs)
{
alert("Data saved:" + rs);
},
error: function(error)
{
alert("couldnt be sent" + error);
}
});
e.preventDefault();
});
Following is my auto suggest code created using jquery
$(document).ready(function(){
$(".input_search").keyup(function()
{
var finder = $(this).val();
var queryString = 'key_wrd='+ finder;
if(finder==''){//check if search is empty}
else
{
$.ajax({
type: "POST",
url: "searcher.php",
data: queryString,
cache: false,
success: function(html)
{
$(".display_found_query_cont").fadeIn();
$(".display_found_query-window").append(html);
}
});
}return false;
});
});
This code closes the suggest window and clears the enterse text
$(document).mouseup(function (e)
{
var search_res_container = $(".display_found_query_cont");
if (!search_res_container.is(e.target)&& search_res_container.has(e.target).length === 0)
{
search_res_container.fadeOut().html();
$(".search_field").val('');
}
});
what do i want to do ?
I want the results displayed to be cleared when the text entered is erased
So how do i do that?
try this code:
if(finder=='')
{
//check if search is empty
$(".display_found_query-window").html('');
}
As per your comment, you want to replace the old content with new result. So just chnage the below line in your ajax success.
$(".display_found_query-window").html(html);
i am having some problems with getting my form to submit. It doesnt seem like anything is being send, is their anything wrong with this code as javascripting isn't my strong point...
$("#send").click(function() {
var complete = true;
$('input#name, input#email, input#subject, textarea#message').each(function() {
if ($(this).val()) {
$(this).css("background","#ffffff").css("color","#5c5c5c");
} else {
$(this).css("background","#d02624").css("color","#ffffff");
complete = false;
}
});
if (complete == true){
var name = $("input#name").val();
var email = $("input#email").val();
var subject = $("input#subject").val();
var message = $("textarea#message").val();
var data = '{"name":"'+name+'","sender":"'+email+'","subject":"'+subject+'","message":"'+message+'"}';
$.ajax({
type:"POST",
url:"contact.php",
data:$.base64.encode(data),
success:function(data){
data = $.parseJSON(data);
if (data.status == "success") {
$.fancybox.close();
}
}
});
}
});
There is also a live version of this in action which can be viewed over at: http://idify.co.uk, thanks :)
You can do it better.
$('form')
.submit(function(event) {
var form = $(this);
$.ajax({
url: '[url here]',
type: 'post',
data: $.base64.encode(form.serialize()), // $.serialize() - it gets all data from your form
dataType: 'json', // function in success callback knows how to parse returned data
success: function(data) {
if (data['status'] == true) {
// your code here
// e.g.
$.fancybox.close();
}
}
});
event.preventDefault();
});
Enjoy! :)
I got an error after submitting:
data is null http://idify.co.uk/javascripts/landing.js Line 25
It looks like the data was sent successfully and there was a response:
{"status":"error","responce":"No token parameter was specified."}
This should help you ensure you've got data in your success callback:
success:function(response) {
if (response) {
var data = $.parseJSON(response);
if (data && data.status == "success") {
$.fancybox.close();
}
} else {
// handle errors
}
}
Haha, thanks guys. I was silly enough not to include the variable that needs to be passed via the php file, got it sorted and it works like a dream, i ended up using the first solution as the form submission one wasnt working for me.
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??