unable to send complete data into database using ajax - php

i m using the following javascript to send the data into database
var x=document.getElementById("sortable").innerHTML;
alert(x);
var http=new XMLHttpRequest();
http.open("POST", "5.php?field="+x, true);
http.onreadystatechange = function()
{
if(http.readyState == 4 && http.status == 200)
{
alert(http.responseText);
}
}
http.send();
on php side i m using the following functions:
$l=$_GET['field'];
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("formdem", $con);
$sql="INSERT INTO rohit(content)VALUES('$l')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "<br/>&nbsp&nbsp&nbsp Your Form is now ready to be filled.....";
$rs= mysql_query("Select * from rohit where content='$l'");
if(mysql_num_rows($rs)!=0)
{
while($row = mysql_fetch_array($rs)) {
echo "<br/>Your unique id is ".$row['formid'];
}
}
but this code is not sending the complete data into database. what may be the reasons. in database i have taken field as longtext.
thnx

As your innerHTML is some HTML, it can't be simply added to make an URL. You can't do this :
http.open("POST", "5.php?field="+x, true);
You have to urlEncode x before :
http.open("POST", "5.php?field="+encodeURIComponent(x), true);

Related

ajax load data from php page and mysqli

I have a database that contains information for x variable. I want to have php page that load datafrom mysqli with ajax and my phpapi page. so
I create my database and it fills up every 1 minute.
I create a php page that load a data from mysqli and output with
this is my php page that load data from my mysqli and it working right
this is myphpapi.php page
<?php
$con = mysqli_connect("x.x.x.x","boob","booob");
if (!$con)
{
die('Could not connect: ' . mysqli_error());
}
mysqli_select_db($con,"sss");
$sql = "SELECT `x` FROM ddd order by id desc limit 1";
$result = mysqli_query($con,$sql);
$result = mysqli_fetch_assoc($result);
$output = json_encode($result);
echo $output;
mysqli_close($con);
?>
this part work well but I have another php page that contain ajax. When I push button, nothing happend
please help
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ajax test</title>
</head>
<body>
<h1>
this is ajax test
</h1>
<div id="main">
</div>
<button type="button" id="ajax_button">click me</button>
<script>
replaceText();
function replaceText() {
var target = document.getElementById("main");
var xhr = new XMLHttpRequest();
xhr.open('GET', 'myphpapi.php', true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 2) {
target.innerHTML = 'loading . . . .';
}
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText);
var json = JSON.parse(xhr.responseText);
target.innerHTML = json;
}
xhr.send();
}
}
var button = document.getElementById("ajax_button");
button.addEventListener("click",replaceText);
</script>
</body>
</html>
If you change the order a little within your ajax function and move the send method outside the onreadystatechange event handler it should work ~ though as pointed ut by #Barmar JSON.parse will return an object.
function replaceText() {
var target = document.getElementById("main");
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 2) {
target.innerHTML = 'loading . . . .';
}
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText);
var json = JSON.parse(xhr.responseText);
target.innerHTML = json;
}
}
xhr.open('GET', 'myphpapi.php', true);
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send();
}

HTML form data is not passed to the php file by ajax GET request

