how to pass a validation from php to ajax - php

How can I make my error messages appear after validation in PHP using AJAX
Hi, I'm currently working on my ajax and I'm tryng to figure out on how will my error message appear on my form. I've already tried to echo the error but what I want is show the error on every invalid field.
here's my html code:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style>
span{
display: none;
}
</style>
</head>
<body>
<form action="test2.php" method="POST" id="formLogin" class="pass">
name: <input type="text" name="name" id="name">
<span id="name">Invalid!</span>
<br>
description: <textarea name="description" id="description"></textarea>
<span id="desc">Invalid!</span>
<br>
image file: <input type="file" name="image" id="image">
<button type="submit" ></button>
</form><br>
<p class="form-message"></p>
<script src="ajax.js"></script>
</body>
heres my ajax code:
$(document).ready(function(){
$("#formLogin").submit(function(event){
event.preventDefault();
$.ajax({
url: 'test2.php',
type: 'POST',
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function(data)
{
if(data.name == "1"){
$("span#name").css("display","block");
}else{
$("span#name").css("display","none");
}
if(data.desc == "1"){
$("span#desc").css("display","block");
}else{
$("span#desc").css("display","none");
}
}
});
});
});
and my php code;
<?php
$myObj = new stdClass();
if(empty($_POST['name'])){
$myObj->name = "1";
}
if(empty($_POST['description'])){
$myObj->description = "1";
}
$myJSON = json_encode($myObj);
echo $myJSON;
?>

In success of ajax, you receive the data in json formate , before use the data.name you have to reqiure parse json like
data=$.parseJSON(data) OR data=JSON.parseJSON(data)
then use data.name

Related

TinyMCE and AJAX is not sending data to php in mysql server

<!-- Page containing form -->
Paragraph
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="//tinymce.cachefly.net/4.2/tinymce.min.js"></script>
<!-- Just be careful that you give correct path to your tinymce.min.js file, above is the default example -->
<script>tinymce.init({selector:'textarea'});</script>
</head>
-->
<div class="container">
<br />
<br />
<h2 align="center">Enter a new paragraph</h2>
<div class="form-group">
<form name="add_paragraph" id="add_paragraph">
<div class="table-responsive">
<table class="table table-bordered
id="dynamic_field">
<tr>
<textarea id = "paragraph" type="text" name="paragraph" placeholder="Enter paragraph text"></textarea>
</tr>
</tr>
</table>
<input type="button" name="submit" id="submit" class="btn btn-info" value="Submit" />
</div>
</form>
</div>
</div>
</body> </html> <script> $(document).ready(function(){
$('#submit').click(function(){
$.ajax({
url:"form1_support.php",
method:"POST",
data:$('#add_paragraph').serialize(),
success:function(data)
{
alert(data);
$('#add_paragraph')[0].reset();
}
});
}); }); </script>
require 'db/connect.php';
$number = count($_POST["paragraph_name"]); //it said experience
before, maybe experience_list?
if($number > 0) {
for($i=0; $i<$number; $i++)
{
if(trim($_POST["paragraph_name"] != ''))
{
$paragraph_name = mysqli_real_escape_string($db, $_POST['paragraph_name']);
$paragraph_text = mysqli_real_escape_string($db, $_POST['paragraph']);
$sql = "INSERT INTO paragraph (paragraph_name, paragraph_text)
VALUES( '$paragraph_name', '$paragraph_text')";
mysqli_query($db, $sql);
}
}
echo "Data Inserted"; } else {
echo "Please Enter Your Paragraph."; } ?>
If you are replacing a textarea with TinyMCE then the actual textarea does not get updated automatically unless one of the following happens:
You perform a standard HTML form submission - in this scenario TinyMCE will automatically update the textarea at the start of the form submission process.
You use the triggerSave() API to force TinyMCE to update the textarea.
Try adding a triggerSave() call before you send the AJAX request.
https://www.tiny.cloud/docs/api/tinymce/root_tinymce/#triggersave
<textarea id="editor" name="editor" type="text"></textarea>
tinyMCE.triggerSave();
var content = $("textarea[name=editor]").val();
var formData = new FormData();
formData.append("content", content);
$.ajax({
url: '../boot/newBlog.php',
method: 'POST',
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function(response) {
switch (response){
}
}
});

I want the appearance of div when the conditions in the php file

