Insert MySQL record with PHP and AJAX - php

trying to insert a record in my DB using AJAX for the very first time. I have the following...
Form
<form>
<input type="text" id="salary" name="salary">
<input type="button" onclick="insertSalary()">
</form>
AJAX
<script type="text/javascript">
function insertSalary()
{
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 (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById('current-salary').innerHTML=xmlhttp.responseText;
}
};
xmlhttp.open("POST","insert_salary.php",true);
xmlhttp.send("salary=" + document.getElementById("salary").value);
}
</script>
PHP
$uid = $_SESSION['oauth_id'];
$monthly_income = mysql_real_escape_string($_POST['salary']);
#Insert a new Record
$query = mysql_query("INSERT INTO `income` (user_id, monthly_income) VALUES ($uid, '$monthly_income')") or die(mysql_error());
$result = mysql_fetch_array($query);
return $result;
Nowmy data is being inserted into the table BESIDES the 'salary' which is being inputted as '0'
Once inserted I also have a div 'current-salary' that should then be populated with there inputted value only it isnt, Can anybody help me to understand where im going wrong?

If you want to save your self a lot of time, effort, and heartache, use the jquery library for your ajax requests. You can download it at http://jquery.com/
After adding a reference(Script tag) to the jquery script your javascript for the ajax request would become:
function insertSalary()
{
var salary = $("#salary").val();
$.post('insert_salary.php', {salary: salary}, function(data)
{
$("#current-salary").html(data);
});
}
Also keep in mind that using "insert_salary.php" as the url means it is a relative path and must be in the folder of the current running script.
Your php script needs to echo whatever you would like to be injected into your current-salary tag also.

Related

AJAX no data in responsetext

Right up front...I am very new to using Ajax.
I'm working on a web site where I want the results of one Select object to determine the options in the second Select object(from a database query). I'm using PHP and it appears that the only way to do this is to use Ajax. I've written a short html page to test my Ajax knowledge and it seems to work just find on Firefox but not on Chrome or IE. I've done a lot of research and found all sorts of folks with similar problems but no real solution.
I'm making the XMLHTTPRequest call to a local file in the same folder even so I should not be experiencing any cross-domain problems. Any help would be greatly appreciated.
Here's my Javascript function that gets called when the Select box is changed:
...
function getData(str)
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","ajax_info.php?color=",true);
xmlhttp.setRequestHeader("Content-Type", "text/xml");
xmlhttp.send();
alert(xmlhttp.responseText);
}
********ajax_info.php
+++++++++++++++++++++
//this is the php file that runs in response to the xmlhttprequest. It just generates a string of number at this time.
<?php
$str = "";
$i = 0;
for($i; $i<1000; $i++)
{
$str = $str.$i."-";
}
echo $str;
?>
You need to attach an event handler to your xmlhttp object to catch the onreadystatechange event. Note that when you alert your value, the asynchronous ajax call has just fired and has not finished yet (you are not checking for that anyway):
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
alert(xmlhttp.responseText);
}
}
xmlhttp.open("GET","ajax_info.php?color=",true);
xmlhttp.setRequestHeader("Content-Type", "text/xml");
xmlhttp.send();
Well in that case you should try jQuery. It will be lot easier for you to make ajax request.
Here is an example for your problem
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
// FOR GET REQUEST
$.get("ajax_info.php",{color:'value'},function(data) {
alert(data); // RETRIEVE THE RESULT
});
</script>

Ajax function with PHP MySQL not calling the php page

