How can i use this kind of var in AJAX? - javascript

The Problem is in the var a I have created
<script>
$( "#EDITsave" ).click(function() {
var a = parseInt(window.id.charAt(window.id.length-1)) //a gets parsed correctly but nothing happens in ajax until i set a number myself
console.log(a)
$.ajax({
type: "POST",
datatype: "text",
url: "edit.php",
data: {
inputID: a,
inputtxt: //issue is in 'a' here!
document.getElementById("editinputtext").value
},
});
});
</script>
PHP: // PHP CODE FOR AJAX
$inputID = $_POST['inputID'];
$inputtxt = $_POST['inputtxt'];
$sql = "UPDATE Contributions SET inputtxt = '$inputtxt' WHERE inputID = $inputID";
if ($connection->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $connection->error;
}
$connection->close();
?>

Related

Upload data base with link onClick

I am having trouble in uploading my database information when I click on a specific link.
It seems that the data is not sent to upload.php
HTML:
Mylink
Javascript:
<script type="text/javascript">
function myfunc(a, b)
{
$.ajax({
url: "upload.php",
type: "POST",
data: {"a": a, "b": b},
success:function() {
alert( "Done");
}
});
}
</script>
upload.php:
if (isset($_POST['a']) && isset($_POST['b']))
{
$a = $_POST['a'];
$b = $_POST['b'];
$query1 = $db->prepare('UPDATE users SET a = a + 1 where uid="'.$a.'"');
$query1->execute();
$query2 = $db->prepare('UPDATE users SET b = b + 1 where uid="'.$b.'"');
$query2->execute();
if (!$query1 || !$query2)
{
echo "Erreur SQL";
exit();
}
}
1st : Your html should be like this myfunc(<?php echo $a ?>,<?php echo $b ?>)"
Mylink
2nd :Add error handling part in ajax request
function myfunc(a, b)
{
$.ajax({
url: "upload.php",
type: "POST",
data: {"a": a, "b": b},
success:function() {
alert( "Done");
},
error:function(jqXHR,error_string,error){
console.log(error);
}
});
}
3rd : use bind_param the values to avoid SQL injection and integer value should not enclosed by single quotes
$query1 = $db->prepare('UPDATE users SET a = a + 1 where uid=?');
$query1->bind_param('i',$a);
$query1->execute();
4th : In your upload.php file your preparing $query2 first and trying to execute $query1 i think it was typo please correct it .

ajax jquery errors on json return value from php script

I'm having problems with this ajax/jquery programming.
I've tried many different things but nothing has worked.
Ajax posts selItem to ajaxsql.php, this works!
The sql query in ajaxsql.php works, cause it outputs this if i call the script directly in the browser: [{"forumname":"SDE forum","user":"michael","txt":"Jeg hedder Michael!"}]
The problem is that the ajax function shows an alert box with Error[object Object]
forum.php script:
<script type="text/javascript">
function ForumChat(selItem) {
$.ajax({
type: "POST",
url: 'ajaxsql.php',
data: { selectedItem : selItem.value },
dataType: "json",
success: function(data) {
alert(data);
$('#txtarea').html(data);
},
error: function(data) {
alert('Error' + data);
}
});
}
</script>
ajaxsql.php script:
<?php
if(!isset($_SESSION))
{
session_start();
}
include('class.php');
//$sel = $_POST['selectedItem'];
$sel = "SDE forum";
$sql = " SELECT * FROM forum WHERE user = '".$_SESSION['currentuser']."' AND forumname = '".$sel."' ";
$result = mysqli_query($_SESSION['con'], $sql);
while($row = mysqli_fetch_array($result))
{
$forumname = $row['forumname'];
$user = $row['user'];
$txt = $row['text'];
$return[] = array("forumname" =>$forumname, "user" =>$user, "txt" =>$txt);
}
echo json_encode($return);
?>
because ajaxsql.php returns object ..
what you can do in your ajax is
success: function(response) {
$('#txtarea').html('');
$.each(response.data, function(){
console.log(this);
$('#txtarea').append(data);
});
},

How to pass multiple variables from a php file to ajax and use them?

I have read many answers on stack overflow but I can't find an apt answer. I want to send multiple variables from php file to a javascript file. I want to use those variables later separately. So please explain with a simple example of how to get the variables from php file and how to use them separately later.
This is my js.
<script>
function here(card_numb) {
alert("pk!");
$.ajax({
url: 'details.php',
type: "GET",
dataType: 'json',
data: ({
card_number: card_numb
}),
success: function(data) {
console.log('card_number:'+data.card_number+'book_issued:'+data.book_isued);
}
});
}
I'm getting the alert 'pk!'. But $.ajax ain't working.
This is details.php
<?php
if(isset($_GET['card_number'])){
$card_number = $_GET['card_number'];
$query = "Select * from users where card_number = '".$card_number."'";
$query_run = mysqli_query($link,$query);
$row_numb =#mysqli_num_rows($query_run);
if($row_numb == 0){
echo "<div class='bdiv1'>No such number found!</div>";
} else{
$row=mysqli_fetch_assoc($query_run);
$book1 = $row['user_name'];
$arr = array('isued_book' => $book1,'card_number' => $card_number);
echo json_encode($arr);
exit();
}
}
?>
Thank you!
somthing.js - ur jspage
<script>
function here(card_numb) {
$.ajax({
url: 'details.php',
type: 'GET',
dataType: 'json',
data: {
card_number: card_numb
},
success: function(data) {
console.log('card_number:'+data.card_number+'book_issued:'+data.isued_book);
}
});
}
success: function(result){
console.log('variable1:'+result.var1+'variable2:'+result.var2+'variable3:'+result.var3);
} });
details.php
<?php
if(isset($_GET['card_number'])){
$card_number = $_GET['card_number'];
$query = "Select * from users where card_number = ".$card_number;
$query_run = mysqli_query($link,$query);
$row_numb =#mysqli_num_rows($query_run);
if(!$query_run){
echo "<div class='bdiv1'>No such number found!</div>";
} else {
$row=mysqli_fetch_assoc($query_run);
$book1 = $row['user_name'];
$arr = array('isued_book' => $book1,'card_number' => $card_number);
echo json_encode($arr);
exit();
}
if the currect value get in $row you can get the result in console

how to put condition alert box in ajax

can anyone help me...how do i put an conditional alert dialog box in ajax that if the data in a query is successfully saved or the data already been saved.
I want to do is if the query is saved an alert box will pop-op same goes to if the data is already been saved.
script code:
<script type="text/javascript">
$(document).ready(function () {
$('#updates').click(function (e) {
e.preventDefault();
var data = {};
data.region_text = $('#t_region').val();
data.town_text = $('#t_town').val();
data.uniq_id_text = $('#t_uniq_id').val();
data.position_text = $('#t_position').val();
data.salary_grade_text = $('#t_salary_grade').val();
data.salary_text = $('#t_salary').val();
for(var $x=1;$x<=15;$x++) {
data['id'+$x+'_text'] = $('#id'+$x).val();
data['aic'+$x+'_text'] = $('#aic'+$x).val();
data['name'+$x+'_text'] = $('#name'+$x).val();
data['optA'+$x+'_text'] = $('#optA'+$x).val();
data['optB'+$x+'_text'] = $('#optB'+$x).val();
data['optC'+$x+'_text'] = $('#optC'+$x).val();
data['optD'+$x+'_text'] = $('#optD'+$x).val();
data['other_qual'+$x+'_text'] = $('#other_qual'+$x).val();
data['interview'+$x+'_text'] = $('#interview'+$x).val();
data['total'+$x+'_text'] = $('#total'+$x).val();
}
$.ajax({
type: "POST",
url: "insert.php",
data: data,
cache: false,
success: function (response) {
// We are using response to distinguish our outer data variable here from the response
}
});
});
});
</script>
insert.php code:
<?php
include('../connection.php');
date_default_timezone_set('Asia/Manila');
$region = #$_POST['region_text'];
$town = #$_POST['town_text'];
$uniq_id = #$_POST['uniq_id_text'];
$position = #$_POST['position_text'];
$salary_grade = #$_POST['salary_grade_text'];
$salary = #$_POST['salary_text'];
$dupesql = "SELECT * FROM afnup_worksheet WHERE funiq_id = '$uniq_id'";
$duperow = mysql_query($dupesql);
if(mysql_num_rows($duperow) > 0){
exit;
}else{
for($n=1;$n<=15;$n++) {
$id = #$_POST['id'.$n.'_text'];
$aic = #$_POST['aic'.$n.'_text'];
$name = #$_POST['name'.$n.'_text'];
$optA = #$_POST['optA'.$n.'_text'];
$optB = #$_POST['optB'.$n.'_text'];
$optC = #$_POST['optC'.$n.'_text'];
$optD = #$_POST['optD'.$n.'_text'];
$other_qual = #$_POST['other_qual'.$n.'_text'];
$interview = #$_POST['interview'.$n.'_text'];
$total = #$_POST['total'.$n.'_text'];
if(!empty($name)){
$query = "INSERT INTO afnup_worksheet (faic,fregion,ftown,funiq_id,fposition,fsalary_grade,fsalary,fnl_name,edu_attain,experience,seminars,eligibility,other_qual,interview,ftotal,dateinputed)
VALUES
('$aic','$region','$town','$uniq_id','$position','$salary_grade','$salary','$name','$optA','$optB','$optC','$optD','$other_qual','$interview','$total',CURRENT_TIMESTAMP)";
$resource = mysql_query($query) or die(mysql_error());
}
}
}
?>
Just return that status from PHP:
if(mysql_num_rows($duperow) > 0){
echo "1"; // Dup status
exit;
}else{
// All your else code.. echo must be the last thing inside your else block
echo "2"; // Saved status
}
Then in your ajax success callback you check it:
$.ajax({
type: "POST",
url: "insert.php",
data: data,
cache: false,
success: function (response) {
if (Number(response) == 1)
{
alert("Dup message");
}
else
{
alert("Saved message");
}
}
});
Instead of exit; in your conditinal for dupes, you could echo "duplicate". Also you should remove die() after your $resource and add if ($resource) echo "ok"; else echo "error";
Then in your success function(response) in javascript you can do if (response=="...") echo duplicate; else if ...
This is just basic explanation, but it should be enough to point you in the right direction.

Ajax separate data which came from mysql

I am doing an ajax call like this:
function myCall() {
var request = $.ajax({
url: "ajax.php",
type: "GET",
dataType: "html"
});
request.done(function(data) {
$("image").attr('src',data);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
This is my ajax.php:
<?php
$connection = mysql_connect ("",
"", "");
mysql_select_db("");
// QUERY NEW ONE
$myquery = "SELECT * FROM mytable ORDER BY rand() LIMIT 1";
$result = mysql_query($myquery);
while($row = mysql_fetch_object($result))
{
$currentid = "$row->id";
$currentname = "$row->name";
$currenturl = "$row->url";
$currentimage = "$row->image";
echo $currenturl,$currentnam, $currenturl,$currentimage;
}
mysql_close($connection);
?>
My data variable from the ajax call now contains all variables at once:
($currenturl,$currentnam, $currenturl,$currentimage)
How can I separate them so I can do something like:
request.done(function(data) {
$("id").attr('src',data1);
$("name").attr('src',data2);
$("url").attr('src',data3);
$("image").attr('src',data4);
});
jQuery :
$.ajax({
type:"POST",
url:"ajax.php",
dataType:"json",
success:function(response){
var url = response['url'];
var name = response['name'];
var image = response['image'];
// Now do with the three variables
// $("id").attr('src',data1);
// $("name").attr('src',data2);
// $("url").attr('src',data3);
// $("image").attr('src',data4);
},
error:function(response){
alert("error occurred");
}
});
From your code:
echo $currenturl,$currentnam, $currenturl,$currentimage;
Replace the above line with the code below:
$array = array('url'=>$currenturl, 'name'=>$currentname, 'image'=>$currentimage);
echo json_encode($array);
instead of string return an array i.e. use json type for returning value
i.e instead of
echo $currenturl,$currentnam, $currenturl,$currentimage;
use
echo json_encode array('current' => $currenturl,'currentnam' => $currentnam, 'currenturl' => $currenturl,'currentimage' => $currentimage);
and also write 'dataType' as 'json' in ajax

Categories