I am a beginner, I unable to get the result from the database through ajax call in my PHP code.
Here is the sample php code with an ajax call.
<script>
$('.input').on('click',function(e){
e.preventDefault();
$.ajax({
method:'POST',
url:'',
data:{data_username:$('#username').val(),
data_lastname:$('#lastname').val()},
success:function(data){
var x =JSON.parse(data);
for(var index in x){ //here my error
console.log(x[index].username);
}
}
,error:function(){
alert("failed!!!!!");
}
});
});
</script>
Looking at the code you posted suggests that you are sending the ajax request to the same page which leads me to think that the error you are receiving is because there is other HTML content all mashed up with the JSON content that you want. To prevent this from happening eithe rsend the request to a different page or use ob_clean before you begin sending the ajax query response and ensuring that the script finishes at the point of sending the data. Perhaps the following might help.
There is also a spelling mistake $usernmae should be $username!
<?php
$use_live_db=false; # set to true to try running sql queries against db
if( isset( $_POST['data_username'], $_POST['data_lastname'] ) ){
/*
when sending ajax to the same page you must ensure that ONLY the
data you want is allowd to be sent - so using `ob_clean()` will
discard any previously generated content from appearing in the
output
*/
ob_clean();
/*
I appreciate this is probably for testing but this is
simply yielding data you already know...
*/
$username=$_POST['data_username'];
$lastname=$_POST['data_lastname'];
$sql='SELECT username, lastname FROM login where username=:one AND lastname=:two';
$results=array(
'username' => $username,
'lastname' => $lastname,
'sql' => $sql
);
if( $use_live_db ){
/* !!! CHANGE THIS TO THE APPROPRIATE FILE FOR YOUR SYSTEM !!! */
require '/path/to/db-pdo.php';
$results=array();
$stmt=$db->prepare( $sql );
if( $stmt ){
# think it should be bindParam rather than bindparam!
$stmt->bindParam(':one',$username,PDO::PARAM_STR);
$stmt->bindParam(':two',$lastname,PDO::PARAM_STR);
$stmt->execute();
while( $row=$stmt->fetch() ){
$results[]=$row;
}
}else{
exit('error: failed to prepare sql query');
}
}
/*
Similarly to using `ob_clean()` you must prevent the remainder of
the current page appearing as part of the ajax response -
so use `exit` or `die`
*/
header('Content-Type: application/json');
exit( json_encode( $results ) );
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>jQuery & AJAX - POST request to PHP script to interrogate db</title>
<script src='//code.jquery.com/jquery-latest.js'></script>
</head>
<body>
<form>
<input type='text' id='username' name='username' value='mike' />
<input type='text' id='lastname' name='lastname' value='hunt' />
<input type='button' class='input' value='OK' />
</form>
<script>
$('.input').on('click',function(e){
e.preventDefault();
$.ajax({
method:'POST',
url:location.href,
/*
If you set the dataType
properties jQuery automagically ensures
the response is in the correct format- JSON
*/
dataType: 'json',
data:{
data_username:$('#username').val(),
data_lastname:$('#lastname').val()
},
success:function( json ){
console.info('username: %s\nlastname: %s\nSQL: %s', json.username, json.lastname, json.sql )
alert('ok')
},
error:function(){
alert('failed!!!!!');
}
});
});
</script>
</body>
</html>
Related
I have an html form, and an ajax script that sends it without refreshing the page, I also have a check that two identical post dates do not get into the database, but when I click on submit, it still writes "form was submitted", help me fix it
Here is my script
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('#my_form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '/main/store',
data: $('#my_form').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
</script>
</head>
Without knowing the data you send in the ajax request or how you process the request at the server you will need to adapt the following semi-pseudo code to suit your needs or simply design your own solution using some of this.
Essentially the ajax callback should receive data from the server. In your code the callback has no arguments supplied - add a variable in success: function () {... similar to success: function(r) {... so the response from the server is now assigned to r
With that response you can now display a different message to the user based upon the value of r.
For instance:
<?php
/****************
/main/store
*/
if( $_SERVER['REQUEST_METHOD']=='POST' ){
require 'dbconn.php';
/* example pseudo function to test date */
function date_is_duplicate( $date ){
global $db; // your db connection variable
$sql='select * from `TABLE` where `DATEFIELD`=?';
$stmt=$db->prepare( $sql );
$stmt->bind_param('s',$date);
$stmt->execute();
$stmt->store_result();
$rows=$stmt->num_rows;
$stmt->free_result();
$stmt->close();
/*
..... etc, etc, etc and return a value to be used in ajax callback
If there are ZERO rows send ZERO as response - or more than ZERO means duplicate
*/
return $rows;
}
/* Do the Duplicate Date search tests */
$result=date_is_duplicate( $_POST['date'] );
if( $result ) exit( $result );
else{
/*
do other exciting things - add to db etc etc but SEND a response to the
ajax callback so that it can display the correct message.
send ZERO as response.
*/
}
}
?>
And then, the modified javascript that has a response variable that helps fork the program logic:-
$(function(){
$('#my_form').on('submit', function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url: '/main/store',
data: $('#my_form').serialize(),
success:function(r) {
let message='OK, form was submitted';
if( Number(r)===1 )message='Bogus, duplicate date detected';
alert(message);
}
});
});
});
A far more robust data structure to send back would be JSON rather than a single integer - this was hastily cobbled together to illustrate the concept. With JSON you can design greater complexity into the solution
I have a html page with jQuery and I used ajax to send data to the a php file to save the data.
I have seen other questions like this but none of them seemed to match my purpose.
The data is an iframe's srcdoc.
My html looks like this:
<iframe srcdoc="<h1>hello</h1>" id="iframe"></iframe>
<br />
<input type="text" placeholder="Filename to save as..." id="fn">
<input type="button" value="Save" onclick="saveDoc(document.querySelector('#fn').value)">
My jQuery and JS looks like this:
function saveDoc(e) {
let iframe = document.querySelector("#iframe");
let data = {"srcdoc": iframe.srcdoc, "lnk": e};
$.ajax({
type: "POST",
url: "saver.php",
dataType : "text",
contentType: "application/json",
data: data,
cache: false,
timeout: 3000,
success: function (data) {
alert("SUCCESS");
console.log(data);
},
error: function (e) {
alert(e);
}
});
}
And my php code looks like this:
<!doctype html>
<html>
<body>
<?php
if (isset($_POST["lnk"]) && isset($_POST["srcdoc"])) {
$myfile = fopen($_POST["link"], "w");
fwrite($myfile, $_POST["srcdoc"]);
fclose($myfile);
echo $_POST["lnk"];
echo "\n <br/>";
echo $_POST["srcdoc"];
} else {
echo "Error";
}
?>
</body>
</html>
When I run it, I get an alert message saying "SUCCESS". And the console.log gives me:
<!doctype html>
<html>
<body>
Error</body>
</html>
What is happening here, and what am I doing wrong?
contentType: "application/json"
You are explicitly sending this to the server as JSON - so you can not access it via $_POST. (PHP only populates $_POST for Content-Types application/x-www-form-urlencoded or multipart/form-data.)
Either remove contentType, so that it can fall back to the normal way of sending form data, or go read up on how to actually read POSTed JSON data in PHP. (That would involve reading the data from php://input first, see Receive JSON POST with PHP)
I assume i am doing something really simply wrong here (to all you seasoned programmers), but forgive me i have spent hours and hours reading trying to understand how AJAX calls work...
My variables aren't making it to recordsale.php to be inserted into SQL table.
The javascript variables are displayed on the HTML page, so i know they contain data.
Can anyone offer some advice?
(any response knocking my ability will not be appreciated - I AM TRYING :) )
My form submit button in html looks like this
<form action="recordsale.php" method="post">
<input type="image" src="assets/CompleteSale.png" alt="Submit"> </form>
My AJAX Post Function:
$( "#submit" ).submit(function( event ) {
alert("hello");
// Jquery code for making AJAX call to server side script
$.ajax({
method: "POST",
url: "recordsale.php",
data: { adultqty: adultticketqty, concessionqty: concessionticketqty, studentqty: studentticketqty, childqty: childticketqty, programqty: programqty, totalsell: totalsaleprice }
})
//alert(adultqty + childqty)
});
Recordsale.php
<?php
$adultticketqty = $_POST['adultqty'];
$concessionticketqty = $_POST['concessionqty'];
$studentticketqty = $_POST['studentqty'];
$childticketqty = $_POST['childqty'];
$programqty = $_POST['programqty'];
$totalsaleprice = $_POST['totalsell'];
//include('phpsqlget.php');
/* Attempt MySQL server connection. Assuming you are running MySQL server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "speedway", "speedwayticketsales");
// Check connection
if($link === false){ die("ERROR: Could not connect. " . mysqli_connect_error()); } // Attempt insert query execution
$sql = "INSERT INTO stdsalesrecords (qtyadulttickets, qtyconcessiontickets, qtystudenttickets, qtychildtickets, qtyprograms, totalsell) VALUES ($adultticketqty,$concessionticketqty,$studentticketqty,$childticketqty,$programqty,$totalsaleprice)";
if(mysqli_query($link, $sql)){
echo "Records inserted successfully."; }
else{ echo "ERROR: Could not able to execute $sql. "
. mysqli_error($link); } // Close connection mysqli_close($link);
?>
This is how i usually do my ajax submissions. there are other ways of handling form submission.
Check out $(form).serialize() amongst others.
$( "#submit" ).submit(function( event ) {
var adultticketcty = $('selector').val();
//continue filling out the fields and mirror them in the below dataString.
var dataString = 'adultqty='+adultticketcty+'&concessionqty='+concessionticketqty;
//Check if you set the correct values in the datastring.
console.log(dataString);
$.ajax({
type: "POST",
url: "recordsale.php",
data: dataString,
success: function(data){
//check whatever is returned from recordsale.php
console.log(data);
}
});
});
then in your recordsale.php do this to see if anything is returned in your ajax success call:
$adultticketqty = $_POST['adultqty'];
$concessionticketqty = $_POST['concessionqty'];
echo $adultticketqty;
Not related to the question, but i wanna recommend checking out pdo queries to prevent sql injections etc.
solved my issue
had to write a function to write my JS Variables into hidden elements in the form
function save()
document.getElementById("qty").value = Aqty;
then add the hidden elements to my form
<form method="post" name="submit" id="submit" action="record.php" >
<input type="hidden" id="qty" name="qty" value="" >
<input type="submit" value="Submit" onclick="save();">
works a treat!
I have a web application where I need to get values from a MySQL database.
The series of event is as follows:
PHP code creates HTML page (works fine)
Click a button on the page, updating a cookie (works fine)
Use cookie in a MySQL query (This does not work)
Get a record from the above MySQL query result and pass to HTML page with jQuery
The problem with bullet 3 is that the MySQL query is only run when I load the page (of course). But I need a method to run a query, based on user input (stored as the cookie), without reloading the PHP script.
How can this be done?
My engineering c-coding brain has a really hard time wrapping this ajax thing. Here is the code so far, still not working:
The popup(HTML) I want to update with new strings when a button on the same page, is clicked:
<div id="popup" class="popup" data-popup="popup-1">
<div class="popup-inner">
<h2 id="popup-headline"></h2> //Headline, created from a cookie. Could be "Geography"
<div id="dialog"></div> //From Will's suggestion
<p id="question"></p> //String 1 from online MySQL DB goes here "A question in Geography"
<p id="answer"></p> //String 2 from online MySQL DB goes here "The answer to the question"
<p class="popup-small-button"><a data-popup-close="popup-1" href="#"><br>Close</a></p> // Hides the popup
<a class="popup-close" data-popup-close="popup-1" href="#">x</a>
</div>
</div>
Then i have my file with custom functions. It executes whenever the popup is shown:
<script>
jQuery(function() {
jQuery('[data-popup-open]').on('click', function(e) {
function myfunction(myparams) {
// your logic here: testing myparams for valid submission, etc.
alert("hey");
jQuery.ajax({
type: 'post',
url: 'server.php',
data: {
my_var1: 'question',
my_var2: 'answer'
},
success: function(data) {
data = JSON.parse(data);
jQuery('#question').html(data["question"]);
jQuery('#answer').html(data["answer"]);
},
error: function(jqxhr, status, exception) {
alert('Exception:', exception);
}
});
}
});
});
</script>
My server.php file contains now this:
<?php
require("db.php");
if(isset($_POST['my_var1']) && isset($_POST['my_var2'])) {
myfunction($_POST['my_var1'], $_POST['my_var2']);
}
?>
And my db.php contains this:
<?php
function myfunction($var1, $var2) {
$db = mysqli_connect('MyOnlineSQLPath','username','password','database1_db_dk');
$stmt = $db->prepare("SELECT question, answer FROM t_da_questions WHERE category_id=?;");
$stmt->bind_param("s", $_COOKIE('category'));
$stmt->execute();
$retval = false;
if($result->num_rows > 0) {
$row = $result->fetch_assoc();
if(!is_null($row['question']) && !is_null($row['answer'])) {
$retval = new stdClass();
$retval->question = row['question'];
$retval->answer = row['answer'];
}
}
mysqli_close($db);
return $retval;
}
?>
What I need, is the "question" and "answer" from the SELECT query.
TL;DR I need question and answer strings to go into <p id="question"></p> and <p id="answer"></p> in the HTML, both without refreshing the page. The getCookie('category') is a cookie stored locally - It contains the last chosen category for a question. The function getCookie('category') returns an integer.
Let me know if you need any more info on this.
Here is some template AJAX that may help you out. I used this in another project. This won't require a page refresh. You will have to include the code to send your cookie's data in the 'data' section.
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<meta charset="utf-8">
</head>
<body>
// your HTML here
<script>
<div id="dialog"></div>
function myfunction(myparams) {
// your logic here: testing myparams for valid submission, etc.
$.ajax({
type: 'post',
url: 'myphpfile.php',
data: {
my_var1: 'myval',
my_var2: 'myval2'
},
success: function(data) {
$("#dialog").html("<span>Success!</span>");
$("#dialog").fadeIn(400).delay(800).fadeOut(400);
}
});
}
</script>
</body>
</html>
Then in the file 'myphpfile.php', you'll have code like the following:
<?php
require("../mycodebase.php");
if(isset($_POST['my_var1']) && isset($_POST['my_var2'])) {
myfunction($_POST['my_var1'], $_POST['my_var2']);
}
?>
Finally, in mycodebase.php (which is stored in a place inaccessible to the public/world), you'll have a function that actually runs your query and returns your result:
function myfunction($var1, $var2) {
$db = mysqli_connect('localhost','myuser','mypass','dbname');
$stmt = $db->prepare("UPDATE mytbl SET col1=? WHERE col2=?;");
$stmt->bind_param("ss", $var1, $var2);
$stmt->execute();
$result = (($db->affected_rows) > 0);
mysqli_close($db);
return $result;
}
UPDATE
That function above is to run an UPDATE query, so the result returned just indicates whether you successfully updated your data or not. If you want to return an actual result, you have to extract the result from the query as follows:
function myfunction($cat) {
$db = mysqli_connect('localhost','myuser','mypass','dbname');
$stmt = $db->prepare("SELECT question, answer FROM t_da_questions WHERE category_id=?;");
$stmt->bind_param("s", $cat);
$stmt->execute();
$retval = false;
if($result->num_rows > 0) {
$row = $result->fetch_assoc();
if(!is_null($row['question']) && !is_null($row['answer'])) {
$retval = new stdClass();
$retval->question = row['question'];
$retval->answer = row['answer'];
}
}
mysqli_close($db);
return $retval;
}
Then your server.php file will look like:
<?php
require("db.php");
if(isset($_COOKIE['category'])) {
json_encode(myfunction($_COOKIE['category']));
}
?>
Here's the JS:
jQuery('[data-popup-open]').on('click', function(e) {
function myfunction(myparams) {
// your logic here: testing myparams for valid submission, etc.
alert("hey");
jQuery.ajax({
type: 'post',
url: 'server.php',
// data section not needed (I think), getting it from the cookie
success: function(data) {
data = JSON.parse(data);
jQuery('#question').html(data["question"]);
jQuery('#answer').html(data["answer"]);
}
});
}
});
This is untested -- I may have gotten an argument wrong, but this is at least very close if it's not already there.
I am new to AngularJs. I was trying to create a simple application using angularjs.
In a simple application i am not able to print posted data via $_POST, $_GET or$_REQUESTin my php script.
While usingfile_get_contents("php://input")` i am able to print data.
Can any one let me know why $_GET, $_POST and $_REQUEST are not working?
My Index.html Code :
<!DOCTYPE html>
<html ng-app>
<head>
<title>Search form with AngualrJS</title>
<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css" />
<script src="http://code.angularjs.org/angular-1.0.0.min.js"></script>
<script src="search.js"></script>
</head>
<body>
<div ng-controller="SearchCtrl">
<form class="well form-search">
<label>Search:</label>
<input type="text" ng-model="test" class="" placeholder="Keywords...">
<button type="submit" class="btn" ng-click="search()">Search</button>
<p class="help-block">Try for example: "php" or "angularjs" or "asdfg"</p>
</form>
<pre ng-model="result">
{{result}}
</pre>
</div>
</body>
</html>
search.js code :
function SearchCtrl($scope, $http) {
$scope.url = 'search.php'; // The url of our search
// The function that will be executed on button click (ng-click="search()")
$scope.search = function() {
// Create the http post request
// the data holds the keywords
// The request is a JSON request.
$http.post($scope.url, { "data" : $scope.test}).
success(function(data, status) {
$scope.status = status;
$scope.data = data;
$scope.result = data; // Show result from server in our <pre></pre> element
})
.
error(function(data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
});
};
}
Search.php Code :
<?php
// The request is a JSON request.
// We must read the input.
// $_POST or $_GET will not work!
$data = file_get_contents("php://input");
$objData = json_decode($data);
// perform query or whatever you wish, sample:
/*
$query = 'SELECT * FROM
tbl_content
WHERE
title="'. $objData->data .'"';
*/
// Static array for this demo
$values = array('php', 'web', 'angularjs', 'js');
// Check if the keywords are in our array
if(in_array($objData->data, $values)) {
echo 'I have found what you\'re looking for!';
}
else {
echo 'Sorry, no match!';
}
Any assistance will be appreciated.
To go along with my comment about a possibility of a bad setting in php.ini, this article(dead link) (linked through this one, from my comment) also offered this quote:
If the Content-Type is empty or not recognized in the HTTP message then the PHP $_POST array is empty. Not sure if this is a bug or is by design…
The symptoms being the same, (empty $_POST but data available through php://input), this brings up the number of possible reasons this error is occurring to two:
Syntax error in php.ini post_max_size setting
Bad value or empty Content-Type header being sent from the front-end
If your setting for post_max_size is correct, then it could be that angular is removing the Content-Type header for the post. According to this question and this question, angular will remove the Content-Type header if there is no payload or an empty payload going along with any request, which I believe is your issue.
Try adding this in your SearchCtrl:
function SearchCtrl($scope, $http) {
$scope.url = 'search.php'; // The url of our search
$scope.test = {test:'test'}; // Add me
// ...
I suspect your $_POST array will become filled, since there will now be a Content-Type header being sent along with the request, and actual request data being sent. If that works, it means that your test input isn't binding correctly to the scope, or you're submitting empty data. Try adding a guard clause before the HTTP Request:
if($scope.test) {
$http.post($scope.url, { "data" : $scope.test})
// ...