Solved

problem with post using jquery

Posted on 2015-02-13
12
42 Views
Last Modified: 2015-03-10
Hello, I have a pop up submit form which uses a jquery script to pass the values. I am not sure why when I click the submit button nothing seem to happen, the values are not passing. My jquery is as follows;

<script type="text/javascript">
function submitForm(e) {
var form = document.myform;
var dataString = $(form).serialize();

$.ajax({
	
    type:'POST',
    url:'checkbox.php',
    data: dataString,
    
	success: function(data){
                                 
				 $('#myResponse').html(data); // selector for div

              }	
	   
});
 return false;
}
</script> 

Open in new window


Can someone let me what I need to do?

Thank you,
A
0
Comment
Question by:aej1973
  • 6
  • 5
12 Comments
 
LVL 42

Expert Comment

by:Chris Stanyon
ID: 40609619
We'll probably need to see your HTML as well. It looks like your form should be called myform (name=myform), and you haven't shown us how you're calling your submitForm() function.

If you're using jQuery, usually the easiest way to do it is to bind to the submit() event of the form. This assumes your form has an ID of myForm:

$(document).ready( function() {
   $('#myForm').submit(function(e) {
      e.preventDefault(); // prevent the 'normal' submit
      // do your processing and AJAX request here
      var dataString = $(this).serialize();
      ...
   });
});

Open in new window

0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 40609740
There's a simple example of jQuery / AJAX in this article.  It shows all the moving parts.
http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Jquery/A_10712-The-Hello-World-Exercise-with-jQuery-and-PHP.html

If you want to find a simpler and better structured JavaScript solution than jQuery, you might want to learn about AngularJS.
https://angularjs.org/
0
 

Author Comment

by:aej1973
ID: 40609782
Thanks Chris, this is my html code

<a href="#close" title="Close" class="close">X</a>
<div id="content">
 <p class="account">
  <table width="100%" align="left" bgcolor="#eeeeee">
  <form id="myform" class="myform" method="post" name="myform">
 <!-- <form action="../index.php" method='post' enctype="multipart/form-data">-->
 
    	<tr bgcolor="#666666">
    	  <td colspan="4" align="center" class="bigcell"><font color="#FFFFFF" size="5"><hr color="#333333" class="strikeout" >
    	   Campaign Schedule 
   	      </hr></font></td>          
  	  </tr>
    	<tr>
    	  <td>&nbsp;</td>
    	  <td>          
     </tr>
    	<tr>  
           <td width="41%">Campaign :<?php echo $vSelect; ?>  </td>   
           <td>&nbsp;</td>            
           <td colspan="2"><div id="campaign_choice" align="left" style="color:#900"></div></td>           
        </tr>
        <tr> 
           <td colspan="4">Media Type: <font color="#990000" class="bold"><?php echo $media; ?></font></td>
        </tr>
        <tr>
        <td colspan="4"><hr></td>
        </tr>        
     <tr>
     <td>Schedule Date</td>
     <td colspan="3"><input name="createDate" type="text" id="createDate"/></td>
     </tr> 
   <tr>    
    <td>Post</td>
    <td colspan="2"><font color="#990000" class="bold"><?php echo $conid['post_text']; ?></font></td>    
  </tr>
   <tr>
        <td colspan="4"><hr></td>
   </tr>
    <tr>
      <td>Platforms</td>
      <td colspan="3"><input type='checkbox' name='channel[]' value='2'>Twitter<br>
                    <input type='checkbox' name='channel[]' value='1'>Facebook<br>
                    <input type='checkbox' name='channel[]' value='3'>Tumblr
      </td> 
     </tr>
  <tr>
        <td colspan="4"><hr></td>
  </tr>
  <tr>
    <td colspan="3" align="center"><input id="submit" type="submit" name="submit" value="Submit" onclick="return submitForm()" />
                                   <input type="hidden" name="content_id" value="<?php echo $_GET['contentid'];?>"/>
                                   <input type="hidden" name="action" value="schedule_content"/>
                                   
                                   </td>    
  </tr>
  
  </form>  
  </table>
  <div id="myResponse"></div>
