Submitting post between ajax and php - javascript

I'm a newbie in the world of php and I was trying to learn it with a simple page.
I've created an html form and I want to send data using ajax but it still
POST http://localhost/Home.php 500 (Internal Server Error)
In particular I want to create a button for every table in a database which I'm using for testing, when I push a button it will show all lines from the database (I've not implemented it yet, I'm only trying to understend how php and ajax communicate)
This is my form (Home.php)
<?php
session_start();
if(!isset($_SESSION['login'])) {
header("Location: Login.php");
unset($_REQUEST);
}
else echo "<span class=\"welcome\"><strong>Benvenuto</strong> <em>" . $_SESSION['username'] . "</em></span>";
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script src='jquery-1.11.3.js'></script>
<script src='Script.js'></script>
</head>
<body>
<div id="functions">
<button id="createTable">CREATE</button>
<button id="displayTable">DISPLAY</button>
</div>
<div id="createForm">
<form id="queryForm" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<input class ="text" name="query" type="text" size="50">
<input type="submit" class="submit" name="createQuery">
</form>
</div>
<div id="displayForm">
<form method="post" id="selectForm">
<?php
include ("Database.php");
$Database = new Database( "localhost", "root", "1234");
$Database->connectToServer();
$Database->connectToDatabase("test");
$Tables = $Database->countTable();
foreach($Tables as $column) {
echo "<input type=\"radio\" class=\"submit\" id=\"selectQuery\" name=\"selectQuery\" value=\"". $column . "\"> " . $column;
}
?>
<input type="submit" class="submit" name="createSelect">
</div>
<div style="position:absolute; bottom:10px; left:50%; font-size: 15pt"></span><em>...</em> Logout</div>
</body>
</html>
<?php
if(isset($_POST['createQuery'])) {
include ("Database.php");
$Database = new Database( "localhost", "root", "1234");
$Database->connectToServer();
$Database->connectToDatabase("test");
$Database->createTable($_POST["query"]);
header("Location:Home.php");
}
?>
And this is my ajax file
$(document).ready(
function() {
$("#createTable").click(goCreate);
$("#displayTable").click(goDisplay);
$('#selectForm').submit(goSelect);
$("#createForm").hide();
$("#displayForm").hide();
}
);
function goCreate(data) {
$("#createForm").show();
$("#functions").hide();
}
function goDisplay(data) {
$("#displayForm").show();
$("#functions").hide();
}
function goSelect() {
var selectedTable = $("#selectQuery:checked").val();
console.log($("#selectQuery:checked").val());
$.ajax({
url: "Prova.php",
type: "POST",
dataType: "html",
data: {
'select': 'display',
'table': selectedTable
},
success: function(msg) {
console.log(msg);
},
error: function(xhr, desc, err) {
console.log("error");
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
}
}); // end ajax call
return false;
};
And this is Prova.php where I managed ajax call
<?php
include 'ChromePhp.php';
ChromePhp::log("corretto");
echo "ok belo";
?>

Related

How to display while loop after Ajax form submit

