Add a record to the database without refreshing - javascript

I want to add a record dynamically.
When I insert action = "add.php" for my form, the addition is accomplished by displaying a message after refreshing.
I want to add this addition without refreshing dynamically.
Also, for the ID of my games, I want that when I delete a record, for the ID to be decremented or removed. So that, when I add a game again, it uses the next ID available, not keeps on incrementing, like it is happeneing with me now.
If I take off add.php from action, nothing happens and the game isn't added.
My question is, where is this script broken? Or if add.php is not functioning right?
Here is my index.php and add.php
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>title</title>
</head>
<body>
<?php
include("dbconfig.php");
$sql = "SELECT * FROM games";
$result = mysql_query($sql);
while ($record = mysql_fetch_array($result)){
echo "<p class=\"p" .$record['ID']. "\"></br> Game ID: " .$record['ID']. "</br> Game Name: " .$record['Name'].
"<br /> Game Type: ".$record['Type']. "<br /> Rating: ".$record['Rating']."<br /> Year Released: ".$record['Release Year']."<br /> <br />" ?>
<img src="trash.png" alt="delete"/> </p>
<?php
}
?>
<form name="add" id ="add" action="" method="post">
<input class ="gameID" type="hidden" id="ID" name="ID" value = " ' .$record['ID'] . ' " />
<b>Game Name: </b> <input type="text" id="name" name="name" size=70>
<b>Game Type:</b> <input type="text" id="type" name="type" size=40>
<b>Rating: </b> <input type="number" id="score" name="score" min="1.0" max="10.0" step ="0.1"/>
<b>Year Released: </b> <input type="number" min="1900" max="2011" id="Yreleased" name="Yreleased" value="1985" size=4>
<p><input type="submit" name="Submit" id = "Submit" value="Add Game" class = "add games"></p>
</form>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type = "text/javascript">
$(document).ready(function(){
$("#add").submit(function(){
var name = this['name'].value;
var type = this['type'].value;
var rating = this['score'].value;
var release = this['Yreleased'].value;
var dataString = 'name='+ name + '&type=' + type + '&rating=' + rating + '&release=' + release;
if (name == '' || type == '' || rating == '' || release == ''){
alert("please enter some valid data for your game entry");
}else
$.ajax({
type: "POST",
url: "add.php",
data: dataString,
success: function(){
window.location.reload(true);
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
return false;
}
)});
</script>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type = "text/javascript">
$(document).ready(function(){
$("a.deletebutton").click(function(){
var del_id = $(this).attr("id");
var info = 'id=' + del_id;
var parent = $(this).parent();
if(confirm("Sure you want to delete this game? !..There is no Undo")){
$.ajax({
type: "get",
url: "delete.php?" + info,
context: document.body,
success: function(){
$('.p'+del_id).html('deleted');
$('.success').fadeIn(200).show();
}
});
}
return false;
});
});
</script>
</body>
</html>
add.php
<?php
require('dbconfig.php'); //we cannot continue without this file, thats why using require instead of include
if(isset($_POST['name']))
{
$name=addslashes($_POST['name']);
$type=addslashes(($_POST['type']));
$rating=addslashes($_POST['rating']);
$release=addslashes($_POST['release']);
$sql = 'INSERT INTO `games` (`Name`,`Type`,`Rating`,`Release Year`) VALUES ("'.$name.'", "'.$type.'", "'.$rating.'", "'.$release.'")';
mysql_query( $sql);
if(!mysql_errno())
echo " your game has been added to the list of games. ";
}
?>

What your code is currently trying to do is the right principle: you are trying to trap the submit event on the form, make your Ajax request instead, and then cancel the default submit.
The reason it doesn't work is this line:
$("add games").Submit(function(){
".submit()" should have a lowercase "s", and the selector you are using, "add games", is not going to return any elements because it looks for elements with the tag name "games" that are descendents of elements with tag name "add".
What you want to do is fix the case of the "s", and select your element by id, which you do with "#yourid". Your form name has the id "add", so do this:
$("#add").submit(function(){
Also both your document.ready and your submit handler functions have an extra pair of {} curly braces around their bodies so you should delete those:
$("#add").submit(function(){
{ // <- delete this {
/*function body code*/
} // <- delete this }
});
Also you are including the jquery.js script twice - once is enough. And you don't need two document.ready handlers, you can combine them into a single one (though you can have more than one and that shouldn't cause a problem).
(There may be some other issues, but try this first and get back to us.)
UPDATE: After the other fixes, I suspect the problem is now in your PHP, in the line:
if(isset($_POST['Submit']))
I don't know PHP, but I assume this is checking for a request parameter called 'Submit' that you are not setting in your JS (it was the name of your submit button and would've been set for a "standard", non-Ajax submit, but it won't be included in your Ajax request). Try changing that line to use a request parameter that you are setting, like:
if(isset($_POST['name']))
Then, even if you don't seem to get a response in the browser, check your database to see if records are being added.

Make a few changes:
$("add games").submit(function(){ }); -> $(".add games").Submit(function(){});
or
$("#add").submit(function(){}); or $("#add").click(function(){ //run your ajax script here});
as for the id issue, MySQl will keep incrementing the id and if you delete one, it won't decrement it. May I know why you want the ids in order?
Editing again: (Use json.js)
here is another workaround:
var postdata = new Object();
postdata.name = value;
postdata.type = value;
postdata.rating = value;
//and so on
$.ajax({
url: 'your url',
type: "POST",
contentType: "application/json; charset=utf-8", //add this
data: JSON.stringify(postdata), //another change
dataType: "json",
success: function(data, st) {
if (st == "success") {
alert('Data Added');
}
},
error: function() {
alert("Failed!");
}
});

Aside from the problems everyone else helped with, your form is still submitting because of this line:
if (id =='' || name == '' || type == '' || rating == '' || release == ''){
You did not define id in the code above it. This is causing the function to throw an exception before return false is called. You need to either remove id =='' || from your if-statement or define it in your function.
As a side note, I see that you are pulling data from the form using the following:
var name = $("#name").val();
var type = $("#type").val();
Inside the submit handler, this is the form object, meaning you can access form fields by name. I would recommend using the following properties:
var name = this['name'].value,
type = this['type'].value;
This way, you don't need IDs on your form fields and you could if necessary insert the same form multiple times in the document.
Also, you should be validating your form input. A user could enter "); DROP TABLE games;// or <script src='http://evil.com/bad.js'></script> in any of your fields and really ruin your life.

Related

My php code is not updating my database

I have been trying everything to get this to work. When I hit the submit button nothing happens. It just sits there.
I have the html calling to a javascript that sends the data to a php file so that the webpage won't refresh. I just need a message to show up saying "success" and the database to update.
But when I hit submit, it doesn't update the database, and the success messages don't show up. I have checked this over and over. Am I calling them improperly? Please help!
function passData() {
//getting values from HTML
var title= $("#title").value;
var year= $("#year").value;
var director= $("#director").value;
var genre= $("#genre").value;
var runtime= $("#runtime").value;
if (title == '' || year == '' || director == '' || genre == '' || runtime == '') {
alert("Please fill all fields");
} else {
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "insert_DVD.php",
data: {
title1: title,
year1: year,
director1: director,
genre1: genre,
runtime1: runtime},
cache: false,
success: function(html) {
alert(html);
}
});
}
return false;
}
<?php
//getting values from JS
$title = $_POST['title11'];
$year = $_POST['year1'];
$director = $_POST['director1'];
$genre = $_POST['genre1'];
$runtime = $_POST['runtime1'];
$title = addslashes($title);
$director = addslashes($director);
$year = addslashes($year);
$genre = addslashes($genre);
$runtime = addslashes($runtime);
//connecting to server
$connection = mysql_pconnect($host,$user,$pass);
if (!($db = mysql_select_db($database)))
echo "<p> could not connect to database </p><br>");
//open database
if(!mysql_select_db($table,$db))
echo "<p> could not open collection database </p><br>");
//insert query
if (isset($_POST['title1'])) {
$query = "INSERT INTO `collection` (`title` , `year` , `director` , `genre` , `runtime` ) VALUES ('$title', '$year', '$director', '$genre', '$runtime')";
if(!$results = mysql_query($query, $db){
print("<p> could not excute query </p>");
} else {
echo "succuess";
}
}else {
echo "Something went wrong";
}
//close connection
mysql_close($connection);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>test</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="refreshForm.js"></script>
<link rel="stylesheet" href="webpage.css">
</head>
<body class="subStyle">
<form id="form" method="post">
If there is more than one director, seperate with comma.
<table border=0>
<tr>
<th>Movie Title</th>
<th>Year Made</th>
<th>Director</th>
<th>Genre</th>
<th>Runtime(Minutes)</th>
</tr>
<tr>
<td><input type=text name="title" id="title" maxlength=100 size=30></td>
<td><input type=text name="year" id="year" maxlength=4 size=10></td>
<td><input type=text name="director" id="director" maxlength=100 size=30></td>
<td><input type=text name="genre" id="genre" maxlength=20 size=20></td>
<td><input type=text name="runtime" id="runtime" maxlength=4 size=20></td>
</tr>
<tr><td>
<input type="submit" id="submit" name="submit" onclick="passData();" value="Update Database"></td></tr>
</table>
</form>
<div id="results">
<!-- All data will display here -->
</div>
</body>
</html>
My answer is based on the assumption that your Javascript function passData() is inside the file refreshForm.js.
There's a few issues here.
The Javascript function cannot be called because it's declared in another file
Each .js file has its own scope. The easiest way to fix this is to assign the passData() function to the global scope. This is the quickest way but do note that there are much better ways like export.
Calling the Javascript function from onclick does not prevent the entire form from submitting
Your function gets called, but then Javascript continues with the form submission since that's the default behaviour of a submit button. You will need some way to tell Javascript to prevent this default action from happening.
// refreshForm.js
window.passData = function (e) { // <-- Assign passData to the global scope
e.preventDefault(); // <-- Tell Javascript to prevent the default action of form submission
//getting values from HTML
var title= $("#title").value;
var year= $("#year").value;
var director= $("#director").value;
var genre= $("#genre").value;
var runtime= $("#runtime").value;
if (title == '' || year == '' || director == '' || genre == '' || runtime == '') {
alert("Please fill all fields");
} else {
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "insert_DVD.php",
data: {
title1: title,
year1: year,
director1: director,
genre1: genre,
runtime1: runtime},
cache: false,
success: function(html) {
alert(html);
}
});
}
return false;
};
Next, change your onclick handler in your HTML to onclick="return passData(event);"

jQuery / ajax data container + organization

My dad and I are working on a project where we'd like to create a script that calls in data when a number is submitted into a form. For example, when you type in your ID number then press ENTER or SUBMIT, the form will print/display information. This is a project for school, so when a student submits their ID number it will read their first period class, for example.
I have the following script code to set up the form:
<form id="firstPeriod" action="firstPeriod.html">
<p>Find your first period.</p>
<p><label>Student no.: <input type="text" name="studentNo"></label></p>
<p><input type="submit" value="Find it"></p>
<p id="result"></p>
</form>
<script type="text/javascript">
$(function() {
$('#firstPeriod').submit(function() {
$.ajax({ // Send the request behind the scenes
url: $(this).attr('action'), // Send it here
data: $(this).serialize(), // With this student no.
success: function(data) {
$('#result').html(data); // Display the resulting HTML
},
error: function(jqxhr, status, error) {
console.log(error);
$('#result').html('No results found. Please check your number and reenter'); // Notify an error
}
});
return false; // Prevent the normal form submission
});
});
My question is, what would be the best way to organize the data? An array, HTML, etc.? There are quite a lot of ID numbers and are currently set up in an HTML table, but that doesn't seem to work in calling the information. And I'd like for the data to be specific. So when a specific ID number is typed in, it reads a specific answer. Right now my problem is when I type in a number it reads several classes.
If there are any suggestions/advice/other posts that could help me, I'd be grateful. I have solid HTML, CSS experience but I'm still learning JS and jQuery so this is a little new for me. Thanks!
Edit, Updated
Note, added value attribute to input type="text" element
<input type="text" name="studentNo" value="" />
substituted .submit() for .on("click") at input type="submit" element
Two possible approaches could be 1) using HTML to store data, .load() to retrieve fragment identifier within html file; or 2) storing data using JSON, retrieving file using php
html at firstPeriod.html
<div id="0">data 0</div><div id="1">data 1</div>
javascript
$(function() {
var form = $("#firstPeriod");
$("input[type=submit]").on("click", function(event) {
event.preventDefault();
event.stopPropagation();
var data = form.serializeArray();
// where `data[0].value` is `id`; e.g.; `0`
var id = data[0].value;
$("#result").load(form.attr("action") +" #"+ id)
})
})
plnkr http://plnkr.co/edit/4onHf9jlJTyDei1zo9IC?p=preview
JSON
0.json
{
"0":"<div id='0'>data 0</div>"
}
1.json
{
"1":"<div id='1'>data 1</div>"
}
javascript
$(function() {
var form = $("#firstPeriod");
$("input[type=submit]").on("click", function(event) {
event.preventDefault();
event.stopPropagation();
var data = form.serializeArray();
// where `data[0].value` is `id`; e.g.; `0`
var id = data[0].value;
$.post("data.php", {id:id}, function(result) {
$("#result").html(result[id])
}, "json")
})
})
php
<?php
if (isset($_POST["id"])) {
$id = $_POST["id"];
$file = $id . ".json";
if (file_exists($file)) {
$jsondata = file_get_contents($file);
$id_data = json_decode($jsondata, true);
echo json_encode($id_data);
};
}

Unsolved PHP page refreshing without Ajax

Please, can somebody publish a mistakes corrected and tested code for my problem?
Program does - 22.php has the form. When the user enter and click Submit button, the result should be taken from 23.php and displayed in div on 22.php
I already tried solutions below and none of them solve my problem;
1) I changed to: $("#testform").submit(function(event){
2) I included "return false;" at the end to prevent it to actually submit the form and reload the page.
3) clear my browser cache
I can see what happen the program with my computer;
1) I do not get error message after I click submit.
2) I can see the tab of the page reloads quickly and the entered text fields are cleared.
3) No error message or result shows.
<html>
<head>
<title>My first PHP page</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#btn").click(function(event){
event.preventDefault();
var myname = $("#name").val();
var myage = $("#age").val();
yourData ='myname='+myname+'&myage='+myage;
$.ajax({
type:'POST',
data:yourData,//Without serialized
url: '23.php',
success:function(data) {
if(data){
$('#testform')[0].reset();//reset the form
$('#result').val(data);
alert('Submitted');
}else{
return false;
}
};
});
});
});
</script>
</head>
<body>
<form method="post" id="testform">
Name:
<input type="text" name="name" id="name" />Age:
<input type="text" name="age" id="age" />
<input type="submit" name="submit" id="btn" />
</form>
<div id='result'></div>
</body>
</html>
<?php
if ( isset($_POST['name']) ) { // was the form submitted?
echo "Welcome ". $_POST["name"] . "<br>";
echo "You are ". $_POST["age"] . "years old<br>";
}
?>
you don't need to change your php code
try submit form with submit event ...
$("#testform").submit(function(event){
use `dataType:json`; in your ajax ..
yourData =$(this).serialize();
Your php
<?php
if ( isset($_POST['name']) ) { // was the form submitted?
$data['name']= 'welcome '.$name;
$data ['age']= 'you are '.$age;
print_r(json_encode($data));exit;
}
?>
Now In Your Success function
var message = data.name + ' ' + data.age;
$('#result').html(message );
You are sending myname and checking name(isset($_POST['name']) in php.
don't use .value() use .html() for data rendering. and console log the data and see whats request and response using firebug.
Can you try this one?
To be changed
var yourData ='name='+myname+'&age='+myage; // php is expecting name and age
and
$('#result').html(data); // here html()
the code becomes
$(document).ready(function() {
$("#btn").click(function(event){
event.preventDefault();
var myname = $("#name").val();
var myage = $("#age").val();
var yourData ='name='+myname+'&age='+myage; // php is expecting name and age
$.ajax({
type:'POST',
data:yourData,//Without serialized
url: '23.php',
success:function(data) {
if(data){
$('#testform')[0].reset();//reset the form
$('#result').html(data); // here html()
alert('Submitted');
}else{
return false;
}
}
});
});
});
Try formatting your post data like this inside your ajax function.
$.ajax({
type:'POST',
data : {
myname: myname
myage: myage
}
...
}
EDIT
Try removing the ; in
return false;
}
};
to
return false;
}
}
You can change at both end ajax and php:
#PHP:
You can check for correct posted data which is myname and myage not name and age.
<?php
if ( isset($_POST['myname'])) { // was the form submitted?
echo "Welcome ". $_POST["myname"] . "<br>";
echo "You are ". $_POST["myage"] . "years old<br>";
}
?>
or #Ajax:
yourData ='name='+myname+'&age='+myage;
//--------^^^^^^----------^^^^----change these to work without changing php
Just noticed the #result is an div element. So, you can't use .val() but use .html(), .append() etc:
$('#result').html(data);