</body>

Open in new window

0
 
LVL 42

Expert Comment

by:Chris Stanyon
ID: 40609932
Your code doesn't show how you're creating and showing the popup so I can't help you with that.

For the AJAX post, remove the onClick attribute from the Submit button and add this to a <script> tag in the head of your document. Also, make sure you include the jQuery library:

$(document).ready(function() {
	$('#myform').submit(function(e) {
		e.preventDefault();
		
		var dataString = $(this).serialize();
		$.ajax({
		    type:'POST',
			url:'checkbox.php',
			data: dataString
		})
		.done(function(data) {
			// do whatever you need to close the popup
			$('#myResponse').html(data);
		})
		.fail(function(jqXHR, textStatus, errorThrown) {
			alert(textStatus + " | " + errorThrown);
		});	
	});
});

Open in new window


This code will make sure your form data is POSTed to your checkbox.php script. You'll need to debug that separately to make sure it's working OK.
0
 

Author Comment

by:aej1973
ID: 40610002
What I see is happening  is that when I use Chrome and click on the submit button I am able to pass the value but it is not working in Firefox. What could the problem be?

Thanks for the help.

A
0
 
LVL 42

Expert Comment

by:Chris Stanyon
ID: 40610027
Don't know really. The jQuery will work across all browsers, so it's unlikely to be that.

Unfortunately, messages like 'it doesn't work' don't really tell us anything useful. Exactly what doesn't work? Do you get any errors? What does it do / not do?. If you have firebug installed (you REALLY should!), what does the console tell you. It should show you the POST request that's been made, along with the request data and the response.

If you have a link to a demo page we could see I'm sure we can figure it out.

We don't need an example of your full page - just the bits you want us to look at.
0
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 

Author Comment

by:aej1973
ID: 40610277
I am not sure why, but the only browser this form is working on is safari and Chrome.  On firefox when I click on the submit button, the value is not being passed to the jquery script ( the firebug console does not give me any information when I click on the submit button). When I use chrome, I see the following error(even though I am able to submit the form)  on the console " Uncaught reference error: submitForm is not defined". What does this error mean?

Thank you,
A
0
 
LVL 42

Expert Comment

by:Chris Stanyon
ID: 40610328
That tells me that you haven't removed the onclick attribute from your submit button, as I suggested.

Currently, you have this:

<input id="submit" type="submit" name="submit" value="Submit" onclick="return submitForm()" />

Open in new window


If you've followed my code suggestions, then you should have this:

<input id="submit" type="submit" name="submit" value="Submit" />

Open in new window

0
 

Author Comment

by:aej1973
ID: 40611508
Chris, it is not working for some reason. I have changed my jquery script as follows;

<script type="text/javascript">
	$(document).ready(function() {		   
         $("#add-content").click(function(e) {
               // event.preventDefault();
				var actionhide = $('#action').val();				
                var c_date=$('#createDate').val();
                var p_message = $("#post_message").val();	
				var p_media=$('input[name=media]:checked').val();
                var av_title = $("#article_video_title").val();	
				var av_link = $("#article_video_link").val();		    
		       						
                  if(c_date!=" ") {
                    $.ajax({
                    type: "POST", 
				    //cache: false,
                 //   contentType: false,
                //    processData: false,                 
                    url: "../index.php",
                    data:"createDate="+c_date+"&post_message="+p_message+"&media="+p_media+"&article_video_title="+av_title+"&article_video_link="+av_link+"&action="+actionhide,
                                        beforeSend:  function() {
                                        $('#more').html('<img src="loading.gif" />');//Loading image during the Ajax Request
                },
                                        success: function(html){
                                        $("#more").remove();
                                //      $(".updates").append(html);
                                     $("#dialog").fadeOut(200);
                                       alert("Values passed: " + html);
                                       window.location.reload(true);

              }
                                      })

                              }

                 })
		
                 return false; 
	});