I am getting errors in creating a GET request to send the form data to the PHP file. What should I do?
function addDetails(str1,str2,str3,str4){
var xmlhttp=new XMLHttpRequest();
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("viewblock").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","addDetails.php?a="+str1+"&b="+str2+"&c="+str3+"&d="+str4,true);
xmlhttp.send();
}
str1 to str4 are the input field values(HTML) I send when calling addDetails().
My PHP code looks like this
$a = $_REQUEST["a"];
$b = $_REQUEST["b"];
$c = $_REQUEST["c"];
$d = $_REQUEST["d"];
$con=new mysqli_connect('localhost','root','');
if(!$con){
die('Connection Error : '.mysqli_error($con));
}
mysqli_select_db($con,"ajax_app");
$sql="INSERT INTO images(title,description,capturedate,image) VALUES ($a,$b,$c,$d)";
if(mysqli_query($con,$sql)){
alert("data added successfully");
}
else{
alert("failed to add");
}
?>
No change occurs when I'm executing this. And there is no error too.
Your probably getting errors on the php script. You can not call the alert() functions in PHP. Use echo instead. Then you will see the responses in your browsers console.
Your PHP code should look like this:
$a = $_REQUEST["a"];
$b = $_REQUEST["b"];
$c = $_REQUEST["c"];
$d = $_REQUEST["d"];
$con=new mysqli_connect('localhost','root','');
if(!$con){
die('Connection Error : '.mysqli_error($con));
}
mysqli_select_db($con,"ajax_app");
$sql="INSERT INTO images(title,description,capturedate,image) VALUES ($a,$b,$c,$d)";
if(mysqli_query($con,$sql)){
echo "data added successfully";
}
else{
echo "failed to add";
}
?>

MySQL query result doesn't show using AJAX

I have a database called opera_house with a table called room that has a field room_name and a field capacity. I want to show the room_name 's that have a capacity larger than the one entered by the user.
The Available Room text disappears, but my code only shows the MySQL query if I echo it, but I'm not sure if it is reaching to search the database.
This is my script code:
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
function showRoom(str) {
if (str === "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","ajax_events.php?q="+str,true);
xmlhttp.send();
}
}
This is my html:
<body>
<form>
<input type="text" name="room" onkeyup="showRoom(this.value)">
</form>
<br>
<div id="txtHint"><b>Available Room...</b></div>
</body>
This is my php:
<?php
include('dbconnect.php');
$q = intval($_GET['q']);
mysqli_select_db($connection,"opera_house");
$sql="SELECT room_name FROM room WHERE capacity >= '".$q."'";
echo $sql;
$result = mysqli_query($connection,$sql);
while($row = mysqli_fetch_array($result)) {
echo "<td>" . $row['room_name'] . "</td>";
}
?>
My php file is called ajax_events.php
And my dbconnect.php is one that I constantly use to connect to this database.
Would really appreciate some help!!
I propose an answer using jquery. You've embedded it in your question but you're not using it ...
Explanations : You call the following url ajax_events.php with the parameter "q" only if str is defined, otherwise it fills the selector txtHint with nothing.
AJAX
if (str != "") {
$.ajax({
type: 'GET',
url: 'ajax_events.php',
dataType: 'JSON',
data : {
q: str
}
}).done(function (data) {
$('#txtHint').text = data;
}).fail(function() {
alert('Fatal error');
})
} else {
$('#txtHint').text = '';
}
With this configuration, it is important to return result with echo json_encode in your server side code.
PHP
<?php
include('dbconnect.php');
$q = intval($_GET['q']);
mysqli_select_db($connection, "opera_house");
$sql = 'SELECT room_name FROM room WHERE capacity >= '.$q; // Some corrections
$result = mysqli_query($connection, $sql);
$return = '';
while($row = mysqli_fetch_array($result)) {
$return .= '<td>' . $row["room_name"] . '</td>';
}
echo json_encode($return); // Return Json to ajax
?>
While thinking of JS it's fine. I think the problems are in the php code. Try this one.
<?php
include('dbconnect.php');
$q = intval($_GET['q']);
mysqli_select_db($connection,"opera_house");
$sql="SELECT room_name FROM room WHERE capacity >= " . $q;
$result = mysqli_query($connection,$sql);
if (!$result) {
echo mysqli_error();
exit();
} // this is to do debugging. remove when you get it fixed
$ret = ""; //variable to hold return string
while($row = mysqli_fetch_array($result)) {
$ret .= "<td>" . $row['room_name'] . "</td>";
}
echo $ret;

MySQL delete row with AJAX and JSON failed

