Jump to content
funbinod

problem with ajax POST method

Recommended Posts

hello all.

 

i got confused in sending form data using ajax.

 

when i send data using ajax with GET type, it works fine. but when i send it with POST type it doesn't work

 

here is the ajax i use :

$(document).ready(function(e) {
	function submIt() {
		$('input').attr('disabled', 'disabled');
		var formData = new FormData(document.getElementById("pgm"));
		$.ajax({
			url:"process.php",
			dataType:"text",
			processData:false,
			contentType:false,
			enctype:"multipart/form-data",
			type:'POST',
			data: formData,
			success: function(result) {
				$('input').removeAttr('disabled');
				if ($(result).filter('#success').text() == '' || $(result).filter('#success').text() == 'NO'){
					$('input, textarea').css('border', '2px solid red');
					alert($(result).filter('#msg').text());
				} else {
					$('input').removeAttr('disabled');
					$('input, textarea').css('border', '1px solid green');
					alert($(result).filter('#msg').text());
					$('#adit').empty();
					$('#adit').load('pgmadd.php');
				}
			},
			error: function() {
				$('input').removeAttr('disabled');
				$('input, textarea').css('border', '2px solid red');
				alert($(result).filter('#msg').text());
			}
		});
	}
	$('#submit').on('click', function(e) {
		if ($('#head').val() == '' || $('#desc').val() == '') {
			if ($('#head').val() == '') {
				alert('Program name is blank!');
				$('#head').select();
				$('#head').css('border', '2px solid red');
			}
			if ($('#desc').val() == '') {
				alert('Description is empty!');
				$('#desc').css('border', '2px solid red');
				$('#head').select();
			}
		} else {
			submIt();
		}
	});
})

it is working properly when i use < type: 'GET' >

 

Edit: I'm using jQuery 1.8.2

 

please guide me.

 

thanks in advance.

Edited by funbinod

Share this post


Link to post
Share on other sites

AND WHAT! is the 'process.php' using to read ajax data sent to it? $_POST, $_GET, or $_REQUEST.

 

its obviously $_POST

 

here is the PHP

        $m = $_POST['m'];
	if ($m == 'pgmadd') {
		$head = ($_POST['hdng']);
		$descr = ($_POST['description']);
		$usenow = 'Y';
		$sql = $mysqli->prepare("INSERT INTO programs (head, description, status, filepath) VALUES(?,?,?,?)");
		if (!$sql) {
			echo '<div id="success">NO</div>';
			echo '<div id="msg">Error: '.$mysqli->error.'</div>';
		} else {
			$sql->bind_param('ssss', $head, $descr, $usenow, $img);
			$msg = "Added Successfully!";
		}
		if ($sql->execute()) {
			echo '<div id="success">YES</div>';
			echo '<div id="msg">'.$msg.'</div>';
		} else {
			echo '<div id="success">NO</div>';
			echo '<div id="msg">Error: '.$mysqli->error.'</div>';
		}
        }

Share this post


Link to post
Share on other sites

Where is the value for $img coming from?

 

its from rest of the code that is used to upload the image.

 

its like:

$img = $dir . basename($_FILES["img"]["name"]);

edit: and the "$dir" depends on the value according to the value of "$m". its also defined above on the rest of the code.

Edited by funbinod

Share this post


Link to post
Share on other sites

Have you checked the network tab of your browser's develper tools to see what's in the response?

 

If you can see what the response is, try printing out the value of some of the variables to see what you're getting.

Share this post


Link to post
Share on other sites

in the network tab of developer tool, it says the status is 200 (i.e. ok) but i found that the ajax is not sending any data to the php (or php is not receiving the data from ajax).

Share this post


Link to post
Share on other sites

Forget the status, what's the actual response?

 

You can see what was sent and what was received in the network tab. Look at the request headers and look at the response body.

Share this post


Link to post
Share on other sites

there is nothing in the response. what it displays is the only message from the php when it is not called from proper $_POST['m'].

 

error.jpg

Share this post


Link to post
Share on other sites

If you are using jquery 1.8.2 mention in post#1, then why is it showing referring to 2.1.0

 

i thought if it would work if i use newer version. it was (and still is) the same while using 1.8.2

Share this post


Link to post
Share on other sites

OK! but did you change 'type' to 'method' as pointed out here

type (default: 'GET')
Type: String
An alias for method. You should use type if you're using versions of jQuery prior to 1.9.0.

Share this post


Link to post
Share on other sites

My guess is that the request is actually being sent as GET, the network tab should have shown that, but I can't tell because the request information isn't visible in the screenshot.

Share this post


Link to post
Share on other sites

Can you show html form and how the ajax is triggered.

here is the html form

<form id="pgm" name="pgm" method="post">
    <input type="file" id="m" name="m" value="pgmadd" hidden="hidden" />
    <span>Program:</span>
    <span><input type="text" id="head" name="head" placeholder="Name of Program" /></span><br /><br />
    <span>Image:</span>
    <span><input type="file" id="img" name="img" /></span><br /><hr />
    <span>Description:</span>
    <span><textarea rows="10" id="description" name="description" placeholder="Description of Program"></textarea></span><br /><br />
    <input id="submit" name="submit" value="Submit" type="submit" />