</script>    

Open in new window


My html code is:
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css" />
<script src="../scripts/functions.js"></script>
</head>
<body>
<table width="100%" align="left" bgcolor="#eeeeee" >
 <!-- <form action="../index.php" method='post' enctype="multipart/form-data">-->
    	<tr bgcolor="#666666">
    	  <td colspan="4" align="center" class="bigcell"><font color="#FFFFFF" size="5"><hr color="#333333" class="strikeout" >Content Library : Create New Content</hr></font></td>
  	  </tr>
    	<tr>
    	  <td>&nbsp;</td>
    	  <td>
     <tr>
     <td>Create Date</td>
     <td colspan="3"><input name="createDate" type="text" id="createDate"/></td>
     </tr>   
    <td>Post Text</td>
    <td colspan="2"><textarea  name="post_message" id="post_message" placeholder="Post Text" cols="30" rows="5" maxlength="140"></textarea>
    <font color="#900"><div id="characterLeft"></div></font></td>    
  </tr>
   <tr>
        <td colspan="4"><hr></td>
   </tr>
    <tr>     
  	  <td>Media Type</td>
    <td  colspan="3"><input type="radio" name="media" id="media" value="10"/>Image
                     <input type="radio" name="media" id="media" value="1" checked="checked"/>None
                     <input type="radio" name="media" id="media" value="30"/>Article
                     <input type="radio" name="media" value="20"/>Youtube Video
    </td>
  </tr>
  <tr>
        <td colspan="4"><hr></td>
  </tr>
  <tr>
    <td colspan="1" class="hidesection_image">Image</td>
    <td class="hidesection_image" colspan="2" ><input type="file" name="file" id="content" /><td >
  </tr>
  <tr class="">
     <td colspan="1" class="hidesection_article">Article Title</td>
    <td colspan="3" class="hidesection_article"><input type="text" id="article_video_title" name="article_video_title" ></td>
  </tr>  
  <tr class="">
     <td colspan="1" class="hidesection_article">Article link</td>
    <td colspan="3" class="hidesection_article"><input type="text" id="article_video_link" name="article_video_link" ></td>
  </tr>  
  <tr class="">
    <td colspan="1" class="hidesection_youtube">Video Title</td>
    <td colspan="3" class="hidesection_youtube"><input type="text" id="article_video_title" name="article_video_title"></td>
  </tr> 
  <tr class="">
    <td colspan="1" class="hidesection_youtube">Video Link</td>
    <td colspan="3" class="hidesection_youtube"><input type="text" id="article_video_link" name="article_video_link"></td>
  </tr> 
  <tr>
    <td colspan="3" align="center"><input name="send"  type="button" value="submit" id="add-content" /><input type="hidden" name="action" id="action" value="add_content" /></td>    
  </tr>
 <!--</form>  -->
  </table>

Open in new window


functions.js
//start checkbox toggle script 		
			$('input[type="radio"]').click(function(){
            if($(this).attr("value")=="10"){
                $(".hidesection_image").show();
            }
			  else {
                 $('.hidesection_image').hide();   
       }
            if($(this).attr("value")=="20"){
                $(".hidesection_youtube").show();;
            }
				else {
                 $('.hidesection_youtube').hide();   
       }
            if($(this).attr("value")=="30"){
                $(".hidesection_article").show();
            }
			else {
                 $('.hidesection_article').hide();   
       }
	     
        }); //End script

Open in new window


But what I am seeing happening here is that, the value of my radio button is not being passed, the other values are passing, what could be the issue?

Thanks for all your help.

A
0
 
LVL 42

Expert Comment

by:Chris Stanyon
ID: 40611915
I've just ran your code and the value of the radio button is being passed fine.

