cURL and Ajax form submit problem

I'm having a problem with redirecting a page after posting data from a form using Ajax.

Here is the Ajax I'm using:

submitForm: function(e) {
    	// tracking and variable set up
    	e.preventDefault();
    	var valid = true;
    	this.$('input').removeClass('error');

    	
    	if(this.$('#first_name').val() == 'First Name' || !this.model.set({first_name: this.$('#first_name').val()})){
    		this.$('#first_name').addClass('error');
    		valid = false;
    	}
    	if(this.$('#last_name').val() == 'Last Name' || !this.model.set({last_name: this.$('#last_name').val()})) {
    		this.$('#last_name').addClass('error');
    		valid = false;
    	}
    	if(!this.model.set({day_phone: this.$('#day_phone').val()})) {
    		this.$('#day_phone').addClass('error');
    		valid = false;
    	}
    	if(!this.model.set({email: this.$('#email').val()})) {
    		this.$('#email').addClass('error');
    		valid = false;
    	}

    	var view = this;
    	
    	if(valid) {
			
	   this.$('.primary').after('<img src="loading.gif" />');
            this.$('button').addClass('disabled');
            this.$('button').attr('disabled', 'disabled');
	
    	$.ajax({
		  type: "GET",
		  url: "process.php",
		  data: { first_name: this.$('#first_name').val(), last_name: this.$('#last_name').val(), day_phone: this.$('#day_phone').val(), email: this.$('#email').val(), amount: this.$('#amount').val(),  
            success: function(e){   
                for(var i=0;i<e.length;i++){
                    document.write(e[i]);
                }
            }
			 }
		})
		} else...

Open in new window


I post to process.php and save my data via Curl:

$first_name=$_GET['first_name'];
$last_name=$_GET['last_name'];
$day_phone=$_GET['day_phone'];
$email=$_GET['email'];

$url = 'http://outsidewebsite.com/post.php';
$fields = array(
						'first_name'=>urlencode($first_name),
						'last_name'=>urlencode($last_name),
						'day_phone'=>urlencode($day_phone),
						'email'=>urlencode($email)
						
				);

//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string,'&');

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                 
curl_setopt($ch, CURLOPT_VERBOSE, 1 );                                                                  
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
    'Content-Type: application/json')                                                                       
);                                                                                                                   
$result = curl_exec($ch);
$obj = json_decode($result);
echo $obj;

Open in new window


When I run this code, the data posts correctly BUT the button on the form stays in the state it was when pushed (disabled, loading image just rotating). If I add window.location.href right after the ajax call on success, the page redirects, but no data is saved.

Any suggestions would be greatly appreciated!
LVL 1
marketizeitAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Julian HansenCommented:
If you want the button to revert to a non disabled state you have to specifically do this in the success function. By the same token you must put your redirect INSIDE the success function. AJAX is asychronous by definition therefore anything you do after call .ajax will in all respects execute before the AJAX call is complete - therefore you put it in the success call.
    this.$('.primary').after('<img src="loading.gif" class="loading"/>');
    this.$('button').addClass('disabled');
    this.$('button').attr('disabled', 'disabled');
    var current = this;
    $.ajax({
        type: "GET",
        url: "process.php",
        data: {
            first_name: this.$('#first_name').val(), 
            last_name: this.$('#last_name').val(), 
            day_phone: this.$('#day_phone').val(), 
            email: this.$('#email').val(), 
            amount: this.$('#amount').val(),  
            success: function(e){   
                for(var i=0;i<e.length;i++){
                    document.write(e[i]);
                }

                $('.loading').remove();
                current.$('button').removeClass('disabled');
                current.$('button').attr('disabled', false);
                // TO REDIRECT PUT YOUR REDIRECT HERE
               window.location = "newpage.html";
            }
         }
    })

Open in new window

0
Julian HansenCommented:
Notes to previous post - I put the enabling of the buttons for illustration purposes - if you are going to redirect the page then it makes no sense to do that.

