ajax is not reading json php response correctly - javascript

I have done a lot of reading research on trying to figure out why ajax is reading a json response as undefined, and of course I have tried a lot of those solutions too, but unfortunately they don't work for me. If you guys can help, it would be GREAT!!!!
I have tried adding dataType: 'json', using data.status and data['status'], they still come as undefined. I can see see php responding the correct status in json format (an example of the response is at the bottom of the page)
php side:
//doing sql query
if ($conn->query($sql) === TRUE) {
$response_array["status"] = "success";
} elseif ($conn->errno == 1062) {
$response_array["status"] = "dup";
} else {
$response_array["status"] = "error";
}
header('Content-Type: application/json');
echo json_encode($response_array);
jquery side:
$(document).ready( function(){
$('#name_form').submit( function(event) {
if ( !formValidation()) {
event.preventDefault();
} else {
var datastr = $('#addclass_form').serialize();
$.ajax({
type: 'POST',
url: someurl,
data: datastr,
success: function(data) {
alert(data.status);
console.log(data);
},
error: function() {
alert('php error');
}
});
}
});
});
html side:
<form id='name_form'>
<div>
<b>Class Name</b>
<input type='text' name='classname' id='classname' placeholder='Enter Class Name'>
</div>
<div class='ui-grid-c'>
<div class='ui-block-a main'><b>Component</b></div>
<div class='ui-block-b point'><b>Max Point</b></div>
<div class='ui-block-c per'><b>Percentage</b></div>
</div>
<div id='components'>
<div class='ui-grid-c'>
<div class='ui-block-a main'><input type='text' name='component0' id='component0' placeholder='Component'></div>
<div class='ui-block-b point'><input type='number' name='point0' id='point0' placeholder='Max Point'></div>
<div class='ui-block-c per'><input type='number' name='percentage0' id='percentage0' placeholder='Percentage'></div>
<div class='ui-block-d rm'><button type='button' class='ui-btn ui-icon-delete ui-shadow ui-corner-all ui-btn-icon-notext' disabled></button></div>
</div>
</div>
<br>
<input type='hidden' name='compSize' id='compSize'>
<input type='submit' class='ui-btn ui-btn-b ui-shadow ui-corner-all' value='Create Class'>
</form>
output of console.log(data):
<!doctype html>
<html>
<head>
</head>
<body>
{"status":"success"}
</body>
</html>

Related

Jquery AJAX shows webpage when form is submitted successfully

