Javascript post

form.php

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function() {

$(".submit").click(function() {
    var mytext = $("#mytext").val();
    var dataString = 'mytext='+ mytext;
	if(mytext=='')
	{
	$('.success').fadeOut(200).hide();
    $('.error').fadeOut(200).show();
	}
	else
	{
	$.ajax({
	type: "POST",
    url: "texter.php",
    data: dataString,
    success: function(){
	$('.success').fadeIn(200).show();
    $('.error').fadeOut(200).hide();	
}
});
}
return false;
});
});
</script>
<input id="mytext" type="text" />
<input  type="submit" class="submit"/>
<span class="error" style="display:none">ERROR FIELD IS EMPTY</span>
<span class="success" style="display:none">DONE</span>

texter.php post

if(isset($_POST['msg_submit'])) {
	$mytext = quote_smart3(htmlspecialchars($_POST['mytext']));

	if ($_POST['mytext'] == '')
				echo 'field is empty';
	else {
	$sql = ..
				echo 'done';
	}
}

i think javascript doesn’t do correct post because when i press submit, then it says: DONE but @ mysql mytext didn’t added…
hmm how to fix?

Before i get to the code i posted below ill highlight what i found…

  1. When using input fields its best to wrap them inside a <form> element for semantic markup and so it can be used without the need for javascript
  2. A quick tip a co-worker taught me was to use event.[COLOR=SeaGreen]preventDefault/COLOR as rather then return false it doesn’t allow for the script to continue or reload the page if an error occurs.
  3. In your texter.php file you had [B]isset/B which wouldn’t have worked at all as your AJAX call didn’t have any data parameters that contained that key name.
  4. When writing your code its best not to use classes too much as they take longer to find on a page due to them been allowed to appear multiple times. Id’s are a more efficient and less time consuming way to write your markup.

form.php

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function() {
    $('#myForm').submit(function(e) {
        // Prevent the default form action
        e.preventDefault();
        
        // Get the value of the "textValue" field
        var textValue = $('input[type="text"]', this).val();
        
        // Make sure that the "textValue" field has a value/length
        if (!textValue.lenth || textValue == '') {
            $('#success').fadeOut(200);
            $('#error').fadeIn(200);
            return false;
        }
        
        $.ajax({
            data    : {text: textValue},
            type    : $(this).attr('method').toUpperCase(),
            url     : $(this).attr('action'),
            success : function(data) {
                if (data === 'success') {
                    $('#error').fadeOut(200);
                    $('#success').fadeIn(200);
                } else {
                    $('#success').fadeOut(200);
                    $('#error').fadeIn(200);
                }
            }
        });
    });
});
</script>

<form action="texter.php" method="post" id="myForm">
    <input type="text" name="textValue" />
    <input type="submit" value="Submit" />
</form>

<span id="error" style="display: none;">ERROR FIELD IS EMPTY</span>
<span id="success" style="display: none;">DONE</span>

texter.php

if (isset($_POST['text'])) {
    $text = quote_smart3(htmlspecialchars($_POST['text']));
    
    if (empty($text)) {
        echo 'error';
    } else {
        // $sql = ..
        echo 'success';
    }
    
    exit;
}

hmm thanks, but i don’t know where is problem but…
Firebug -> Net ^ All ^ says
POST form.php -> mypage.com/texter.php ^ Post
Parameters - application/x-www-form-urlencoded
text asdasd
Source
text=asdasd

js i think works fine because he is giving post but always it says ERROR FIELD IS EMPTY, if i submit text or nothing submit, but i think this php code doesn’t work… :frowning:

if (isset($_POST['text'])) {
    $text = quote_smart3(htmlspecialchars($_POST['text']));
    
    if (empty($text)) {
        echo 'error';
    } else {

Is there a link you could post so i can see the page in action?

What is that quote_smart3 function? It’s not a standard PHP function, so if it’s not defined, that can result in $text being empty.

yes sure, montavit.fps.lv
texter.php

<?
# connect to db

function quote_smart3($value) {
	if (get_magic_quotes_gpc())
	{
		$value = stripslashes($value);
	}
	if (!is_numeric($value))
	{
		$value = "'" . mysql_real_escape_string($value) . "'";
	}
	return $value;
}

if (isset($_POST['text_post'])) {
    $textX = quote_smart3(htmlspecialchars($_POST['text_post']));
    
    if (empty($textX)) {
        echo 'error';
    } else {
		# query
		mysql_query($sql)
		echo 'done';
		
	}
}
?>

jqueryform.php

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function() {
    $('#myForm').submit(function(e) {
        // Prevent the default form action
        e.preventDefault();
        
        // Get the value of the "textValue" field
        var textValue = $('input[type="text"]', this).val();
        
        // Make sure that the "textValue" field has a value/length
        if (!textValue.length || textValue == '') {
            $('#success').fadeOut(200);
            $('#error').fadeIn(200);
            return false;
        }
        
        $.ajax({
            data    : {text_post: textValue},
            type    : $(this).attr('method'),
            url     : $(this).attr('action'),
            success : function(data) {
                if (data === 'success') {
                    $('#error').fadeOut(200);
                    $('#success').fadeIn(200);
                } else {
                    $('#success').fadeOut(200);
                    $('#error').fadeIn(200);
                }
            }
        });
    });
});
</script>

<form action="/texter.php" method="POST" id="myForm">
    <input type="text" name="textValue" />
    <input type="submit" value="Submit" />
</form>

<span id="error" style="display: none;">ERROR FIELD IS EMPTY</span>
<span id="success" style="display: none;">DONE</span>

ps. Firebug
http://imageshack.us/m/541/212/montavit.png

Compare the name of the form fields, with those retrieved by $_POST

You’ll find that there’s a discrepancy there.

thanks all!! now it works!
but when i press submit, then text = added @ db but js show always “ERROR FIELD IS EMPTY”

In this line:

success : function(data) {

The data variable is whatever the php file outputs as text. The JavaScript code expects it to output ‘success’ so you need to check what texter.php actually outputs.

ok, after query i pasted:

die('success');

now all works fine!

and now i added this script identical to my website but when i press Submit then i got in firebug:
textValue is undefined

 if (!textValue.length || textValue == '') {

what reasons can be for this error?
does i need to add @ input length=“20”?
but on montavit.fps.lv (test page) he works fine…

Do you have a link to a test version of your page that has the problem?

yes sure
bit.ly/hEvXao
Lietotāja vārds = testacc
Parole = 123
sidebar like chat

Looking at the DOM tree, the input fields aren’t contained by the form.


<form action="/sys/sidebar/inc/chat.php" method="POST" id="myForm"></form>
<input type="text" name="textValue">
<input type="submit" value="Submit">

even though the source code show this instead:


<form action="/sys/sidebar/inc/chat.php" method="POST" id="myForm"> 
<input type="text" name="textValue" /> 
<input type="submit" value="Submit" /> 
</form> 

So, the web browser itself is for some reason not processing the HTML code as it should.

That’s quite a mystery.

I think that the web browsers are mis-interpreting form because the content in a table row is not contained by a <td> element.

this <form></form> <input… can be when i uploaded script trying to get it work…


<form action="/sys/sidebar/inc/chat.php" method="POST" id="myForm"></form>
<input type="text" name="textValue">
<input type="submit" value="Submit">

amm doesn’t work… :frowning:
http://imageshack.us/m/856/1511/ihavealready.png

One of your <tr> tags does not have a <td> tag inside it. That’s the problem.

Without that, the web browser tries to fix things, and fails.
That’s why the web browser misinterprets your form.

Fix the bad table code and the form problem will fix itself.

thanks, fixed!
do u have any idea how to give for js this Message added?

die('success');

just now i have content before the die and now he is saying again Sorry the field is empty!
and refreshing chat without page reload after submiting? because when i hit on enter then i can floood many many messages…

The response from chat.php is much more than just “success”. This is what the Ajax request is receiving from chat.php


<div id="chat_container">
<div id="chat_content">
<script type="text/javascript">
$(function() {
    $('#myForm').submit(function(e) {
        // Prevent the default form action
        e.preventDefault();
        
        // Get the value of the "textValue" field
        var textValue = $('input[type="text"]', this).val();
        
        // Make sure that the "textValue" field has a value/length
        if (!textValue.length || textValue == '') {
            $('#success').fadeOut(200);
            $('#error').fadeIn(200);
            return false;
        }
        
        $.ajax({
            data    : {text_post: textValue},
            type    : $(this).attr('method'),
            url     : $(this).attr('action'),
            success : function(data) {
                if (data === 'success') {
                    $('#error').fadeOut(200);
                    $('#success').fadeIn(200);
                } else {
                    $('#success').fadeOut(200);
                    $('#error').fadeIn(200);
                }
            }
        });
    });
});
</script>
<div id="ajax_chatinc"><div class="loading"></div></div>
success

Notice the “success” at the end? Even though it’s at the end, it’s the whole output from chat.php that is assigned to the data variable.

So if you want “success” to work, you need to stop the other code from being outputted.

fixed! thaaanks!
so… do u have any idea to refresh chat without page reload after submiting in my situation? because when i hit on enter then i can floood many many messages…

I understand your words individually but collectively they make very little sense. That might be due to it being near 2:30am though, so let’s hope someone else can make better sense of them than I.