PHP - Post to Self without refreshing (Or another alternative) - javascript

Good evening SO community,
I'm trying to build a global chat system for my network of websites. In other words, a staff member can log in to www.myadminswebsite.com and check the live chat systems from all of our other external sites. I have the system working fairly well, except for the fact that the page is refreshing every time a user submits a new message. Is there something I can do to avoid refreshing the page to submit a message? Currently, I'm using an HTML form which posts to itself, then the page checks to see if the $_POST["var"] exists, then writes to the IM log file.
Code From HTML Form
<form method='POST' action='" . $_SERVER['PHP_SELF'] . "'>
<input type='text' name='newMSG' id='lcTextInput' placeholder='Type a Message'>
<input type='submit' value='Send'>
</form>
Function to Process POST
if (isset($_POST['newMSG'])) {
$wHandle = fopen($lFile, "a");
fwrite($wHandle, "[CUSTOMER] " . $_POST['newMSG'] . "\n");
fclose($wHandle);
}
This does what I need it to do, other than refreshing the page. Please let me know if you need any more information or if you have any ideas!
Thanks in advance,
Tim

<form>
<input type='text' name='newMSG' id='lcTextInput' placeholder='Type a Message'>
<input type='submit' value='Send' id="submit">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$('#submit').click(function()
{
var message=$("#lcTextInput").val();
$.ajax({
url: "msg.php",
type:'POST',
data:
{
action: 'addmsg',
message: message
},
success: function(msg)
{
$(".li").append(message);
}
});
return false;
});
</script>

Change your form action to:
<form method='POST' action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type='text' name='newMSG' id='lcTextInput' placeholder='Type a Message'>
<input type='submit' value='Send'>
</form>

$('#submit').click(function()
{
var message=$("#lcTextInput").val();
$.ajax({
url: "msg.php",
type:'POST',
data:
{
action: 'addmsg',
message: message
},
success: function(msg)
{
$(".li").append(message);
}
});
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type='text' name='newMSG' id='lcTextInput' placeholder='Type a Message'>
<input type='submit' value='Send' id="submit">
</form>

Related

Only text values being posted to php file but not files

I have the following code for an HTML form:
<form id="idForm" method="post" enctype="multipart/form-data">
<input type="text" name="first" value="Bob" />
<input type="text" name="middle" value="James" />
<input type="text" name="last" value="Smith" />
<input name="image" type="file" />
<input type="submit" name="submit" value="Submit" />
</form>
and the following Javascript code on the same page where the form is located. Also, this code is written below the form code:
$("#idForm").submit(function() {
alert("hi");
var url = "submit.php";
$.ajax({
type: "POST",
url: url,
data: $("#idForm").serialize(),
success: function(data) {
alert(data);
}
});
return false;
});
And here is the PHP code that I'm using to see if the form data is being posted:
if (isset($_FILES['image'])) {
$image = $_FILES['image'];
echo $image;
}
if (isset($_POST['first'])) {
$name = $_POST['first'];
echo $name;
}
With the above code, it seems as though the attached file is not being sent to the PHP file. Only the values are being sent, since they are echoed when I inspected the element using Google Chrome dev tool.
I want to be able to post both text value and files to the PHP file for processing.
Why am I getting this problem? How do I fix this?
Also, as part of the solution, I want to prevent the page from being refreshed when the submit button is clicked.
Thanks much!
Unfortunately input[type='file'] cannot be submitted by .serialize(), you have to manipulate by formData.
You will find a very good formData example in here

Ajax Response as HTML

When the submit button is clicked on page1.php the response is printed as HTML format for a moment but it gets automatically deleted.
I want to display the response of page2.php in page1 in the id="output" element.
What am I doing wrong?
Here is the content of page1.php
<script type="text/javascript">
function func(tosearch) {
alert("search");
$.ajax({
type: 'post',
url: 'page2.php',
data: {
'tosearch' : tosearch
},
success: function(result) {
print(result);
}
});
}
function print(result) {
document.getElementById("output").innerHTML=result;
}
</script>
<form method="post" action="page1.php">
<input type="text" name="search" placeholder="Search.."><br><br>
<input type="submit" name="submit" onclick="func()">
</form>
<p id="output">table here!!</p>
Content of page2.php
<?php echo "<table align='center'>"
."<tr>"
."<td>"."Mr XYZ"."</td>"
."<td>"."MALE"."</td>"
."<td>"."987558745"."</td>"
."<td>"."xyz#gmail.com"."</td>"
."</tr>";
?>
The response isn't being deleted, the page is refreshing. Since you don't want the page to refresh at all, you don't really need that form element. Just remove the form and make the input a plain button to keep the markup simple:
<script>
// your JavaScript
</script>
<input type="text" name="search" placeholder="Search.."><br><br>
<button onclick="func()">
<p id="output">table here!!</p>

how to get parameters in php page with ajax and $.post

actually i'm new to web and php,
i'm building a website,
i would like to introduce chat session there but, when the user click the insert button that's not working (failing to pass the paramerts to another page)
Help me out...!!!
here is the code
chat_page.php
<input type="text" id="txtmsg" name="txtmsg" size="25"> <input type="button" value="send" onclick="sndmsg()">
jscript.js
function sndmsg() {
msg=document.getElementById('txtmsg').value;
$.post("insert.php",{u:un,m:msg},function(){ });
document.getElementById('txtmsg').value="";
}
insert.php
include("connec.php");
$chatmsg=mysql_real_escape_string($_REQUEST['m']);
$uname=mysql_real_escape_string($_REQUEST['u']);
echo $chatmsg;
echo $uname;
mysql_query("INSERT INTO `mdi_chat_msg`(`uname`, `chatmsg` ) VALUES ( '$uname','$chatmsg')") or die(mysql_error());
What is un in jscript.js. Maybe, that parameter is unknown.
$.post("insert.php",{u:un,m:msg},function(){ });
You should declare un and msg variables;
var un, msg;
Check you have declare and change the type="submit" instead type="button" you cant use the word msg as variable and cant pass the js value in ajax and check un variable.
<form>
<input type="text" id="txtmsg" name="txtmsg" size="25"> <input type="submit" value="send" onclick="sndmsg()">
</form>
<script>
function sndmsg() {
msg1=$("#txtmsg").val();
$.post("insert.php",{u:un,m:msg},function(){ });
document.getElementById('txtmsg').value="";
}
$.ajax({
type: "POST",
url: "insert.php",
data: { u: un,m:msg1},
});
</script>

How to prevent from page refresh on submit button click

i have form with one input and one submit button.
<form method='POST' action='' enctype='multipart/form-data' id="form_search">
<input type='hidden' name="action" id="form_1" value='1' />
</span><input id="query" type="text" name="mol" value="">
<input type='submit' value='Search' name="Search" id="Search" />
on form submission form input data goes to php below code
if (isset($_POST['Search'])) {
$_SESSION["query"] = $_POST["mol"];
$_SESSION["action"] = $_POST["action"];
}
i want to avoid page refresh on form submission. i tried e.preventDefault() and return false;
methods in my java script but not working(this methods helping me from page refresh but does not allowing me to send data to php code)
please help me out of this problem, please suggest working ajax code for this problem.
Page refresh will delete you previous data so to reserve it you can use $.post() or $.ajax()
You can prevent page refreshing by adding one of these two things in event handler function
for pure js
return false;
for jquery you can use
e.preventDefault(); // e is passed to handler
Your complete code will be something like
using $.post() in js
function checkfunction(obj){
$.post("your_url.php",$(obj).serialize(),function(data){
alert("success");
});
return false;
}
html
<input type='submit' onclick="return checkfunction(this)" />
or same effect with onsubmit
<form onsubmit="return checkfunction(this)" method="post">
Without ajax you can simply add the checked attribute in PHP. So for example if your radio group has the name radio and one has value a, the other b:
<?php
$a_checked = $_POST['radio'] === 'a';
$b_checked = $_POST['radio'] === 'b';
?>
<input type="radio" name="radio" value="a"<?=($a_checked ? ' checked' : '')?>></input>
<input type="radio" name="radio" value="b"<?=($b_checked ? ' checked' : '')?>></input>
So when a user submits the form and you display it again, it will be like the user submitted it even the page refreshes.
<input type="radio" name="rbutton" id="r1">R1
<input type="radio" name="rbutton" id="r2">R2
<input type="button" id="go" value="SUBMIT" />
<div id="result"></div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#go').click(function(){
var val1 = $('input:radio[name=rbutton]:checked').val();
var datastring = "partialName="+val1;
$.ajax({
url: "search.php",
type: "POST",
data: datastring,
success: function(data)
{
$("#result").html(data);
}
});
});
});
</script>