I'm still in a learning shift when it comes to Ajax. I made a script that sends data to a database and it works. The data inserts. Now my question is how can I display the data on the page?
display.php
<div class='displayMessage' style='height: 540px; padding:5%; overflow-x:hidden;'>
<?php
$chatmsgQ="SELECT * FROM ve_chat c
WHERE c.isActive='1' AND c.fromUserId='$loginid_session'
OR c.toUserId='$loginid_session'";
$chatmsgresult= mysqli_query($db,$chatmsgQ);
while($chatmsg= mysqli_fetch_array($chatmsgresult)){?>
<?php if($chatmsg['fromUserId']==$loginid_session):?>
<!-- user one -->
<p class='bubble pull-left'><?=$chatmsg['message'];?></p>
<?php elseif($chatmsg['fromUserId']!=$loginid_session):?>
<!-- user two-->
<p class='bubbleother pull-right'><?=$chatmsg['message'];?></p>
<?php endif;?>
<?php } ;?>
</div>
<!-- write message-->
<form id="chatForm" method='post' action='chat.php'>
<textarea id='chatMessage' name='chatMessage' placeholder="Type your message here... " value=''></textarea>
<button id='buttons' type="submit" name='sendChat' class="btn btn-default">Send</button>
<input type='hidden' id='fromUserId' name='fromUserId' value='<?=$loginid_session;?>'>
<input type='hidden' id='toUserId' name='toUserId' value='<?=$touserid;?>'>
</form>
js script
<script>
$(document).ready(function(){
$("#buttons").click(function(){
var fromuserid = $("#fromUserId").val();
var touserid = $("#toUserId").val();
var chatMessage = $("#chatMessage").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'fromUserId='+ fromuserid + '&toUserId='+ touserid + '&chatMessage='+ chatMessage;
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "chat.php",
data: dataString,
cache: false,
success: function(result){
//what do I put here exactly?
}
});
return false;
});
});
</script>
chat.php
//get variables
$chatMessage= $_POST['chatMessage'];
$fromUserId= $_POST['fromUserId'];
$toUserId= $_POST['toUserId'];
$chatStatus='1';
//insert in ve_articles_comments
$startChatQ = $db->prepare("INSERT INTO ve_chat (fromUserId,toUserId,message,isActive) VALUES (?,?,?,?)");
$startChatQ ->bind_param("iisi",$fromUserId,$toUserId,$chatMessage,$chatStatus);
$startChatQ ->execute() or die(mysqli_error($db));
if($startChatQ ){
// echo "Data Submitted succesfully";
$_SESSION['success']='<h4 style="text-align: center;" class="alert alert-success alert-dismissable" >×Your chat request was sent with success.</h4>';
header('Location: ' . $_SERVER['HTTP_REFERER']);
exit;
}
$startChatQ ->close();
$db->close();
Alright so this works for me:
display.php
<div class='displayMessage' style='height: 540px; padding:5%; overflow-x:hidden;'>
<?php
$chatmsgQ="SELECT * FROM ve_chat c
WHERE c.isActive='1' AND c.fromUserId='$loginid_session'
OR c.toUserId='$loginid_session'";
$chatmsgresult= mysqli_query($db,$chatmsgQ);
while($chatmsg= mysqli_fetch_array($chatmsgresult)){?>
<?php if($chatmsg['fromUserId']==$loginid_session):?>
<!-- user one -->
<p class='bubble pull-left'><?=$chatmsg['message'];?></p>
<?php elseif($chatmsg['fromUserId']!=$loginid_session):?>
<!-- user two-->
<p class='bubbleother pull-right'><?=$chatmsg['message'];?></p>
<?php endif;?>
<?php } ;?>
</div>
<!-- write message-->
<form id="chatForm" method='post' action='chat.php'>
<textarea id='chatMessage' name='chatMessage' placeholder="Type your message here... " value=''></textarea>
<button id='buttons' type="submit" name='sendChat' class="btn btn-default">Send</button>
<input type='hidden' id='fromUserId' name='fromUserId' value='<?=$loginid_session;?>'>
<input type='hidden' id='toUserId' name='toUserId' value='<?=$touserid;?>'>
</form>
jQuery
$(document).ready(function(){
$("#buttons").click(function(){
var fromuserid = $("#fromUserId").val();
var touserid = $("#toUserId").val();
var chatMessage = $("#chatMessage").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'fromUserId='+ fromuserid + '&toUserId='+ touserid + '&chatMessage='+ chatMessage;
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "chat.php",
data: dataString,
cache: false,
success: function(response){
$("#displayMessage").html(response);
}
});
return false;
});
});
chat.php
//get variables
$chatMessage= $_POST['chatMessage'];
$fromUserId= $_POST['fromUserId'];
$toUserId= $_POST['toUserId'];
$chatStatus='1';
$loginid_session=$_POST['fromUserId'];
//insert in ve_articles_comments
$startChatQ = $db->prepare("INSERT INTO ve_chat (fromUserId,toUserId,message,isActive) VALUES (?,?,?,?)");
$startChatQ ->bind_param("iisi",$fromUserId,$toUserId,$chatMessage,$chatStatus);
$startChatQ ->execute() or die(mysqli_error($db));
if($startChatQ ){
// echo "Data Submitted succesfully";
$chatmsgQ="SELECT * FROM ve_chat c WHERE c.isActive='1' AND (c.fromUserId='$loginid_session' OR c.toUserId='$loginid_session')";
$chatmsgresult= mysqli_query($db,$chatmsgQ);
while($chatmsg= mysqli_fetch_array($chatmsgresult)){
if($chatmsg['fromUserId']==$loginid_session){
echo " <p class='bubble pull-left'>" .$chatmsg['message'] . "</p> ";
}
elseif($chatmsg['fromUserId']!=$loginid_session){
echo " <p class='bubbleother pull-right'>" . $chatmsg['message'] . "</p> ";
} }
}
$startChatQ ->close();
$db->close();