I try to DELETE a row in mysql. I got help to insert and it works well. I tried to use the same logic for delete one row with ID identification, but I can not delete the row.
What is wrong in this code?
...
Here is the full code:
Javascript:
function jsRecordDeleteWrite()
{
var jsObject = {
"ID": document.form_articles.ID.value
};
// ... the AJAX request is successful
var updatePage = function (response) {
alert("record successful deleted");
};
// ... the AJAX request fail
var printError = function (req, status, err) {
alert("deletingt record failed");
};
// Create an object to describe the AJAX request
$.ajax({
url : 'deletearticle.php',
dataType : 'json',
contentType: 'application/x-www-form-urlencoded',
data : jsObject,
type : 'POST',
success: updatePage,
error: printError
});
}
Here is deletearticle.php
<?php
$link = mysql_connect('localhost', 'admin0', 'star1star1star0');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db('sob', $link);
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
//read the json file contents
$ID = $_POST['ID'];
//delete item from mysql table
$sql = mysql_query("DELETE FROM articles WHERE ID=$ID");
if(!mysql_query($sql))
{
die('Error : ' . mysql_error());
}
//database connection close
mysql_close($link);
//}
?>
Verify that the server receives in php
var_dump($ID);
If query is right, check the mysql user has rights to update table
Put single quotes around $ID:
//delete item from mysql table
$sql = mysql_query("DELETE FROM articles WHERE ID= '$ID'");

PHP jQuery AJAX

Trying to pass data to the server but it keeps returning a "Parameter Missing"
So either the data is not being passed to the PHP script or I am doing something wrong.
Here is the jQuery:
function quickJob(obj) {
var quickJobNumber = $(obj).text();
//alert(quickJobNumber)
$.ajax({
type: "GET",
url: "quickJobCB.php",
data: quickJobNumber,
success: function(server_response)
{
$("#message").removeClass().html(server_response);
}
});
}
Ok....when tracing the issue I created an alert as seen below. The alert is producing the expected results.
Here is the PHP script:
<?php
require_once("models/config.php");
// Make the connection:
$dbc = #mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if (!$dbc) {
trigger_error('Could not connect to MySQL: ' . mysqli_connect_error());
}
if (isset($_GET['quickJobNumber'])) {
$quickJobNumber = trim($_GET['quickJobNumber']);
$quickJobNumber = mysqli_real_escape_string($dbc, $quickJobNumber);
$query = "SELECT * FROM projects WHERE projectNumber = '" . $quickJobNumber . "'";
$result = mysqli_query($dbc, $query);
if ($result) {
if (mysqli_affected_rows($dbc) != 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo $row['projectName'];
}
} else {
echo 'No Results for :"' . $_GET['quickJobNumber'] . '"';
}
}
} else {
echo 'Parameter Missing';
}
?>
<?php include("models/clean_up.php"); ?>
data: quickJobNumber,
should be
data: { 'quickJobNumber': quickJobNumber },
You'll need to pass the data either as a query string like so
data: "quickJobNumber="+quickJobNumber,
or a map like so
data: data { quickJobNumber: quickJobNumber },
If you want to use the GET request, use $.get
$.get("/get_request.php", { quickJobNumber: "myAjaxTestMessage"},
function(data){
console.log("WOW! Server was answer: " + data);
});
In php
<?php
if(isset($_GET['quickJobNumber'])){
header('Content-Type: application/json; charset=utf-8');
echo json_encode(array('answer'=>'Hello user!'));
}
?>
If you want to use the POST request, use $.post
$.post("/post_request.php", { quickJobNumber: "myAjaxTestMessage"},
function(data){
console.log("WOW! Server was answer: " + data);
});
In php
<?php
if(isset($_POST['quickJobNumber'])){
header('Content-Type: application/json; charset=utf-8');
echo json_encode(array('answer'=>'Hello user!'));
}
?>
P.S. or you can use $_REQUEST in php.

Categories