Hi I want to show the div (msga) when the first condition i want the appearance of div (msgb) when the second condition
my php code
if(isset($_POST['aa'])) {
echo "a";
}
if (isset($_POST['bb']))) {
echo "b";
}
my ajax code
<script>
$('#form')
.submit( function(e) {
$.ajax({
url: 'php.php',
type: 'POST',
data: new FormData( this ),
processData: false,
contentType: false,
success: function(response){
if (response == 'a') {
$('#msga').show();
}else if (response == 'b') {
$('#msgb').show();
}
}
});
});
</script>
my html code
<div id="msga" style="display: none;">aaaaaaaaaa</div>
<div id="msgb" style="display: none;">bbbbbbbbbb</div>
<form id="form" method="post" enctype="multipart/form-data">
<input name="test" type="text" value="test"/>
<input class="up" type="file" name="up" />
<button class="submit">send now</button>
</form>
First things, you have an error on your php.php
hence your code never execute as you expected.
Parse error: syntax error, unexpected ')' in
.... on line 7
this is line 7 :
if (isset($_POST['bb']))) { You have an extra ")"
and the space between the if ( will give u errors.
and also
$_POST['aa'] and $_POST['bb']
does not exist.
And when you click the submit button your page will load a little trying to submit the form by the default form action, because you did not prevent it with e.preventDefault();
This how your code should be
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<div id="msga" style="display: none;">aaaaaaaaaa</div>
<div id="msgb" style="display: none;">bbbbbbbbbb</div>
<form id="form" method="post" enctype="multipart/form-data">
<input name="test" type="text" value="test"/>
<input class="up" type="file" name="up" />
<button class="submit">send now</button>
</form>
<script>
$('document').ready(function(){
$('#form').submit( function(e) {
// e.preventDefault();
$.ajax({
url: 'php.php',
type: 'POST',
data: new FormData( this ),
processData: false,
contentType: false,
success: function(response){
// console.log(response);
if (response == 'a') {
// $('#msga').show();
$("#msga").css("display", "block");
}else if (response == 'b') {
$('#msgb').css("display", "block");
}
}
});
});
});
</script>
Then php.php
<?php
if(isset($_POST['test'])) {
echo "a";
}
if(isset($_POST['up'])) {
echo "b";
}
?>
Your form has no input with name="aa" or name="bb" so the response data to the ajax call is always empty.

file is not uploading in ajax php mysql

I am trying to upload a file using ajax which is giving me an error and the rest of data upload successfully i have try without ajax the file is uploading but when i try to upload file via ajax it give me error i am totally confuse why ajax is giving me the problem.here is my code.
<html>
<head>
<script src="jquery-1.8.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#button").click(function(){
var form_data = $('#reg_form').serialize();
$.ajax({
type:"POST",
url:"process.php",
data:form_data,
success: function(data)
{
$("#info").html(data);
}
});
});
});
</script>
</head>
<body>
<form id="reg_form" enctype="multipart/form-data" method="post" action="">
name : <input type="text" name="name" id="name"/>
</br>
message : <input type="text" name="message" id="message" />
</br>
Image : <input type="file" name="file" id="file" />
<input type="button" value="Send Comment" id="button">
<div id="info" />
</form>
</body>
</html>
The process.php file coding is here.
<?php
mysql_connect("localhost","root","");
mysql_select_db("ajaxdatabase");
$name=$_POST["name"];
$message=$_POST["message"];
//storing file in filename variable
$fileName = $_FILES['file']['name'];
//destination dir
$to="image/".$fileName;
move_uploaded_file($_FILES['file']['tmp_name'],$to);
$query=mysql_query("INSERT INTO common(name,message,destination) values('$name','$message','$to') ");
if($query){
echo "Your comment has been sent";
}
else{
echo "Error in sending your comment";
}
?>
First of all serialize() function don't work for file you should have to make an object of form through which you can post the data and will work perfectly I had the same problem and I have just resolved your issue and is working 100% because I have tested this. Please check out.
The form.
<form name="multiform" id="multiform" action="process.php" method="POST" enctype="multipart/form-data">
name : <input type="text" name="name" id="name"/>
</br>
message : <input type="text" name="message" id="message" />
</br>
Image : <input type="file" name="file" id="file" />
</form>
<input type="button" id="multi-post" value="Run Code"></input>
<div id="multi-msg"></div>
The script.
<script type="text/javascript">
$(document).ready(function(){
$("#multiform").submit(function(e)
{
var formObj = $(this);
var formURL = formObj.attr("action");
if(window.FormData !== undefined)
{
var formData = new FormData(this);
$.ajax({
url: formURL,
type: 'POST',
data: formData,
mimeType:"multipart/form-data",
contentType: false,
cache: false,
processData:false,
success: function(data, textStatus, jqXHR)
{
$("#multi-msg").html('<pre><code>'+data+'</code></pre>');
},
error: function(jqXHR, textStatus, errorThrown)
{
$("#multi-msg").html('<pre><code class="prettyprint">AJAX Request Failed<br/> textStatus='+textStatus+', errorThrown='+errorThrown+'</code></pre>');
}
});
e.preventDefault();
e.unbind();
}
});
$("#multi-post").click(function()
{
//sending form from here
$("#multiform").submit();
});
});
</script>
And your php file is the same I have tested and is working.
<?php
mysql_connect("localhost","root","");
mysql_select_db("ajaxdatabase");
$name=$_POST["name"];
$message=$_POST["message"];
//storing file in filename variable
$fileName = $_FILES['file']['name'];
//destination dir
$to="image/".$fileName;
move_uploaded_file($_FILES['file']['tmp_name'],$to);
$query=mysql_query("INSERT INTO common(name,message,destination) values('$name','$message','$to') ");
if($query){
echo "Your comment has been sent";
}
else{
echo "Error in sending your comment";
}
?>