</form>

and here is the ajax request

<script>
$(document).ready(function(e) {
    function submIt() {
	$('input').attr('disabled', 'disabled');
	$.ajax({
		url:"process.php",
		dataType:"text",
		processData:false,
		contentType:false,
		enctype:"multipart/form-data",
		type:'POST',
		data: {
			m: 'pgmadd',
			hdng: $('#head').val(),
			img: $('#img').val(),
			description: $('#description').val()
		},
		success: function(result) {
			$('input').removeAttr('disabled');
			if ($(result).filter('#success').text() == '' || $(result).filter('#success').text() == 'NO'){
				$('input, textarea').css('border', '2px solid red');
				alert('return but error!');
				alert($(result).filter('#msg').text());
			} else {
				$('input').removeAttr('disabled');
				$('input, textarea').css('border', '1px solid green');
				alert('return success');
				alert($(result).filter('#msg').text());
				$('#adit').empty();
				$('#adit').load('pgmadd.php');
			}
		},
		error: function() {
			$('input').removeAttr('disabled');
			$('input, textarea').css('border', '2px solid red');
			alert('error with error');
			alert($(result).filter('#msg').text());
		}
	});
    }
    $('#submit').on('click', function(e) {
	submIt();
    });
})
</script>

i again remind. this is working properly when i use "type: GET".

Share this post


Link to post
Share on other sites

Why do you specify the enctype, is that necessary with jQuery? What about the other properties you're sending to the ajax method, do you know what all of those do and that you have them set correctly?

Share this post


Link to post
Share on other sites

Why do you specify the enctype, is that necessary with jQuery? What about the other properties you're sending to the ajax method, do you know what all of those do and that you have them set correctly?

 

because i'm uploading image also. so i thought i need to specify this, as i need this as i need in html form. and i read the same on some tutorials about sending image using ajax

Share this post


Link to post
Share on other sites

The problem with 'this works with 'get', is that when you submit, there is nothing to stop the whole form being submitted as well as the ajax code, meaning it will submit to itself, clear whatever is input is filled in, and prevent ajax proceeding.

 

'm', 'pmgadd' are not $_GET or $_POST, but $_FILE, so using either of these won't work either?

Share this post


Link to post
Share on other sites

i tried "$.post" in stead of "$.ajax" and the form is sent to target properly.

 

but i faced another problem with file upload. the response from php says "$_FILES['img']" to be undefined index.

Share this post


Link to post
Share on other sites

All you are doing is swapping one ajax option to another ajax alternative which unless you have set it up correctly, will give you the same outcome.

 

Fixes required:

1) prevent submission of form itself .preventDefault()

function submIt(e) { 
e.preventDefault();

.... rest of code

}

2) you need the form to capture submission not submit button click, because submission can be triggered by pressing enter in a input element

                $('#pgm').on('submit', function(e) {
                    submIt(e);
                });

3) The file type inputs values are retrieved and sent as post or get, so $_FILE is not required in process.php, just $_GET or $_POST depending which method is used.

4) Talking of 'method' you ARE STILL using 'type', when because you using version of jQuery greater than 1.9.0 now, it should be 'method'