The only thing I can see that may cause a problem is that all your radio buttons have the same ID. IDs must be unique, although this shouldn't prevent them from being submitted.

As I said before, post a link to a demo page for us to take a look at.

On another point, your approach does seem a little 'odd'. You're making an AJAX request to the index.php page, and once the request has been completed, you're reloading the page - making the AJAX request redundant. Is this intentional?
0
 

Author Comment

by:aej1973
ID: 40612004
Chris, I may be doing it wrong. What is the right way to do this?
0
 
LVL 42

Accepted Solution

by:
Chris Stanyon earned 500 total points
ID: 40612113
OK. First off, if you intend to use this to upload a file - it won't work. AJAX File Uploads are possible, but browser support is flaky at best - you'd be better of using one of the many File Upload plugins available - google for jQuery File Upload (Uploadify is a good one)

If you just want to do a standard AJAX request, then my advice is to start simple and build up from there. This way you can test as you go, and make sure each part is working fully before moving on to the next.

Create a very basic HTML page that will allow you to test the parts you need. Forget about styling or any additional jQuery. Make sure it's valid HTML.

Create a very simple PHP script that will simply display the data you've sent to it through your AJAX request.

The HTML Page:

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="utf-8">
		<title>Chris Stanyon</title>
		<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

		<script type="text/javascript">
			$(document).ready(function() {		   
		
				$("#myForm").submit(function(e) {
					// prevent the form from submitting in the 'normal' way
					e.preventDefault();
		
					// check if we have a date
					if ( $('#createDate').val() ) {
						// serialize the form data
						var dataString = $(this).serialize();	
		
						// make the AJAX call
						$.ajax({
							type: "post",
							url: "data.php",
							data: dataString
						})
						// the AJAX call succeeded
						.done(function(response) {
							$('#response').html(response);
						})
						// the AJAX call failed
						.fail(function(jqXHR, textStatus, errorThrown) {
							alert("Error: " + textStatus);
						});
					} else {
						// We don't have a date
						alert("You must enter a date");
					};
				});
				
			});
		</script>    
	</head>

	<body>
		
		<form action="#" method='post' enctype="multipart/form-data" id="myForm">
			<table width="100%">
				<tr>
					<td colspan="2">Content Library : Create New Content</td>
				</tr>
				<tr>
					<td>Create Date</td>
					<td><input name="createDate" type="text" id="createDate"/></td>
				</tr>   
				<tr>
					<td>Post Text</td>
					<td><textarea name="post_message" id="post_message" placeholder="Post Text" cols="30" rows="5" maxlength="140"></textarea>
				</tr>
				<tr>     
					<td>Media Type</td>
					<td colspan="3">
						<input type="radio" name="media" id="media_image" value="10"/><label for="media_image">Image</label>
						<input type="radio" name="media" id="media_none" value="1" checked="checked"/><label for="media_none">None</label>
						<input type="radio" name="media" id="media_article" value="30"/><label for="media_article">Article</label>
						<input type="radio" name="media" id="media_youtube" value="20"/><label for="media_youtube">Youtube Video</label>
					</td>
				</tr>
				<tr>
					<td>&nbsp;</td>
					<td>
						<input type="hidden" name="action" id="action" value="add_content" />
						<input name="send" type="submit" value="submit" id="add-content" />
					</td>    
				</tr>
			</table>
		</form>
	
		<pre id="response"></pre>
                                          
	</body>
</html>

Open in new window


The PHP Page:

<?php
var_dump($_POST);

Open in new window


Now open your page, fill in the form and click the button - you should get the form data echoed back to you underneath the form. You now know that your HTML page is working, the data is being submitted and your PHP script is receiving the data, so you can then move on to the next step - get your PHP script to process the data and do something with it (database etc). Once that's working, add in some extra jQuery and test that. etc. etc. etc...
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now