how to insert value in database using php, jquery and ajax

I am struggling very hard to get this to work and I don't know what I'm doing wrong. I have a register page that I want to take the data inserted into the form and INSERT it to the database with jQuery and AJAX. I'm not very experienced with AJAX AND jQuery so be gentle! :P I will show you the files that I have...this is a msg.php page when i have submit data sometimes post submit in database`
mostly not so i want to know that why it s happening i am new in this field
<?
php $id=$_GET['id'];
$id1=$_SESSION['id'];
?>
<form method="post" class="msgfrm" id="msgfrm">
<input type="hidden" value="<?php echo $_GET['id']; ?>" name="rcvrid" id="rcvrid">
<input type="hidden" name="senderid" id="senderid" value="<?php echo $id1;?>" >
<div class="msgdiv" id="chatbox"></div>
<div class="textdiv">
<input type="text" name="msg" id="msg" class="textmsg">
<input type="submit" value="Send" onClick="sendChat()">
</div>
</form>
function sendChat()
{
$.ajax({
type: "POST",
url: "msg_save.php",
data: {
senderid:$('#senderid').val(),
rcvrid:$('#rcvrid').val(),
msg: $('#msg').val(),
},
dataType: "json",
success: function(data){
},
});
}
msg_save.php file
<?php
require_once('include/util.php');
$rcvrid=$_POST['rcvrid'];
$senderid=$_POST['senderid'];
$msg=$_POST['msg'];
$sql="insert into message(rcvrid,senderid,msg) values($rcvrid,$senderid,'$msg')";
mysql_query($sql);
?>
$.ajax({
type: "POST",
url: "msg_save.php",
data: " senderid="+$('#senderid').val()+"rcvrid="+$('#rcvrid').val()+"msg="+$('#msg').val(),
dataType: "json",
success: function(data){
},
});
please try this code and send data ,and use post method in php to get data,it will work
if you are trying chat application check this, it is old but just for idea:
http://www.codeproject.com/Articles/649771/Chat-Application-in-PHP
use mysqli_query instead of mysql_query recommended
<?php
$id=$_GET['id'];
//$id1=$_SESSION['id']; COMMENTED THIS AS I AM NOT IN SESSION. HARDCODED IT IN THE FORM AS VALUE 5
?>
<html>
<head>
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
</head>
<body>
<form method="post" class="msgfrm" id="msgfrm">
<input type="hidden" value="<?php echo $_GET['id']; ?>" name="rcvrid" id="rcvrid">
<input type="hidden" name="senderid" id="senderid" value="5" >
<div class="msgdiv" id="chatbox"></div>
<div class="textdiv">
<input type="text" name="msg" id="msg" class="textmsg">
<input type="submit" value="Send" >
</div>
</form>
<script>
$("#msgfrm").on("submit", function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "msg_save.php",
data: $(this).serialize(),
success: function(data) {
$("#chatbox").append(data+"<br/>");//instead this line here you can call some function to read database values and display
},
});
});
</script>
</body>
</html>
msg_save.php
<?php
//require_once('include/util.php');
$rcvrid = $_POST['rcvrid'];
$senderid = $_POST['senderid'];
$msg = $_POST['msg'];
echo $rcvrid.$senderid.$msg;
$con = mysqli_connect("localhost", "root", "", "dummy");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "insert into message(rcvrid,senderid,msg) values($rcvrid,$senderid,'$msg')";
mysqli_query($con,$sql);
mysqli_close($con);
echo "successful"
?>
check that whether you have inserted jquery file or not.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
Then include your function sendChat() inside <script> tags.
On submit button
<button type="submit" id="button">SAVE</button>
<script>
$(document).ready(function(){
$("#button").click(function(){
var firstname=$("#firstname").val();
var lastname=$("#lastname").val();
var email=$("#email").val();
$.ajax({
url:'dbConfigAndInsertionQuery.php',
method:'POST',
data:{
firstname:firstname,
lastname:lastname,
email:email
},
success:function(data){
alert(data);
}
});
});
});
</script>

