Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 15 of 15
  1. #1
    New Coder
    Join Date
    Aug 2013
    Posts
    36
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Javascript for Ajax not working properly

    Hi, I'm adding Ajax to my forms which have javascript validation on them. I created a function that runs if validation passes which is suppose to trigger the php submit page so the values in the form get inserted in the mysql database.

    Here's the function

    Code:
    function SubmitAddToAddress()
    {
    	var ajaxObject = null;
    	
    	if(window.XMLHttpRequest)
    		ajaxObject = new XMLHttpRequest();
    	else if(window.ActiveXObject)
    		ajaxObject = new ActiveXObject("Microsoft.XMLHTTP");
    		
    	if(ajaxObject != null)
    	{
    		 var tocompany = document.getElementById("tocompany").value;
    		 var tosuite = document.getElementById("tosuite").value;
    		 var toaddress = document.getElementById("toaddress").value;
    		 var tocity = document.getElementById("tocity").value;
    		 var toprovince = document.getElementById("toprovince").value;
    		 var topostalcode = document.getElementById("topostalcode").value;
    		 var params = "ToComany=" + tocompany + "&ToSuite=" + tosuite + "&ToAddress=" + toaddress + "&ToCity=" + tocity + "&ToProvince=" + toprovince + "&ToPostalCode=" + topostalcode;
    
    		 alert(params)
    		 ajaxObject.open("POST", "addtoaddress.php", true);
    		 ajaxObject.setRequestHeader("Content-type", "application/x-www.form-urlencoded");
    		 ajaxObject.send(params);
    	}
    	else
    		alert("You do not have a compatible browser for this action");
    }
    When the code runs and gets to the "alert(params)" section it does alert me and shows the correct values in the form and a new record is being added to the database however all the values are blank not null. So its writing to each column in the database but not writing the value is shows me on the alert.

    If anyone has any ideas that would be great. The form and submit php page does work good, if I use the form as a normal php form it inserts correctly in the database.

    Thanks

  • #2
    Regular Coder
    Join Date
    Jan 2013
    Location
    Germany
    Posts
    578
    Thanks
    4
    Thanked 77 Times in 77 Posts
    The value of an empty input field is a blank string. Why would it be wrong? This becomes even more clear when you realize that what you are sending is a string (params). Literally anything you write in there will be turned into a string.

  • #3
    New Coder
    Join Date
    Aug 2013
    Posts
    36
    Thanks
    6
    Thanked 0 Times in 0 Posts
    yeah but the input fields aren't empty, I'm typing something in them, I hit submit and an alert popups up showing me what I typed in each field but those values aren't added to the database, the record is empty.

  • #4
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    26,588
    Thanks
    80
    Thanked 4,498 Times in 4,462 Posts
    Ummm....are you SURE the params are all correct??
    Code:
    var params = "ToComany=" + tocompany + ...
    Shouldn't that be ToCompany

    But along with that...

    You really should be encoding all those values!
    Code:
    var tocompany = encodeURIComponent( document.getElementById("tocompany").value );
    var tosuite = encodeURIComponent( document.getElementById("tosuite").value );
    ... etc. ...
    Anyway, I don't think the problem is in the JS code (except maybe for "ToComany").

    Time to more thoroughly debug the PHP code.

    What you could do: Have the PHP code echo the SQL statement it is going to use. And then have your AJAX code read that from the AJAX ResponseText and echo it onto the browser screen.

    One easy way to do that: Change from an asynchronous request to synchronous, thus:
    Code:
    		 ajaxObject.open("POST", "addtoaddress.php", false);
    		 ajaxObject.setRequestHeader("Content-type", "application/x-www.form-urlencoded");
    		 ajaxObject.send(params);
                     alert( ajaxObject.responseText );
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • Users who have thanked Old Pedant for this post:

    robsworld78 (08-24-2013)

  • #5
    New Coder
    Join Date
    Aug 2013
    Posts
    36
    Thanks
    6
    Thanked 0 Times in 0 Posts
    Thanks for that! First the typo wasn't really a typo, I was playing and forgot to put it back when posting. Second I did what you suggested which is a cool technique to see whats happening with the php file.

    It showed me the script file that holds the javascript and it showed the SQL insert statement which has all blank values. The php file works great when I submit the form normally, here's what it looks like.

    PHP Code:
    <script type="text/javascript" src="editmyinfojavascript.js"></script>
    <?php
        session_start
    ();

        if( empty(
    $_SESSION['username']) )
        {
            
    header('location: login.php');
            
            exit;
        }
        
        
    mysql_connect("localhost""root""") or die(mysql_error());
        
    mysql_select_db("a2b") or die(mysql_error());     

        
    $search $_SESSION['ClientID'];

    $ToAddress $_POST['ToAddress'];
    $ToSuite $_POST['ToSuite'];
    $ToCity $_POST['ToCity'];
    $ToProvince $_POST['ToProvince'];
    $ToPostalCode $_POST['ToPostalCode'];
    $ToCompany $_POST['ToCompany'];

        
    $sql "INSERT INTO clienttolocations (ClientID, ToCompany, ToSuite, ToAddress, ToCity, ToProvince, ToPostalCode) VALUES ('$search', '$ToCompany', '$ToSuite', '$ToAddress', '$ToCity', '$ToProvince', '$ToPostalCode')";

        if (!
    mysql_query($sql)) {
        die(
    'Error: ' mysql_error());
        }

    echo 
    $sql    
     
    //  header('location: editmyinfo.php#tabs-2');

    ?>
    The clientID is the only field being added to the database and that popup from your method also showed that it would be inserted. I added the script file to the php file just in case, of course it didn't help. I'm guessing thats why it showed up in the popup.

  • #6
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    26,588
    Thanks
    80
    Thanked 4,498 Times in 4,462 Posts
    Yes, there was no reason to put the script file into your PHP page. In fact, a bad idea for an AJAX responder.

    Quite frankly, I'm mystified.

    I have done this exact same thing many times in the past and it has worked.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #7
    New Coder
    Join Date
    Aug 2013
    Posts
    36
    Thanks
    6
    Thanked 0 Times in 0 Posts
    Ok, I'll remove that link.

    Are you allowed to use the same variable name in different functions?

    I've tried everything and nothing seems to work.

  • #8
    New Coder
    Join Date
    Aug 2013
    Posts
    36
    Thanks
    6
    Thanked 0 Times in 0 Posts
    I should also mention all the entries going in the database are empty and not null. The php is adding "" to the record, in MySQL workbench the word null disappears.

    This is very frustrating, are there any other techniques that would work in my case?

    I found a really nice piece of code which works for any and all forms by reusing it. The nice thing with it beside having to re-write it for every form is it processes the form normally if ajax isn't available and uses the ajax if it can.

    However the problem with it is it uses a form as it should be built, as in having the button inside the form tags and all my javascript validation requires the button to be outside the tag and use a function to call the processing section if validation passes.

    This code all you do is add a class to the form and a link to a file javascript file. Because I'm not calling a function where i should be in my validation function it processes the form reguardless.

    Is it possible to turn the following code into a function so I can call it that way instead of calling it with a class on the form?

    Code:
    $('form.ajax').on('submit', function() {
    	var that = $(this),
    		url = that.attr('action'),
    		type = that.attr('method'),
    		data = {};
    		
    	that.find('[name]').each(function(index, value) {
            var that = $(this),
    			name = that.attr('name'),
    			value = that.val();
    			
    		data[name] = value;
        });	
    	
    	$.ajax({
    		url: url,
    		type: type,
    		data: data,
    		success: function(response) {
    			console.log(response);	
    		}		
    	});
    	
    	return false;	
    });
    I've tried many variations but can't get it to work. Here's how it currently submits with a form. Pretty simple and very cool. All I had to do was add the class to the form tag and a link to the above piece of code.

    Code:
    <form action="addtoaddress.php" method="post" class="ajax">
    
    <input onclick="validateToAddressForm()" type="submit" value="Add New Ship To Address"/>
    </form>
    My function for validating is called "validateToAddressForm" it has an if else statement and if validation passes it calls the function "SubmitAddToAddress" which I originally posted and if that worked as it should I would be good. Can the code I just posted be re-written into a function I can call normally?

  • #9
    Senior Coder Arbitrator's Avatar
    Join Date
    Mar 2006
    Location
    Splendora, Texas, United States of America
    Posts
    3,338
    Thanks
    29
    Thanked 282 Times in 276 Posts
    Quote Originally Posted by robsworld78 View Post
    If anyone has any ideas that would be great. The form and submit php page does work good, if I use the form as a normal php form it inserts correctly in the database.
    Maybe the typo in application/x-www.form-urlencoded has something to do with your issue. The correct media type is application/x-www-form-urlencoded.
    For every complex problem, there is an answer that is clear, simple, and wrong.

  • Users who have thanked Arbitrator for this post:

    robsworld78 (08-24-2013)

  • #10
    New Coder
    Join Date
    Aug 2013
    Posts
    36
    Thanks
    6
    Thanked 0 Times in 0 Posts
    lol, ouch, brutal, thank-you!

    Unbelievable, I checked that over and over and over.

    Thanks so much!

  • #11
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    26,588
    Thanks
    80
    Thanked 4,498 Times in 4,462 Posts
    Holy eagle eyes, batman!

    Do you know, I even found that string in my own code and copy/pasted it right under his to compare and make sure it was right...AND STILL missed the typo! I would say I need to get my eyes checked except I really am undergoing treatments on my left eye right now. <grin/>
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #12
    Senior Coder Arbitrator's Avatar
    Join Date
    Mar 2006
    Location
    Splendora, Texas, United States of America
    Posts
    3,338
    Thanks
    29
    Thanked 282 Times in 276 Posts
    Quote Originally Posted by Old Pedant View Post
    Holy eagle eyes, batman!

    Do you know, I even found that string in my own code and copy/pasted it right under his to compare and make sure it was right...AND STILL missed the typo! I would say I need to get my eyes checked except I really am undergoing treatments on my left eye right now. <grin/>
    So you're wearing a pirate eye patch? No wonder.

    Could always try some LASIK surgery while you're at it. I went from 20/40 to 20/15 vision. It'll help you spot those hyphens-turned-periods lol
    For every complex problem, there is an answer that is clear, simple, and wrong.

  • #13
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    26,588
    Thanks
    80
    Thanked 4,498 Times in 4,462 Posts
    My problem is a filmy covering on the retina that has developed thanks to 35 years of diabetes. Trying injections in the eye, but they don't seem to be helping a lot, so next step is surgery. Nope, can't use lasers for this, unfortunately.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #14
    Senior Coder Arbitrator's Avatar
    Join Date
    Mar 2006
    Location
    Splendora, Texas, United States of America
    Posts
    3,338
    Thanks
    29
    Thanked 282 Times in 276 Posts
    Quote Originally Posted by Old Pedant View Post
    My problem is a filmy covering on the retina that has developed thanks to 35 years of diabetes. Trying injections in the eye, but they don't seem to be helping a lot, so next step is surgery. Nope, can't use lasers for this, unfortunately.
    Sounds like macular pucker and a vitrectomy. Best of luck with the surgery.

    (I've had to take an interest in the subject because my mom developed diabetic retinopathy after leaving her diabetes untreated. That and I just took a genetic test at 23andMe stating I had a 48% chance of also developing type 2 diabetes.)

    Anyway, I guess I should stop spamming robsworld78 now lol
    For every complex problem, there is an answer that is clear, simple, and wrong.

  • #15
    New Coder
    Join Date
    Aug 2013
    Posts
    36
    Thanks
    6
    Thanked 0 Times in 0 Posts
    Spam away, heck I even made a new thread for you guys to spam, check it out.

    http://www.codingforums.com/showthre...48#post1354148


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •