Ajax request dataType json - php

I'm having troubles displaying a value in an input field. I did this in the past, and I haven't got a clue where my code goes wrong.
I have an input field with id="input" and a button with id="button". This is my jquery code:
$("#button").click(function() {
var uid = <?php echo $user['uid']; ?>;
$.ajax({
url: "php/fetchUserData.php",
method: "POST",
data: {
uid: uid
},
dataType: "json",
success: function(text) {
$("#input).val(text.bedrijfsnaam);
}
});
});
And here is the code on of the php/fetchUserData.php file:
<?php
include_once 'dbc.php';
if($_POST){
$uid = $_POST['uid'];
$sql = "SELECT * FROM users WHERE uid = '$uid'";
$query = mysqli_query($dbc, $sql);
$result = mysqli_fetch_assoc($query);
echo json_encode($result);
}
?>
UPDATE:
var_dump($result) does displays the associative array.
console.log(text) gives no result.
if I change dataType to text and echo out $result['bedrijfsnaam'] instead of json_encode($result) all goed well. The problem is that I want to load more than just the bedrijfsnaam (= company name).
UPDATE 2:
If I use the very same code but with another table in the database it does works. I really don't have a clue what can be the problem here...
I've been searching what could be the matter with the users table, and I notice cardinality is 0, although there are 4 rows in the table. In the other tables of the database, the cardinality value represents the number of rows. Could that have anything to do with this problem?
UPDATE 3:
Instead of the query:
$sql = "SELECT * FROM users WHERE uid = '$uid'";
I tried:
$sql = "SELECT bedrijfsnaam FROM users WHERE uid = '$uid'";
And it worked! Then I started adding column names, and all went well until a certain column: land (meaning country) a varchar column just like many others in the table.
What could be the reason this particular column causes the error to happen?
I know this became a phpmyadmin question instead of a php or jquery question. Should the question be moved to the sql part of the forum?

Assuming this is your actual code, your issue is likely stemming from not actually referencing and updating a field.
Something like this should be what you need:
$("#input").val(text.bedrijfsnaam)

I don't know anything about PHP and I don't think it matters. I think you got most part right. In success of your ajax request, set the text value of the input field.
$.ajax({
url:"php/fetchUserData.php",
method: "POST",
data:{uid:uid},
dataType:"json",
success:function(text){
$("id='button'").text(text.bedrijfsnaam);
}
});

$.ajax({
url:"php/fetchUserData.php",
method: "POST",
data:{uid:uid},
dataType:"json",
success:function(text){
$('#input').val(text[0]);
}
});
hmtl maybe better works than .val
You're wrong with your jquery selection of your div: you're missing an " in your code.
hope it will work

Related

Why is my SQL query not returning results?

I'm trying to get a form on my site to work. Here are the tables in the database it's referencing:
USERS TABLE
userID
Object1
Object2
1
1abc
123a
2
2def
123b
POSTS TABLE
ID
Object2
12
123a
43
123b
The form takes a manually entered key. When I hit submit, it's supposed to run this function:
public function claim(Request $request){
$post = "SELECT posts.id FROM posts INNER JOIN users ON users.Object2=posts.Object2 WHERE posts.is_deleted='No' && users.Object1=$request->'Object1'";
$result = mysql_query($post);
if($result->num_rows > 0) {
return 1;
}
else{
return 0;
}
}
The problem is, when I click submit, the form doesn't do anything. No result, no error message. The form is supposed to take the manually entered "Object1", find the associated "Object2", check the Posts table for entries that have that "Object2" and spit out a result.
I've tried running the query in phpMyAdmin and replaced "users.Object1=$request->'Object1'" with "users.Object1='1abc'" and it gives me the correct result which is "12". Yet when I try putting it in my php file for my site, the form does nothing.
EDIT:
Here is the code that is running the form:
$.ajax({
url: "http://*********",
type: 'POST',
data: {key},
success: function(response){
console.log(response)
if(response == 1){
$('.message').text('Success')
$('.message').removeClass('text-danger')
$('.message').addClass('text-success')
$('#pdf').show();
$('#button').hide();
You have the single quotes in the wrong place.'
users.Object1=$request->'Object1'
should be
users.Object1='$request->Object1'
The quotes need to go around the entire string value, just like when you write it literally with users.Object1='1abc'.

How to load large bulk records in MySql using jquery autocomplete

I am having nearly 80,000 records in a single table in MYSQL, I wanna make it display in the Autocomplete control.
The table structure is given below
Table_name
-ID
-Code
-codeType
In client side, I have made that autocomplete script like given below
var Cds = "";
$.ajax({
type: "POST",
url:"cdList.php",
async: false,
data:{
value1 : '9'
},
success:function(result){
Cds = JSON.parse(result);
}
});
$("#prin").autocomplete({
minlength : 3,
source: Cds,
autoFocus:true,
width:500
});
cdList.php
<?php
$con = mysql_connect("localhost","***","***");
if(!$con){
die("Error : ".mysql_error());
}
mysql_select_db("ananth",$con);
$value1 = $_POST['value1'];
$cd9 = array();
$result = mysql_query("select * from Table_name where codeType = '9' AND Code LIKE '$value1%'");
while($row = mysql_fetch_array($result)){
$cd9[] = $row['Code'];
}
echo json_encode($cd9);
?>
Even i set minLength in autocomplete control, still i am feeling damn slowness on getting the data. It took around 30 seconds. So what will be the work around to make it fast?
Look at this post abot like operator.
For your case i reccomend using query_caching flag and select only one column instead *
select Code from Table_name where codeType = '9' AND Code LIKE '$value1%'
LIKE queries have a potential for taking a long time...
for autocomplete purposes you could use MySQL's LIMIT and return only a chunk of the relevant entries.
check out this link:
http://www.w3schools.com/php/php_mysql_select_limit.asp
also you should probably index codeType column for a faster search.
hope this helps

Ajax post to php to update mysql

I've built an admin page for my site, that contains numerous forms that save, update, delete data into different tables in my database.
Currently i have one PHP file for each function that does the mysql query according to my ajax post command. which is getting a bit out of control.
for example i have a file for saving a new category
$cataddname = $_POST['name'];
$area = $_POST['area'];
$shortname = preg_replace('/\s+/', '_', $cataddname);
$update_category = "INSERT INTO clet_faq_category (id, name, nickname, area) VALUES ('', '$cataddname', '$shortname', '$area')";
mysqli_query($db_connect, $update_category);
my save new category command posts to this file:
then i have a file that saves a category edit:
$cataddname = $_POST['name'];
$area = $_POST['area'];
$id = $_POST['cid'];
$shortname = preg_replace('/\s+/', '_', $cataddname);
$update_category = "UPDATE clet_faq_category SET name='$cataddname', nickname='$shortname', area='$area' WHERE id = '$id'";
mysqli_query($db_connect, $update_category);
And another one to delete a category:
$c_id = $_POST['delete_id'];
$sql_del = "DELETE FROM clet_faq_category WHERE id = '$c_id'";
$del_question = mysqli_query( $db_connect, $sql_del );
then i have an jQuery ajax call that calls the page:
function newcat(){
var id = "answer";
tinymce.execCommand('mceRemoveEditor', true, id);
var category = document.getElementById('newcategory').value;
var area = document.getElementById('area').value;
var dataString = 'name=' + category + '&area=' + area;
$.ajax({
type: "post",
url: "newcat.php?area_id=" + areaid,
data : {
'name': category,
'area': area,
'query' : query
},
cache: false,
success: function(html){
$('#category_table').html(html);
$('#cat-form').text("Category Saved");
}
});
return false;
}
And When you look at them it's pretty much the same thing it's just a mysql query running.
What i'm trying to do is streamline this a little bit, i thought about passing the entire query via ajax to my php file, but that's not an option as anyone that can see my js file will be able to figure out all my queries and table names, and all they need to do is post a query to my php page and damage my entire DB.
so my question is, is there a way to do this in a smarter way maybe creating php functions inside the same file, that has category_delete(), category_add(), category_edit() on the same file and using ajax target each one of those categories, at least all my functions and queries will be on the same spot not in multiple separate files if you know what i mean.
You can do like this create a separate class which perform options for insert delete and update. and on your ajax page call these function like this
$func = new CUD();
switch($_POST['action'])
{
case 'delete':
$func->delete($values..)
case 'update':
$func->update($values..)
case 'delete':
$func->insert($values..)
}
You can have to send extra parameter in ajax as action, this parameter specifies the action
in php
switch($_POST['action'])
{
case 'delete':
.....
}

After successful ajax POST operation nothing happens in the database

I've checked for duplicates and none of them are strictly related to this problem.
I have the following javascript code
var value = $.ajax({
type: "POST",
url: "bank.php",
data: {sum:money},
cache: false,
async: true
}).done(function() {
console.log( "success" );
}).fail(function() {
console.log( "error" );
});
and php in bank.php
if(isset($_POST['sum']))
{
$money = mysql_real_escape_string($_POST['sum']);
$query = "UPDATE banks SET currency = 1 WHERE amount = '.$money.'";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
}
I receive in the browser console "success" for the ajax operation but nothing happens in the database. Take note that "currency" is a tinyint(1) and amount is an int(10) [I'm using sql tables as you might have guessed]. What am I doing wrong? (bank.php also includes the header to link to my database, so that's not the problem because I tested others queries there).
I believe the code isn't going through the if(isset($_POST['sum'])) validation but don't understand why. Any suggestions?
Try this :
$query = "UPDATE banks SET currency = 1 WHERE amount = ".$money.";
Hope this help u.

Saving to database via AJAX/jQuery, sending two variables

I have this problem that I have multiple fields that updates a database via an AJAX-call. The AJAX call looks like this:
$(".fresheditable").fresheditor("save", function (id, parsedHtml) {
$.ajax({
url: 'save.php',
type: 'POST',
data: {
id: id,
parsedHtml: parsedHtml
}
});
});
The ID value changes depending on what element is being edited. The problem is when the update gets sent to the save.php document. How do I only run the update with the specific ID?
See my save.php:
if($_POST['id']='link')
{
$link = $_POST['parsedHtml']; //get posted data
// query
$sql = "UPDATE buttons SET linkname=? WHERE id=?";
$q = $conn->prepare($sql);
if ($q->execute(array($link,$_SESSION['button'])))
{
echo 1;
}
}
//The next if-statement could look like this:
if($_POST['id']='contactperson')
{
$contactperson = $_POST['parsedHtml']; //get posted data
// query
$sql = "UPDATE buttons SET contactperson=? WHERE id=?";
$q = $conn->prepare($sql);
if ($q->execute(array($contactperson,$_SESSION['button'])))
{
echo 1;
}
}
If more than one ID is sent to the save.php say link and contactperson both if-statements are true and the update sets the same values because the parsedHtml variable.
Is there anything I can do in save.php that can prevent this? Somehow I need to associate the correct parsedHtml with the corresponding id.
The comparison operator in PHP (as well as in Javascript) is == and not =
if($_POST["id"]=="link")
Is it because you're using single equals in your IF tests, which assigns and returns true as a value exists? Not double-equals for comparison?
E.g.
if($_POST['id']=='link')
not
if($_POST['id']='link')
One thing you can use is data attribute i mean
<span item-data="some_id">data</span> now you can select in jquery, the specific item-data from your html to update.
Use else-if structure.
if($_POST['id']='link') {
}
else if($_POST['id']='contactperson') {
}

Categories