How do I get my jQuery and PHP to work together with ajax?

I've seen some similar questions, but I haven't seen any that specifically speaks to this. I've created a very simple sample, and I feel that it should work, but it doesn't. The point is to see something simple, so that other, similar things are clear.
I feel that this is very 'basic', and it's hard to be much simpler; so, people should be able to get behind it, knowing that it's the ultimate noobie stepping stone:
The HTML and JS:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<script type="javascript"></script>
<script type="text/javascript" src="/javascript/jquery-1.8.2.js">
$(document).ready(function(){
$("submit").click(function(){
var req = $.ajax({
type: 'POST',
url: 'form.php',
data: {
message: $('#message').val(),
author: $('#author').val()
},
timeout: 20000,
beforeSend: function(msg) {
$("#sent").html(msg);
}
});
req.fail(function(xhr, ajaxOptions, thrownError) {
alert("AJAX Failed");
});
req.done(function(res) {
$("#received").html(res);
});
});
});
</script>
</head>
<body>
<div id="sent"></div>
<div id="form">
<form>
Your message: <input type="text" name="message" value="Hi!" /><br />
Your name: <input type="text" name="author" value="Michael" /><br />
<input type="submit" name="submit" value="Submit me!" />
</form>
</div>
<div id="received"></div>
</body>
</html>
And the PHP:
<?php
echo "The file is located at ".$_POST["message"].".<br>";
echo "The file is named ".$_POST["author"].".";
You can use serialize instead of assigning id to the input fields:
<html>
<head>
<script type="javascript"></script>
<script type="text/javascript" src="/javascript/jquery-1.8.2.js">
$(document).ready(function(){
$("#submit").click(function(){
var req = $.ajax({
type: 'POST',
url: 'form.php',
data: $('#frm').serialize(),
timeout: 20000,
beforeSend: function(msg) {
$("#sent").html(msg);
},
success: function(data){
alert('Success!Data was received by php.Message from the php script:'+data.res);
}
});
req.fail(function(xhr, ajaxOptions, thrownError) {
alert("AJAX Failed");
});
req.done(function(res) {
$("#received").html(res);
});
});});
</script>
</head>
<body>
<div id="sent"></div>
<div id="form">
<form id="frm">
Your message: <input type="text" name="message" value="Hi!" /><br />
Your name: <input type="text" name="author" value="Michael" /><br />
<input type="submit" id="submit" value="Submit me!" />
</form>
</div>
<div id="received"></div>
</body>
</html>
PHP SCRIPT:
<?php
if(isset($_POST['message']) && isset($_POST['author']))
{
$arr_to_pass_as_json = array('res'=>'This is your message:'.$_POST['message'].' and your author '.$_POST['author']);
echo json_encode($arr_to_pass_as_json)
}
else
echo json_encode(array('res'=>'Message and Author is required'));
We use json in displaying result from php to javascript. hope this will help.
Check the difference with this:
$(document).ready(function(){
$("submit").click(function(){
var req = $.ajax({
type: 'POST',
url: 'form.php',
data: {
message: $('#message').val(),
author: $('#author').val()
},
timeout: 20000,
beforeSend: function(msg) {
$("#sent").html(data);
}
})
.fail(function(xhr, ajaxOptions, thrownError) {
alert("AJAX Failed");
})
.done(function(res) {
$("#received").html(res);
});
});
});
Check if this works (According to http://api.jquery.com/jQuery.ajax/#jqXHR it should)
since your using
message: $('#message').val(),
author: $('#author').val()
You will need to specify your id's in you input tgs.
<form>
Your message: <input type="text" name="message" value="Hi!" id="message" /><br />
Your name: <input type="text" name="author" value="Michael" id="author" /><br />
<input type="submit" name="submit" value="Submit me!" />
</form>
Your asking to find and html id selectyor, and get the value from it, 'name' is NOT the same as an ID.
Alternatively you could put and id on your html form and use .sezialize(), but simply adding an id is simpler at this step.
http://api.jquery.com/serialize/

Categories