Ajax form submit using mongodb

i am trying to use ajax submit form but for some reason it doesn't work for me, any suggestions how to fix it.
I'm getting the alert message when I submit but it takes me to another page, what am i doing wrong with ajax request ?
<!DOCTYPE html>
<html>
<head>
<title>Get Data From a MySQL Database Using jQuery and PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
// AJAX forms
$("#search_form").submit(function(e){
e.preventDefault();
//var data = $(this).serialize();
var method = $(this).attr("method");
var action = $(this).attr("action");
var username = $('#username').val();
$.ajax({
url: 'process.php',
type: 'POST',
data: { name: username },
cache: false,
success: function(data){
$('#results').html(data);
}
})
})
});
</script>
</head>
<body>
<span>Search by name: </span>
<form method="POST" action="process.php" id="search_form">
<input type="text" id="username" name="name">
<input type="submit" id="submit" value="Search">
</form>
<div id="results"></div>
</body>
</html>
process.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
// Check if $_POST is set
if ( empty ( $_POST['name'] ) ) {
echo "Something wrong!";
exit;
}
$name = $_POST['name'];
$m = new MongoClient();
//echo "Connection to database successfully";
// select a database
$address = array(
'name'=>$name,
'city' => 'test',
'state' => 'test2',
'zipcode' => 'test3'
);
$db = $m->local;
//echo "Database mydb selected";
$collection = $db->user;
//echo "Collection selected succsessfully";
$collection->insert($address);
$user = $collection->findOne(array('name' => $name));
?>
<ul>
<li><?php echo $user['name']; ?>: <?php echo $user['city']; ?></li>
<script>
alert('test 1234');
</script>
</ul>
I had to change:
$("#search_form").submit(function(e){
to:
$(document).on('submit', '#search_form', function(){
Now it works fine.
<!DOCTYPE html>
<html>
<head>
<title>Get Data From a MySQL Database Using jQuery and PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
// AJAX forms
$(document).on('submit', '#search_form', function() {
//e.preventDefault();
//var data = $(this).serialize();
var method = $(this).attr("method");
var action = $(this).attr("action");
var username = $('#username').val();
$.ajax({
type: 'POST',
url: 'process.php',
data: {
name: username
},
cache: false,
success: function(data) {
$('#results').html(data);
}
})
return false;
});
});
</script>
</head>
<body>
<span>Search by name: </span>
<form method="POST" action="process.php" id="search_form">
<input type="text" id="username" name="name">
<input type="submit" id="submit" value="Search">
</form>
<div id="results"></div>
</body>
</html>

What is the working of this function

I am newbie in php and javascript.
I want to know about the working of this function.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
});
function sendPushNotification(id){
echo ('I am in Send Push Nottification');
var data = $('form#'+id).serialize();
$('form#'+id).unbind('submit');
$.ajax({
url: "send_message.php",
type: 'GET',
data: data,
beforeSend: function() {
},
success: function(data, textStatus, xhr) {
$('.txt_message').val("");
},
error: function(xhr, textStatus, errorThrown) {
}
});
return false;
}
</script>
Q) My question is how this fuction sending the data php file
Like(http://uitdevelopers.site40.net/ClientServer/?name=qasim)
EDIT
Here is send_message.php
<?php
if (isset($_GET["regId"]) && isset($_GET["message"])) {
$regId = $_GET["regId"];
$message = $_GET["message"];
include_once 'gcm.php';
$gcm = new GCM();
$registatoin_ids = array($regId);
$message = array("price" => $message);
$result = $gcm->send_notification($registatoin_ids, $message);
echo $result;
}
?>
This is my php file and i want to execute it but i cannot understand this function
Edit
This is my index.html. Where i want to call this function
But it cannot working.
It is working staticaly but when I send data dynamically can't work
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
});
function sendPushNotification(id){
echo ('I am in Send Push Nottification');
var data = $('form#'+id).serialize();
$('form#'+id).unbind('submit');
$.ajax({
url: "send_message.php",
type: 'GET',
data: data,
beforeSend: function() {
},
success: function(data, textStatus, xhr) {
$('.txt_message').val("");
},
error: function(xhr, textStatus, errorThrown) {
}
});
return false;
}
</script>
</head>
<body>
<?php
require_once('db_functions.php');
$db = new DB_Functions();
$users = $db->getAllUsers();
if ($users != false)
$no_of_users = mysql_num_rows($users);
else
$no_of_users = 0;
?>
<div class="container">
<h1>No of Devices Registered: <?php echo $no_of_users; ?></h1>
<hr/>
<ul class="devices">
<?php
if ($no_of_users > 0) {
?>
<?php
while ($row = mysql_fetch_array($users)) {
?>
<li>
<form id="<?php echo $row["id"] ?>" name="" method="post"
onsubmit="return sendPushNotification( $row["id"])">
<label>Name: </label> <span><?php echo $row["name"] ?></span>
<div class="clear"></div>
<label>Email:</label> <span><?php echo $row["email"] ?></span>
<div class="clear"></div>
<div class="send_container">
<textarea rows="3" name="message" cols="25" class="txt_message"
placeholder="Type message here"></textarea>
<input type="hidden" name="regId" value="<?php echo $row["gcm_regid"] ?>"/>
<input type="submit" class="send_btn" value="Send"
onclick="sendPushNotification( $row["id"])"/>
</div>
</form>
</li>
<?php }
} else { ?>
<li>
No Users Registered Yet!
</li>
<?php } ?>
</ul>
</div>
</body>
</html>
$.ajax means, call method ajax from the object $
this method will use http GET method, this means that array data will be appended to URL send_message.php after question mark ?
as soon as url does not start with / or protocol (like http://), current protocol, hostname and path will be used, so final string will be PROTOCOL://HOST[:PORT]/PATH/send_message.php?form_field_name=form_field_value&form_field_name2=form_field_value2
after forming full URL, this method will use browser-dependent method (for example XMLHTTPRequest) to call this url and call your JS function success with result
It gathers the data from your form in client side by using $('selector').serialize(); of jquery and get's all the data inside your php then if your server side has no errors it throws back to your client side to show all data's by using success if it is success or error if it fails. Ajax is for querying your result without reloading your page.

How to Insert and display record without refreshing web page in codeigniter version?

I have a code here of inserting and displaying record without refreshing web page using ajax and plain php but I don't know how to set this up using codeigniter. Please help. Here are the codes
inserting.php
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js">
</script>
<script type="text/javascript" >
$(function() {
$(".comment_button").click(function() {
var test = $("#content").val();
var dataString = 'content='+ test;
if(test=='')
{
alert("Please Enter Some Text");
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="ajax-loader.gif" align="absmiddle">
<span class="loading">Loading Comment...</span>');
$.ajax({
type: "POST",
url: "demo_insert.php",
data: dataString,
cache: false,
success: function(html){
$("#display").after(html);
document.getElementById('content').value='';
document.getElementById('content').focus();
$("#flash").hide();
}
});
} return false;
});
});
</script>
// HTML code
<div>
<form method="post" name="form" action="">
<h3>What are you doing?</h3>
<textarea cols="30" rows="2" name="content" id="content" maxlength="145" >
</textarea><br />
<input type="submit" value="Update" name="submit" class="comment_button"/>
</form>
</div>
<div id="flash"></div>
<div id="display"></div>
demo_insert.php
PHP Code display recently inserted record from the database.
<?php
include('db.php');
if(isSet($_POST['content']))
{
$content=$_POST['content'];
mysql_query("insert into messages(msg) values ('$content')");
$sql_in= mysql_query("SELECT msg,msg_id FROM messages order by msg_id desc");
$r=mysql_fetch_array($sql_in);
}
?>
<b><?php echo $r['msg']; ?></b>
In your wellcome controller you can add the following:
public function inserting()
{
$this->load->view('inserting');
}
public function process()
{
$content=$this->input->post('content');
if($this->db->insert('mytable', array('msg' => $content))){
echo "<b>{$content}</b>";
}
You should then use inserting.php as your view, in application/views, and the ajax url would be /process.
Didn't test it, but this should do the trick. Also, you should check this example http://runnable.com/UXczcazDrMMiAAGl/how-to-do-ajax-in-codeigniter-for-php

How print AJAX data?

Thanks to people from stackoverflow, they helped me to realize my functional with Ajax, but now I have another problem. Below is code:
if(isset($_POST['site'])){
if($_POST['site'] == NULL)
{
echo "Field cannot be empty";
return;
}
//here we check site validation on server side
if (!preg_match("~^(?:(?:https?|ftp|telnet)://(?:[a-z0-9_-]{1,32}".
"(?::[a-z0-9_-]{1,32})?#)?)?(?:(?:[a-z0-9-]{1,128}\.)+(?:com|net|".
"org|mil|edu|arpa|gov|biz|info|aero|inc|name|[a-z]{2})|(?!0)(?:(?".
"!0[^.]|255)[0-9]{1,3}\.){3}(?!0|255)[0-9]{1,3})(?:/[a-z0-9.,_#%&".
"?+=\~/-]*)?(?:#[^ '\"&<>]*)?$~i", $_POST['site']))
{
echo "<br/>";
echo "<div id='err'>Oooops!!! Wrong site name</div>";
return;
}
$homepage = file_get_contents("http://".$_POST['site']);
preg_match('%<meta.*name="keywords".*content="(.*)"\s+/>%U', $homepage, $regs);
if(count($regs))
{
$myString = implode( '', $regs );
echo "<br/>";
echo "<div id='test'>Keywords:</div>";
print_r( "<div id='test2'>$myString</div>");
}
else
{
echo "<br/>";
echo "<div id='test'>There is no keywords</div>";
}
}
?>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#payment').submit(function(e){
e.preventDefault();
var x = $('input[name=site]').val();
$.ajax({
type: "POST",
url: 'test.php',
//data: $(this).serialize(),
data: x,
datatype: 'json',
success: function(data)
{
$('#metaTags').text(data)
},
error: function(xhr, ajaxOptions, thrownError) { alert(xhr.status);}
});
});
});
</script>
</head>
<div>
<form id="payment" method="post" name="forma1">
<label for=name>ENTER www.bbc.com:</label>
<input id="name" type=text placeholder="Write here..." name="site">
<input type="submit" value="START" name="searchbutton" id="sb">
</form>
<div id="metaTags"></div>
</div>
</html>
Everything is ok, but the output you can see here:
http://tsite.500mb.net/test.php
for testing type for example: www.bbc.com and you'll see the output result
I need that the otput will only meta tags, without source code. How to do it?
I tried next idea:
var x = $('input[name=site]').val();
$.ajax({
type: "POST",
url: 'test.php',
data: x,
where data = x, and x - value from input textbox, but it doesn't help. Any ideas?
You can use the get_meta_tags() function, here is a quick and dirty sample you can take further.
php
<?
if (isset($_POST['site'])) {
if (empty($_POST['site'])) {
echo "<div>Field cannot be empty</div>";
} else {
//here we check site validation on server side
if (!preg_match("~^(?:(?:https?|ftp|telnet)://(?:[a-z0-9_-]{1,32}" .
"(?::[a-z0-9_-]{1,32})?#)?)?(?:(?:[a-z0-9-]{1,128}\.)+(?:com|net|" .
"org|mil|edu|arpa|gov|biz|info|aero|inc|name|[a-z]{2})|(?!0)(?:(?" .
"!0[^.]|255)[0-9]{1,3}\.){3}(?!0|255)[0-9]{1,3})(?:/[a-z0-9.,_#%&" .
"?+=\~/-]*)?(?:#[^ '\"&<>]*)?$~i", $_POST['site'])) {
echo "<div id='err'>Oooops!!! Wrong site name</div>";
}
$metatags = get_meta_tags("http://" . $_POST['site']);
/* List all meta tags
echo "<pre>".print_r($metatags, true)."</pre>";
*/
if (count($metatags)) {
foreach ($metatags as $tag => $value) {
echo "<div class=\"result\"><strong>$tag:</strong> $value</div>";
}
} else {
echo "<div id='test'>There is no keywords</div>";
}
}
return;
}
?>
html
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#payment').submit(function(e) {
e.preventDefault();
var x = $('input[name=site]').val();
$.ajax({
type: "POST",
url: 'test.php',
data: {site: x},
success: function(response) {
$('#metaTags').html(response)
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
}
});
});
});
</script>
<style>
.result {
margin-bottom: 15px;
}
</style>
</head>
<body>
<div>
<form id="payment" method="post" name="forma1">
<label for="name">ENTER www.bbc.com:</label>
<input id="name" type=text placeholder="Write here..." name="site">
<input type="submit" value="START" name="searchbutton" id="sb">
</form>
<div id="metaTags"></div>
</div>
</body>
</html>
Hope it helps.

Categories