You might want to implement an error: function which picks up the failure - and add the re-enabling there.
0
marketizeitAuthor Commented:
That makes sense with Ajax - thanks for the explanation of that works. If I implement your code, the button stays frozen and nothing is inserted. If I remove the whole success function and just run this:
this.$('.primary').after('<img src="loading.gif" class="loading"/>');
			this.$('button').addClass('disabled');
			this.$('button').attr('disabled', 'disabled');
			var current = this;
			$.ajax({
				type: "GET",
				dataType: "json",
				beforeSend: function(x) {
						if(x && x.overrideMimeType) {
							x.overrideMimeType("application/json;charset=UTF-8");
						}
					},
				url: "process.php",
				data: {
					first_name: this.$('#first_name').val(), 
					last_name: this.$('#last_name').val(), 
					day_phone: this.$('#day_phone').val(), 
					email: this.$('#email').val(), 
					amount: this.$('#amount').val()  
					
					}

Open in new window

The data gets saved, but the button stays frozen (disabled/loading).

So it seems to me that there is an error coming back which prevents anything inside 'success' running. I suspect it has to do with me not knowing how to pass a json object back for success - so can i either get a suggestion on that - or just a suggestion on how to use the working (saving) code above and then just redirect. Do I have to use a success function?
0
CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

Julian HansenCommented:
Do you have a link?

Have you tried looking at it in Firebug / Chrome Console?

If there is an error comming back you will be able to see what it is.
0
GaryCommented:
If you are redirecting on a successful ajax post then your success function should just be
            success: function(e){  
                        location.href="newpage.html";
            }

Nothing else, no point writing anything to the document. And doing document.write will force a 'new' page
0
marketizeitAuthor Commented:
In Chrome console - I get a message returned that just says 'undefined'?

Here's a link to the form: link
0
GaryCommented:
Is http://www.safeharborfc.com/ld/7/process.php supposed to be returning something?
0
Julian HansenCommented:
The problem is your use of this.

If you see in my code I set a var current = this.

This is because - when the success function is called the "this" is no longer in scope.

You don't actually need the "this" because you are referring to your controls by id.

this.$('.primary').after('<img src="loading.gif" class="loading"/>');
			this.$('button').addClass('disabled');
			this.$('button').attr('disabled', 'disabled');
			var current = this;
			$.ajax({
				type: "GET",
				dataType: "json",
				beforeSend: function(x) {
						if(x && x.overrideMimeType) {
							x.overrideMimeType("application/json;charset=UTF-8");
						}
					},
				url: "process.php",
				data: {
					first_name:$('#first_name').val(), 
					last_name: $('#last_name').val(), 
					day_phone: $('#day_phone').val(), 
					email: $('#email').val(), 
					amount: $('#amount').val()  
					
					}

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
marketizeitAuthor Commented:
I think I understand - but I still have the weirdness of the redirect. If I add the redirect to the success function, the page redirects but the data does not save. If I remove the redirect, the data is saved, but obviously the page stays stuck on submit. Losing. My. Mind.

if(valid) {

			this.$('.primary').after('<img src="loading.gif" class="loading"/>');
			this.$('button').addClass('disabled');
			this.$('button').attr('disabled', 'disabled');
			var current = this;
			$.ajax({
				type: "GET",
				dataType: "json",
				beforeSend: function(x) {
						if(x && x.overrideMimeType) {
							x.overrideMimeType("application/json;charset=UTF-8");
						}
					},
				url: "process.php",
				data: {
					first_name:$('#first_name').val(), 
					last_name: $('#last_name').val(), 
					day_phone: $('#day_phone').val(), 
					email: $('#email').val(), 
					amount: $('#amount').val(),  
					error: function(xhr, testStatus, error)
								{console.log("Error occured: "+error+" "+xhr+" "+testStatus)
							},
					success: function(data){
//if i remove the line below - data saves and page is stuck
//if i leave this as is, no data save and page redirects								
window.location = "http://www.safeharborfc.com/ld/7/thanks.php";
							}

					 }
				});
			
		} else {
			return false;
		}

Open in new window


Also - funny little thing: if I reverse the error and success functions (make success first, then error second), it's always the last one that does something?
0
marketizeitAuthor Commented:
@GaryC123 - the process.php page only saves the data to an outside server - I dont need anything returned.
0
GaryCommented:
You had some syntax errors

if(valid) {

			this.$('.primary').after('<img src="loading.gif" class="loading"/>');
			this.$('button').addClass('disabled');
			this.$('button').attr('disabled', 'disabled');
			var current = this;
			$.ajax({
				type: "GET",
				dataType: "json",
				beforeSend: function(x) {
						if(x && x.overrideMimeType) {
							x.overrideMimeType("application/json;charset=UTF-8");
						}
					},
				url: "process.php",
				data: {
					first_name:$('#first_name').val(), 
					last_name: $('#last_name').val(), 
					day_phone: $('#day_phone').val(), 
					email: $('#email').val(), 
					amount: $('#amount').val()},  
					error: function(xhr, testStatus, error)
								{console.log("Error occured: "+error+" "+xhr+" "+testStatus)
							},
					success: function(data){
//if i remove the line below - data saves and page is stuck
//if i leave this as is, no data save and page redirects								
window.location = "http://www.safeharborfc.com/ld/7/thanks.php";
							}

					 
				});
			
		} else {
			return false;
		}

Open in new window


ps
No points for this Julian has done all the hard work
0
marketizeitAuthor Commented:
Gary- That worked! Except now I have an error in Firebug - "Error occured:  [object Object] error"

I need to know how to figure that out - in the meantime, i just put the redirect in the error area...which i know is completely wrong - but i'm on a deadline and all i need is the saved data and the redirect.

I think I'm going to post a new question regarding this because I really need to understand this for the next project.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.