user1576748
user1576748

Reputation: 687

HTML form using jQuery AJAX

I need to retrieve data from server using jQuery AJAX on HTML form then store the response data in a php string variable. So far my code is:

<form method="post" name="myform" id="myform" action="https://domain.com/cgi-bin/cgi.exe">
<input name="exec" value="viewproduct" type="hidden">
<input name="customer" value="customer_name" type="hidden">
<input name="sku" value="sku_number" type="hidden">
<input name="submit" type="button">
</form>
<div id="results"></div>
<script type="text/javascript">
jQuery("#myform").submit(function(e){
    var postData = jQuery(this).serializeArray();
    var formURL = jQuery(this).attr("action");
    jQuery.ajax(
    {
       url : formURL,
       type: "POST",
       data : postData,
       success:function(data, textStatus, jqXHR)
       {
         jQuery('#results').html(data.toString());
       },
       error: function(jqXHR, textStatus, errorThrown)
       {
         alert('fail');    
       }
    });
    e.preventDefault();
});

jQuery(document).ready(function() {
  jQuery("#myform").submit();
});
</script>

But I still haven't see any result. If I just use the form normally without any js code, then I'll get the raw response data from the server/database directly on the browser. How can I save that raw response data on the browser into a string variable in php?

Upvotes: 1

Views: 379

Answers (2)

Josh LaMar
Josh LaMar

Reputation: 209

You won't be able to store the Javascript value into a PHP variable because PHP runs on the server and returns a response to the browser where Javascript runs on the browser. What you could do is call your script with AJAX and then set your form values with jQuery using

$("input[name=customer]").val(data);

You could either have an AJAX call for each input or you could parse out the return string to get each value. The first may be more straight forward.

If the action is becoming an issue, remove the entirely and just add an onClick to the submit button that calls a function that makes the AJAX calls.

Hope this helps!

Upvotes: 0

Deryck
Deryck

Reputation: 7668

Change your submit() handler to include this in the first line:

jQuery("#myform").submit(function(e){
    e.preventDefault();  //  <---
    ....

and/or add return false; to the end of it.

If that stops it from reloading but doesn't show anything in your #results div, troubleshoot by changing your success() in the AJAX to use this:

jQuery('#results').html(data.toString());

If that shows something, go to your server code and split up your data into individual properties that your Javascript can separate and use individually (or combine it all into one big string if you want).

.html() takes an input of String, not an object (which data is in this case).

Upvotes: 1

Related Questions