Jquery and php delete row without refresh page

I am trying to make a jquery delete div function but i have one problem.
When i press submit button div was not removed and also page refreshed. How can i do without refresh page.
This is my DEMO page
This is my jquery function code:
$(document).ready(function () {
$('.ilan_alani').on('click', '.showmenu', function(e) {
var $ilan_alani = e.delegateTarget;
$('.note_area', $ilan_alani).toggle('puff');
$('.showmenu', $ilan_alani).hide();
$('.hidemenu', $ilan_alani).show();
})
.on('click', '.hidemenu', function(e) {
var $ilan_alani = e.delegateTarget;
$('.note_area', $ilan_alani).toggle("puff");
$(".hidemenu", $ilan_alani).hide();
$(".showmenu", $ilan_alani).show();
});
$('.ilan_alani .psdlt').click(function() {
$(this).parents('.ilan_alani').animate({ opacity: 'hide' }, 'slow');
});
});
and also HTML code here:
<div class="ilan_alani">
<div class="note_area">
<div class="hidemenu">
<form method="post">
<input type='submit' name='Delete' value='Delete' class='psdlt' />
</form></div>
</div>
<div class="test"></div>
<div class="showmenu">Shows</div>
</div>
<div class="ilan_alani">
<div class="note_area">
<div class="hidemenu"> <form method="post">
<input type='submit' name='Delete' value='Delete' class='psdlt' />
</form></div>
</div>
<div class="test"></div>
<div class="showmenu">Show</div>
</div>
What I want. Div without refreshing the ilan_alani is deleted.
You are using form tag and submit button which submit your form on click try to remove form tag and button type as submit
<form method="post">
<input type='submit' name='Delete' value='Delete' class='psdlt' />
</form>
to
<input type='button' name='Delete' value='Delete' class='psdlt' />
You can add onclick="return false;" on <form> to avoid event submit like this:
<form method="post" onclick="return false;">
<input type='submit' name='Delete' value='Delete' class='psdlt' />
</form>
Demo
What you want to do is make a php page apart from this,
which deletes a row based on your get or post value
something like this (with your own security and db connection added)
<?php
$db->query('DELETE FROM yourtable WHERE id = ' . $_POST['rowId']);
?>
Than with your javascript button or whatever has the click event, you add the ajax to call the page above.
So this will look something like this:
$('#someElement').click(function() {
id = the id of the row you want deleted;
$.ajax({
url: "url to the page above here",
type: "post",
data: {
"rowId" : id,
}
}).done(function() {
alert('row deleted');
});
});

Categories

Resources