5) enctype: "multipart/form-data" is not required, as you are sending file name as 'post' or 'get' not a actual file.

            $(document).ready(function() {

                function submIt(e) {
                    e.preventDefault();
                    $('input').attr('disabled', 'disabled');

                    $.ajax({
                        url: "process.php",
                        dataType: "text",
                        //processData: false,
                        // contentType: false,
                        //enctype: "multipart/form-data",
                        type: 'POST',
                        data: {
                            m: 'pgmadd',
                            hdng: $('#head').val(),
                            img: $('#img').val(),
                            description: $('#description').val()
                        },

6) you don't require 'processData: false or contentType: false' either so remove.

 

This should work!

  • Like 1

Share this post


Link to post
Share on other sites

This uploads 'img' named type file, I have done it to original, which has weird renaming key names, and altering of file input values. IT also look it may have compatibility issue with IE 10 and even Edge.

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta name="viewport" id="viewport" content="target-densitydpi=high-dpi,initial-scale=1.0,user-scalable=no" />
        <title>Document Title</title>
        <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
        <script  type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
        <script type="text/javascript">

        </script>
        <style type="text/css">

        </style>
    </head>
    <body>
        <form id="pgm" name="pgm" method="GET">
            <input type="file" id="m" name="m">
            <span>Program:</span>
            <span><input type="text" id="head" name="head" placeholder="Name of Program" /></span><br /><br />
            <span>Image:</span>
            <span><input type="file" id="img" name="img" /></span><br /><hr />
            <span>Description:</span>
            <span><textarea rows="10" id="description" name="description" placeholder="Description of Program"></textarea></span><br /><br />
            <input id="submit" name="submit" value="Submit" type="submit" >
        </form>
        <div id="adit"></div>
        <script>
            $(document).ready(function() {

                function submIt(e) {

                    e.preventDefault();

                    var formdata = new FormData($('#pgm').get(0));

                    formdata.set('hdng', formdata.get('head'));// copy form input named 'head' to newly created 'hdng'
                    formdata.delete('head'); // delete input named 'head' WHY??????

                    $('#pgm input[type=file]').each(function(index) {

                        if ($(this).attr('name') !== "m") {
                            formdata.set($(this).attr('name'), $('input[type=file]')[index].files[0]);// set file input within formdata
                        }

                        else {
                            formdata.set($(this).attr('name'), $('input[type=file]')[index].files[0], 'pgmadd') // set name value of input file to 'pgmadd WHY????
                        }

                    });

                    $.ajax({
                        url: "process.php",
                        type: 'POST',
                        data: formdata,
                        contentType: false,
                        cache: false,
                        processData: false,
                        success: function(result) {
                           
                            $('input').removeAttr('disabled');
                            if ($(result).filter('#success').text() == '' || $(result).filter('#success').text() == 'NO') {
                                $('input, textarea').css('border', '2px solid red');
                                alert('return but error!');
                                alert($(result).filter('#msg').text());/**/
                            } else {
                                $('input').removeAttr('disabled');
                                $('input, textarea').css('border', '1px solid green');
                                alert('return success');
                                alert($(result).filter('#msg').text());
                                $('#adit').empty();
                                $('#adit').load('pgmadd.php');
                            }
                            $('#pgm :input').attr('disabled', true);// moved here by dsonesuk
                        },
                        error: function() {
                            $('input').removeAttr('disabled');
                            $('input, textarea').css('border', '2px solid red');

                            alert($(result).filter('#msg').text());/* */
                        }
                    });
                }
                $('#pgm').on('submit', function(e) {

                    submIt(e);
                });
            });
        </script>
    </body>
</html>

with

<?php

$dir = "images/";

// Check connection
if ($mysqli->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$m = $_FILES['m']['name'];
if ($m == 'pgmadd') {

    $sourcePath = $_FILES['img']['tmp_name']; // Storing source path of the file in a variable
    $targetPath = $dir . $_FILES['img']['name']; // Target path where file is to be stored
    move_uploaded_file($sourcePath, $targetPath); // Moving Uploaded file

    $img = $targetPath;

    $head = ($_POST['hdng']);
    $descr = ($_POST['description']);
    $usenow = 'Y';
    $sql = $mysqli->prepare("INSERT INTO programs (head, description, status, filepath) VALUES(?,?,?,?)");
    if (!$sql) {
        echo '<div id="success">NO</div>';
        echo '<div id="msg">Error: ' . $mysqli->error . '</div>';
    } else {
        $sql->bind_param('ssss', $head, $descr, $usenow, $img);
        $msg = "Added Successfully!";
    }
    if ($sql->execute()) {
        echo '<div id="success">YES</div>';
        echo '<div id="msg">' . $msg . '</div>';
    } else {
        echo '<div id="success">NO</div>';
        echo '<div id="msg">Error: ' . $mysqli->error . '</div>';
    }
    
}

Edited by dsonesuk

Share this post


Link to post
Share on other sites

thank u for this @dsonesuk..

 

but sorry! there was a mistake in my html form. the input name="m" is "text" type not "file" type. so, i think, u've to write some extra line on setting formdata. i tried to revise the code accordingly. please tell me if it is correct or not--

$(document).ready(function(e) {
	function submIt(e) {
		e.preventDefault();
		var formdata = new FormData($('#pgm').get(0));
		formdata.set($(this).attr('name'), $('input[type=file]')[index].files[0]);
		$('input').attr('disabled', 'disabled');
		$.ajax({
			url: "process.php",
                        type: 'POST',
                        data: formdata,
                        contentType: false,
                        cache: false,
                        processData: false,
                        success: function(result) {
                           
                            $('input').removeAttr('disabled');
                            if ($(result).filter('#success').text() == '' || $(result).filter('#success').text() == 'NO') {
                                $('input, textarea').css('border', '2px solid red');
                                alert('return but error!');
                                alert($(result).filter('#msg').text());/**/
                            } else {
                                $('input').removeAttr('disabled');
                                $('input, textarea').css('border', '1px solid green');
                                alert('return success');
                                alert($(result).filter('#msg').text());
                                $('#adit').empty();
                                $('#adit').load('pgmadd.php');
                            }
                            $('#pgm :input').attr('disabled', true);// moved here by dsonesuk
                        },
                        error: function() {
                            $('input').removeAttr('disabled');
                            $('input, textarea').css('border', '2px solid red');

                            alert($(result).filter('#msg').text());/* */
                        }
                    });
	}
	$('#pgm').on('submit', function(e) {
		if ($('#hdng').val() == '' || $('#desc').val() == '') {
			if ($('#hdng').val() == '') {
				alert('Program name is blank!');
				$('#hdng').select();
				$('#hdng').css('border', '2px solid red');
			}
			if ($('#desc').val() == '') {
				alert('Description is empty!');
				$('#desc').css('border', '2px solid red');
				$('#hdng').select();
			}
		} else {
			submIt();
		}
	});
})

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...