I have a form in PHP am sending via AJAX Jquery. The form is sent successfully via AJAX JQuery but the webpage is shown when the success message shows or the form is sent. What might be the exact problem causing this.
<? php include_once 'config.php'; if(isset($_POST) && !empty($_POST)) { $staff_number=$ _POST[ 'staff_number']; $department=$ _POST[ 'department']; $stmt=$ link->prepare("INSERT INTO `staffs` (`staff_name`,`department`) VALUES (?,?)"); $stmt->bind_param('ss',$staff_name, $staff_number, $designation, $department); if ($stmt->execute()){ echo "<span style='background-color:#69d052;
padding:6px;
color:white; font-size:13px;border-radius:5px;'>Staff created
successfully. </span>"; } else{ echo "
<p align=center>Error inserting data.</p>"; echo mysqli_error($link); } } ?>
<!DOCTYPE html>
<body>
<div class="container">
<div class="col-md-7 col-md-offset-3">
<form action="" method="post" autocomplete="off" id="my_form">
<div class="form-group">
<label>Staff Name</label>
<input type="text" required="true" name="staff_name" class="form-control" value="">
</div>
<div class="form-group">
<label>Department</label>
<input input="text" name="department" class="form-control" value="">
</div>
<div class="message_box" style="margin:50px 0px;">
</div>
<br>
<input type="submit" class="btn btn-success" value="Add">
</form>
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/ libs/jquery/1.3.0/jquery.min.js"></script>
<script>
$(function() {
$('form').on('submit', function(e) {
e.preventDefault();
$('.message_box').html('Processing...');
$.ajax({
type: 'post',
data: $('form').serialize(),
success: function(data) {
$('.message_box').html(data).fadeIn('slow');
$("#my_form")[0].reset();
}
});
});
});
</script>
</body>
</html>
You might be Redirecting the request after success from the server side (PHP). That's why a page is showing.
In you ajax call you are not setting your url property, by default this will be set to the current page, that is why you might be getting the page instead.
try adding your url, to your ajax...
$.ajax({
url: '..my ajax url.....',
type: 'post',
data: $('form').serialize(),
success: function(data) {
$('.message_box').html(data).fadeIn('slow');
$("#my_form")[0].reset();
}
});

405 method not found. On localhost

So I'm making a form that puts info into my local mysql db. But I stuck when I try to POST it. I getting "405 method not found" when try to debbug. I'm sing xampp for my virtual DB, maybe it's because of that?
The code:
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Kasmetinių atostogų prašymas</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div class="title">
<h1>Kasmetinių atostogų prašymas</h1>
</div>
<div class="form">
<form id="requestForm" method="POST" target="_blank">
<input type="date" name="request_date" id="input_field" placeholder="Prašymo data" required></br></br>
<input type="text" name="first_name" placeholder="Vardas" id="input_field" required></br></br>
<input type="text" name="last_name" placeholder="Pavardė" id="input_field" ></br></br>
<input type="number" name="personal_code" placeholder="Asmens kodas" id="input_field" min="11" max="11" ></br></br>
<input type="text" name="p_address" placeholder="Jūsų adresas" id="input_field" ></br></br>
<input type="date" name="requestDateFrom" id="input_field" placeholder="Atostogos nuo" ></br></br>
<input type="date" name="requestDateTo" id="input_field" placeholder="Atostogos iki" ></br></br>
<input type="number" name="daysNumber" placeholder="Atostogų dienų skaičius" id="input_field" ></br></br>
</br>
<Input type="button" name="submit_button" id="buttonLast" value="Patvirtinti">
</form>
</div>
<script>
$(document).ready(function(){
$("#buttonLast").click(function(){
$.ajax({
url:"http://127.0.0.1:5500/insert.php",
type: "POST",
data:$("#requestForm").serialize(),
success:function(response)
{
alert("Well done!");
}
});
});
});
</script>
</body>
</html>
And this is php code to connect db and post info into specific columns.
For the purpose of test I trying to post just from the 3 cols.
PHP:
<?php
$con = mysqli_connect("localhost","root","","test");
if(!$con)
{
echo 'Connection problems';
}
else
{
echo 'Ok';
}
if(isset($_POST['submit'])){
$date = $_POST['requestDate'];
$name=$_POST['firstName'];
$lname = $_POST['lastName'];
$query = "insert into info (date,name,lname) values ('$date','$name','$lname')";
if($con->query($query) === true )
{
echo 'Duomenys išsaugoti!';
}
else{
echo 'Duomenų nepavyko išsaugoti!';
}
}
header("refresh:2; url=index.html");
?>
Change
type: "POST"
to
method:"POST"
Other error you might encounter:
You are using requestDate in php but request_date in html. Similar for other params.
Update:
Add cors header to Ajax call
url:"http://127.0.0.1:5500/insert.php",
method: "POST",
headers: {
'Access-Control-Allow-Origin': '*'
},
data:$("#requestForm").serialize(),
success:function(response)
{
alert("Well done!");
}
$(document).on("submit", "#requestForm", function (event) {$.ajax({
url:"https://127.0.0.1:5500/insert.php",
type: "POST",
data:$(this).serialize(),
success:function(response)
{
alert("Well done!");
}
});
});
Try this Jquery Code.

Submitting post between ajax and php

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";
?>

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