-1

I want to pass some text data and file through one ajax code

Here is my code's index.php :-

<?php session_start(); if (@$_SESSION['user']!=true) { echo "<script>window.alert('You are not login.');</script>"; echo "<script>window.open('login.php','_self');</script>"; } else { include_once '../connection.php'; $uid=$_SESSION['id']; $query=mysqli_query($conn,"SELECT * FROM `register` WHERE `id`='$uid'"); $row=mysqli_fetch_array($query); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <meta name="author" content="Karthikeyan K"> <title>POST</title> <!-- Bootstrap CSS file --> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" /> <style type="text/css"> body { padding: 45px; } footer { margin: 10px 0; } .photo { margin-bottom: 10px; } </style> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" /> <link rel="stylesheet" type="text/css" href="css/jquery.mentionsInput.css"> <style type="text/css"> #status-overlay { height: 100%; width: 100%; background: rgba(0, 0, 0, 0.50); position: fixed; top: 0; left: 0; z-index: 99999; overflow: hidden; } #highlight-textarea { background: #fff; } .form-control:focus { box-shadow: 0 0 0 2px #3399ff; outline: 0; } h2 { font-size: 20px; } </style> <style> #upload_button { display: none; border: 0px; background: linear-gradient(180deg, #f44, #811); border-radius: 5px; color: #fff; padding: 5px; } </style> </head> <body> <div id="status-overlay" style="display: none"></div> <form method="POST" class="form" enctype="multipart/form-data"> <div class="form-group"> <input type="text" name="title" id="title" class="form-control" placeholder="Post title..."><br> <div id="highlight-textarea"> <textarea onclick="highlight();" name="postText" class="form-control postText mention" cols="10" rows="8" placeholder="What&#039;s going on?" dir="auto"></textarea> </div><br> <select class="form-control" name="type" id="type" required> <option value="">Choose Post Type</option> <option value="Closet">Closet</option> <option value="Follower">Follower</option> <option value="Group">Group</option> </select><br> <p><button id="upload_button">Click here to select file</button></p> <p><input id="upload_input" name="upfile" type="file"/></p> </div> <input type="button" value="Post" class="btn btn-primary pull-right postMention"> </form> <!-- Bootstrap Script file --> <script src="//ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script> <script src='https://cdn.rawgit.com/jashkenas/underscore/1.8.3/underscore-min.js' type='text/javascript'></script> <script src='js/lib/jquery.elastic.js' type='text/javascript'></script> <script type="text/javascript" src="js/jquery.mentionsInput.js"></script> <script type="text/javascript"> $(document).ready(function(){ $('textarea').on('click', function(e) { e.stopPropagation(); }); $(document).on('click', function (e) { $("#status-overlay").hide(); $("#highlight-textarea").css('z-index','1'); $("#highlight-textarea").css('position', ''); }); }); function highlight() { $("#status-overlay").show(); $("#highlight-textarea").css('z-index','9999999'); $("#highlight-textarea").css('position', 'relative'); } $(document).ready(function(){ $('.postMention').click(function() { $('textarea.mention').mentionsInput('val', function(text) { var post_text = text; if(post_text != '') { //post text in jquery ajax var post_data = "text="+encodeURIComponent(post_text); var val1 = $('#title').val(); var val2 = $('#type').val(); //var val3 = $('#upload_input'); //var post_title = $('#title').val(); var form = new FormData(document.getElementById('.postMention')); //append files var file = document.getElementById('upload_input').files[0]; if (file) { form.append('upload_input', file); } $.ajax({ type: "POST", data: post_data+'&title='+val1+'&type='+val2+'&upload_input='+form, url: 'ajax/post.php', success: function(msg) { if(msg.error== 1) { alert('Something Went Wrong!'); } else { $("#post_updates").prepend(msg); //reset the textarea after successful update $("textarea.mention").mentionsInput('reset'); } } }); } else { alert("Post cannot be empty!"); } }); }); //used for get users from database while typing @.. $('textarea.mention').mentionsInput({ onDataRequest:function (mode, query, callback) { $.getJSON('ajax/get_users_json.php', function(responseData) { responseData = _.filter(responseData, function(item) { return item.name.toLowerCase().indexOf(query.toLowerCase()) > -1 }); callback.call(this, responseData); }); } }); }); </script> </body> </html> <?php } ?> 

here's a code of my php file to insert data into database ajax/post.php . . . .

<?php session_start(); if (@$_SESSION['user']!=true) { echo "<script>window.alert('You are not login.');</script>"; echo "<script>window.open('login.php','_self');</script>"; } else { include_once '../../connection.php'; $uid=$_SESSION['id']; $query=mysqli_query($conn,"SELECT * FROM `register` WHERE `id`='$uid'"); $row=mysqli_fetch_array($query); if(isset($_POST) && !empty($_POST['text']) && $_POST['text'] != '') { include '../config/config.php'; $user = $uid; //w3lessons demo user $postid=mt_rand(); $text = strip_tags($_POST['text']); //clean the text $title= $_POST['title']; $type= $_POST['type']; define('FIRST_MATCH_GROUP', 1); preg_match_all("/@\[(.+)\]/U", $text, $tags); // Value under @[] $tags = implode(',', $tags[FIRST_MATCH_GROUP]); $upfile_name = $_FILES['upload_input']['name']; $upfile_size =$_FILES['upload_input']['size']; $upfile_tmp =$_FILES['upload_input']['tmp_name']; $upfile_type=$_FILES['upload_input']['type']; $upfile_t = explode(".", $_FILES["upload_input"]["name"]); $upfile_name = mt_rand() . '.' . end($upfile_t); if($upfile_type == "image/jpg" && $upfile_type == "image/png" && $upfile_type == "image/jpeg" && $upfile_type == "video/mp4"){ echo "<script>window.alert('extension not allowed, please choose a JPG or PNG or MP4 file.');</script>"; } else { if($upfile_size > 10485760){ echo "<script>window.alert('File size must be Less 10 MB');</script>"; } else { move_uploaded_file($upfile_tmp,"../../uploads/".$upfile_name); $DB->query("INSERT INTO posts(post_id,title,content,user_id,type,tags,image) VALUES(?,?,?,?,?,?,?)", array($postid,$title,$text,$user,$type,$tags,$upload_input)); ?> <div class="media"> <div class="media-left"> <img src="https://cdn.w3lessons.info/logo.png" class="media-object" style="width:60px"> </div> <div class="media-body"> <h4 class="media-heading">w3lessons</h4> <p><?php echo getMentions($text); ?></p> </div> </div> <hr> <?php } } } else { echo "1"; //Post Cannot be empty! } function getMentions($content) { global $DB; $mention_regex = '/@\[([0-9]+)\]/i'; //mention regrex to get all @texts if (preg_match_all($mention_regex, $content, $matches)) { foreach ($matches[1] as $match) { $match_user =$DB->row("SELECT * FROM register WHERE id=?",array($match)); $match_search = '@[' . $match . ']'; $match_replace = '<a target="_blank" href="' . $match_user['profile_img'] . '">@' . $match_user['first_name'] . '</a>'; if (isset($match_user['id'])) { $content = str_replace($match_search, $match_replace, $content); } } } return $content; } }?> 

When i submit form data was passing at my php page but images index is goes undefined...

0

1 Answer 1

0

change the way you pass data in request

try this

$(document).ready(function(){ $('.postMention').click(function() { $('textarea.mention').mentionsInput('val', function(text) { var post_text = text; if(post_text != '') { var formData = new FormData($('.form')[0]); formData.append('text',encodeURIComponent(post_text)); $.ajax({ url: 'ajax/post.php', type: 'POST', data: formData, success: function (data) { if(msg.error== 1) { alert('Something Went Wrong!'); } else { $("#post_updates").prepend(msg); //reset the textarea after successful update $("textarea.mention").mentionsInput('reset'); } }, cache: false, contentType: false, processData: false }); } else { alert("Post cannot be empty!"); } }); }); 

and input name

<input id="upload_input" name="upload_input" type="file"/> 
Sign up to request clarification or add additional context in comments.

5 Comments

getting error in php file my first statement not working That is : if(isset($_POST) && !empty($_POST['text']) && $_POST['text'] != '')
add this line before ajax req formData.append('text',encodeURIComponent(post_text));
Ohh i'm sorry that was error off server side file i had solved that one more problem is how to concatenate post_text with formData to pass both to ajax/post.php?
formData.append('post_text',encodeURIComponent(post_text))
after adding this my data in postText field will replace blank space with %20

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.