Make Ajax and PHP update page without page refresh?

Whenever I submit the "Add Bill" form, nothing happens until I refresh the page. That's when I see my new item in the Twig loop. The same problem happens when I click on the Remove link. Nothing is removed (visually) until I refresh the page.
How do I make this stuff happen right away on the page without a page refresh? I'm thinking it might have something to do with my PHP or SQL?
JavaScript:
$(document).ready(function() {
$(".addBill").on("click", function() {
var billAmount = $('.billAmount').val();
var billName = $('.billName').val();
$.ajax({
type: "POST",
url: "index.php",
data: {
bill_amount: billAmount,
bill_name: billName,
action: 'addBill'
}
});
return false;
});
$(".removeBill").on("click", function() {
var id = $(this).data('id');
$.ajax({
type: "POST",
url: "index.php",
data: {
id_to_delete: id,
action: 'removeBill'
}
});
return false;
});
});
HTML:
<form method="post" name="addBillForm">
<input type="text" placeholder="Enter bill name" name="billName" class="billName">
<input type="text" placeholder="Enter bill amount" name="billAmount" class="billAmount">
<input type="submit" value="Submit" name="addBillForm" class="addBill">
</form>
<br><br>
<h2>My Bills</h2>
{% for bill in bills %}
<p>{{ bill.billName }} - {{ bill.billAmount }} -
Remove
</p>
{% endfor %}
Here is my PHP file:
<?php
require_once 'global.php';
if (#$_POST['action'] == 'addBill')
{
$billName = $_POST['bill_name'];
$billAmount = intval($_POST['bill_amount']);
$stmt = $db->prepare("INSERT INTO bills (billName, billAmount) VALUES(?,?)");
$stmt->bindParam(1, $billName);
$stmt->bindParam(2, $billAmount);
$stmt->execute();
}
if (#$_POST['action'] == 'removeBill')
{
$id = intval($_POST['id_to_delete']);
$stmt = $db->prepare("DELETE FROM bills WHERE id = ?");
$stmt->bindValue(1, $id);
$stmt->execute();
}
$billResults = $db->query('SELECT * FROM bills');
$bills = $billResults->fetchAll(PDO::FETCH_ASSOC);
$twigContext = array(
"bills" => $bills
);
echo $twig->render('base.html.twig', $twigContext);
You're not actually doing anything to the page after the AJAX call completes. For example:
$.ajax({
type: "POST",
url: "index.php",
data: {
bill_amount: billAmount,
bill_name: billName,
action: 'addBill'
},
success: function (data) {
// update the page somehow
},
error: function () {
// there was an error, handle it here
}
});
The page isn't going to automatically know how it should be updated. You have to write the code in that function to do it. Likely by identifying some page elements and modifying their contents, adding/removing other page elements, etc.
You arent telling it to do anything after the ajax returns. Replace your .ajax call with this.
$.post( "index.php", { action: "add bill", time: "2pm" })
.done(function( data ) {
alert( "Data Loaded: " + data );
});
Then you can replace the alert with w.e you were trying to do.
As apparent as it could be, you don't have anything for when Ajax request succeeds(state == 200).
First you should look into this documentation for getting the idea of how jquery's ajax method works, also refer below links for the same:
http://www.sitepoint.com/use-jquerys-ajax-function/
http://www.w3schools.com/jquery/ajax_ajax.asp
You have to specify what you need to be done as soon as the jquery.ajax method is successfull or when it has completed it's execution. Mainly you have to specify what you need to do with data you get at the end of execution of the same method, generally you would show that data you got, to a specified section in the same page or you would build the whole page to reflect the changes made with ajax.

Enter ID in html form and load related data from MySQL database in same page

I have a form with an input field for a userID. Based on the entered UID I want to load data on the same page related to that userID when the user clicks btnLoad. The data is stored in a MySQL database. I tried several approaches, but I can't manage to make it work. The problem is not fetching the data from the database, but getting the value from the input field into my php script to use in my statement/query.
What I did so far:
I have a form with input field txtTest and a button btnLoad to trigger an ajax call that launches the php script and pass the value of txtTest.
I have a div on the same page in which the result of the php script will be echoed.
When I click the button, nothing happens...
Test.html
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<script>
//AJAX CALL
function fireAjax(){
$.ajax({
url:"testpassvariable.php",
type:"POST",
data:{userID:$("#txtTest").val(),},
success: function (response){
$('#testDiv').html(response);
}
});
}
</script>
</head>
<body>
<form name="testForm" id="testForm" action="" method="post" enctype="application/x-www-form-urlencoded">
<input type="text" name="txtTest" id="txtTest"/>
<input type="button" id="btnLoad" name="btnLoad" onclick="fireAjax();"
<input type="submit" name="SubmitButton" id="SubmitButton" value="TEST"/>
</form>
<div id="testDiv" name="testDiv">
</div>
</body>
The submit button is to insert updated data into the DB. I know I have to add the "action". But I leave it out at this point to focus on my current problem.
testpassvariable.php
<?php
$player = $_POST['userID'];
echo $player;
?>
For the purpose of this script (testing if I can pass a value to php and return it in the current page), I left all script related to fetching data from the DB out.
As the documentation says 'A page can't be manipulated safely until the document is ready.' Try this:
<script>
$(document).ready(function(){
//AJAX CALL
function fireAjax(){
$.ajax({
url:"testpassvariable.php",
type:"POST",
data:{userID:$("#txtTest").val(),},
success: function (response){
$('#testDiv').html(response);
}
});
}
});
</script>
You need to correct two things:
1) Need to add $(document).ready().
When you include jQuery in your page, it automatically traverses through all HTML elements (forms, form elements, images, etc...) and binds them.
So that we can fire any event of them further.
If you do not include $(document).ready(), this traversing will not be done, thus no events will be fired.
Corrected Code:
<script>
$(document).ready(function(){
//AJAX CALL
function fireAjax(){
$.ajax({
url:"testpassvariable.php",
type:"POST",
data:{userID:$("#txtTest").val(),},
success: function (response){
$('#testDiv').html(response);
}
});
}
});
</script>
$(document).ready() can also be written as:
$(function(){
// Your code
});
2) The button's HTML is improper:
Change:
<input type="button" id="btnLoad" name="btnLoad" onclick="fireAjax();"
To:
<input type="button" id="btnLoad" name="btnLoad" onclick="fireAjax();"/>
$.ajax({
url: "testpassvariable.php",
type: "POST",
data: {
userID: $("#txtTest").val(),
},
dataType: text, //<-add
success: function (response) {
$('#testDiv').html(response);
}
});
add dataType:text, you should be ok.
You need to specify the response from the php page since you are returning a string you should expect a string. Adding dataType: text tells ajax that you are expecting text response from php
This is very basic but should see you through.
Change
<input type="button" id="btnLoad" name="btnLoad" onclick="fireAjax();"/>
Change AJAX to pass JSON Array.
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "action.php",
data: data,
....
// action.php
header('Content-type: application/json; charset=utf-8');
echo json_encode(array(
'a' => $b[5]
));
//Connect to DB
$db = mysql_connect("localhst","user","pass") or die("Database Error");
mysql_select_db("db_name",$db);
//Get ID from request
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
//Check id is valid
if($id > 0)
{
//Query the DB
$resource = mysql_query("SELECT * FROM table WHERE id = " . $id);
if($resource === false)
{
die("Database Error");
}
if(mysql_num_rows($resource) == 0)
{
die("No User Exists");
}
$user = mysql_fetch_assoc($resource);
echo "Hello User, your number is" . $user['number'];
}
try this:- for more info go here
$(document).ready(function(){
$("#btnLoad").click(function(){
$.post({"testpassvariable.php",{{'userID':$("#txtTest").val()},function(response){
$('#testDiv').html(response);
}
});
});
});
and i think that the error is here:-(you wrote it like this)
data:{userID:$("#txtTest").val(),}
but it should be like this:-
data:{userID:$("#txtTest").val()}
happy coding :-)

Categories