I have a page that lists customers from a SQL database. It lists the credits they have left and I have a button that I can click to remove one credit. The way it is done is when you click on the button it calls a Ajax function that runs a php page that remopves one credit and echoes the credit after that.
The php page works fine when I input the string in the URL manually but smy Ajax function must be wrong.
here is the listing with the form:
while ($data = mysql_fetch_object($result)) {
print "<TR><TD>".$data->pass_name."</TD><TD><span id='credit'>".$data->credit_left."</span></TD><TD><form><input type='submit' value='- 1' onsubmit='removeOneCredit(pass_id=".$data->pass_id."&credit_left=".$data->credit_left.")'></form></TD></TR>\n";
}
and here is my function:
<script>
function removeOneCredit(str)
{
if (str=="")
{
document.getElementById("credit").innerHTML="";
return;
}
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 (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("credit").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","removeonecredit.php?"+str,true);
xmlhttp.send();
}
</script>
I'm not sure why the function is not working. I know for a fact that removeonecredit.php is doing its job.
turns out the = in the function arguments is a problem, I posted a question on how to escape it here: Javascript escape a equal sign PHP

Javascript document.getElementById concatenating

I'm struggling with some JavaScript code that I have used countless times across my pages just tweaking as I go. The problem I have is concatenating part of the form elements id and a string variable defined elsewhere in the page to make my ajax call dynamic.
Im am using the following code which works perfect when the element is hard coded as below(only works for the item coded and not dynamically so no good after testing)
<script type="text/javascript">
function edttodo(str)
{
if (str=="")
{
document.getElementById("todoitemwr").innerHTML="";
return;
}
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 (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("todoitemwr(2)").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","todo/edt_todo.php?q="+str,true);
xmlhttp.send();
}
</script>
So you understand what my need is for the dynamic aspect of the code I have a mysql query undertaken which is as follows:
<?php
//Get Current To-Do Items
//select database
mysql_select_db("jbsrint", $con);
//query users_dash_user
$result1 = mysql_query("SELECT * FROM todo WHERE todo_user_id_fk= '".$_SESSION['user_id']."' AND todo_item_status='1'");
while($row1 = mysql_fetch_array($result1))
{
echo"<div class=\"todoitemwr\" name=\"todoitemwr(". $row1['todo_id'] .")\" ID=\"todoitemwr(". $row1['todo_id'] .")\"><span class=\"todoitem\">" . $row1['todo_item'] . "</span><span class=\"rmv\" onclick=\"rmvtodo(". $row1['todo_id'] .")\" onmouseover=\"className='rmvon';\" onmouseout=\"className='rmv';\">X</span><img src=\"images/edit.png\" class=\"edt\" onclick=\"edttodo(". $row1['todo_id'] .")\"></img></div>";
}
?>
</div>
As you can see the div id is dynamically named based on the id of the information that has been retrieved. The use of my ajax code above is to be able to edit the text that is retrieved in-situ and once corrected/altered it can then be re-submitted and update that record.
I'm sure that it is simply a case of understanding how JavaScript requires me to combine the text and str value in the document.getElementById("todoitemwr(2)") part.
As usual any help is much appreciated.
Alan.
Instead of using id="todoitemwr(2)" write id="todoitemwr_2".
That's because braces are not allowed in ID attributes.
The code would become:
document.getElementById('todoitemwr(' + str + ')')

Update values from MYSQL table without reloading the page?

I've build a small login system for a home project,so,when the user do the login,he is redirect to the userspage.php.In the page i get some data from my mysql table,but the problem is,one of the values i fetch is display to the user with a button near it,when the user press those button i need to perform an php action to increase the value which is display with the button(as an example==> myvalue = 10 | When the user clicks on the button: myvalue = 11 ).I've already build this part,it is working perfectly,but i need to increase the value and update the mysql column without refreshing the page?I know its possible but every tutorial from the web i've tried doesn't work.
Thanks is advance!
AJAX is what you're looking for. Best lib for that is jQuery with it's $.ajax() method http://api.jquery.com/jQuery.ajax/
The following code has a button which onclick calls updatedb.php and shows its output in div element called 'result'
<html>
<head>
<script type="text/javascript">
function UpdateDb()
{
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 (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("result").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","updatedb.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<button onclick='UpdateDb()'>Update</button>
<p> <span id="result"></span></p>
</body>
</html>
Then write updatedb.php
<?php
do mysql update here.
and echo the result you want to display.
?>

Auto-save textarea every so many seconds

I need help with "auto-saving" a textarea. Basically, whenever a user is typing in the textarea, I would like to save a "draft" in our database. So for example, a user is typing a blog post. Every 15 seconds I would like for the script to update the database with all text input that was typed into the textarea.
I would like for this to be accomplished thru jQuery/Ajax but I cannot seem to finding anything that is meeting my needs.
Any help on this matter is greatly appreciated!
UPDATE:
Here is my PHP code:
<?php
$q=$_GET["q"];
$answer=$_GET["a"];
//Connect to the database
require_once('mysql_connect.php') ;
$sql="UPDATE english_backup SET q".$q."='".$answer."' WHERE student_id = {$_COOKIE['student']} LIMIT 1";
$result = mysqli_query($dbc, $sql);
?>
Here is my javascript code:
<script type="text/javascript">
function showUser(str, answer)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
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 (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser_english.php?q="+str+"&a="+answer,true);
xmlhttp.send();
}
</script>
function saveText() {
var text = $("#myTextArea").val();
// ajax call to save the text variable
// call this function again in 15 seconds
setTimeout(saveText, 15000);
}();
I think you want something like ajax... I'm using ajax jQuery so you will need jQuery Library for it to work. Download it. You can find tutorials on the documentation tab of the website.
//in your javascript file or part
$("textarea#myTextArea").bind("keydown", function() {
myAjaxFunction(this.value) //the same as myAjaxFunction($("textarea#myTextArea").val())
});
function myAjaxFunction(value) {
$.ajax({
url: "yoururl.php",
type: "POST",
data: "textareaname=" + value,
success: function(data) {
if (!data) {
alert("unable to save file!");
}
}
});
}
//in your php part
$text = $_POST["textareaname"];
//$user_id is the id of the person typing
$sql = "UPDATE draft set text='".$text."' where user_id='".$user_id."'"; //Try another type of query not like this. This is only an example
mysql_query($sql);
if (mysql_affected_rows()==1) {
echo true;
} else echo false;
Hey everyone I'm still having a problem please see here https://stackoverflow.com/questions/10050785/php-parse-html-using-querypath-to-plain-html-characters-like-facebook-twitter

Categories