I have a plugin that uses a click to edit AJAX POST request, I have the script all made up, but when I went to go test it, it never changed my database values that I was trying to modify, so I changed the URL you set to a function to report the request into my google console, it returns the following,
Object {name: "", value: "derp#derpp.com", pk: 23}
Here is the PHP script I am trying to AJAX to,
<? $query = "
UPDATE users SET email = '".$_POST['value']."' WHERE id = '".$_POST['pk']."'
";
try
{
$stmt = $db->prepare($query);
$stmt->execute();
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$rows = $stmt->fetchAll();
?>
My overall issue, is that the content is not being changed by the AJAX, I tested the script manually and everything works.
EDIT
I am not manually doing an AJAX request, its being used off of a plugin, called X-Editable The Documentation can be found here
did you checked the data which you are sending is actually inside post request. I would check if i am using a proper jquery post request such as
$.ajax({
type: 'POST',
url: url,
data: data,
success: success,
dataType: dataType
});
just sending post data doesn't helps. Moreover if you are not passing any dummy value such as javascript.getTime function its a good idea to use it coz sometime the xmlhttp object doesn't recognises as new query.
Therefore your url should be "url:'dummy='+dt.getTime()+'&var1='+$textbox1.val()"
hope this helps you.
post data type must be application/x-www-urlencoded , if use $_POST function in php .
HTTP /yourURI HTTP/1.0
Content-Length:xxx
Content-Type:application/x-www-urlencoded
Connection:clsoe
name=&value=derp%40derpp.com&pk=23
can't post object to Server,as body...
HTTP /yourURI HTTP/1.0
Content-Length:xxx
Content-Type:application/json
Connection:clsoe
{name: "", value: "derp#derpp.com", pk: 23}
revised query... If you have an integer based value, it can't be quoted;
$query = "UPDATE users SET email = '".$_POST['value']."' WHERE id = ".$_POST['pk'];
or using string replacement
$query = "UPDATE users SET email = '{$_POST['value']}' WHERE id = {$_POST['pk']}";
Related
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
I need to update a variable named $count (in the below code) automatically. When my database update, $count be update immediately because i need to use value of $count in android app so i can't refresh count.php file every time.
<?php
$con=mysql_connect("","","");
mysql_select_db("u607509006_bd1",$con);
$query = "select * from content where status='a'";
$result = mysql_query($query);
$count = mysql_num_rows($result);
echo $count;
mysql_close($con);
?>
Just use a Jquery Ajax Request on the client side like so:
$.ajax({
url: "path/to/code/file.php" // change this to your path to your code
}).done(function(data) {
// This is executed after the ajax request is complete
// data should be the updated value. You can also return other data // types e.g. JOSN
$('#counter').text(data);
});
JS Fiddle Example: https://jsfiddle.net/anik786/nvkdLhv2/2/
I have a table called Stats. Stats has 4 columns: id, ip, count, and date. count is the number of clicks the ip has clicked on the ads on my site. Each time the user clicks on an ad, their count number will increase by 1. How do I increase their count number by 1 and update that in the database? Here is my code and it's not working for some reason. When I click on the div, it doesn't refresh...so the whole block of code isn't executing. Note that I've already captured the user's ip when they entered my site, this is the part where if they clicked my ad, the count is incremented and updated in the database.
<script>
$(document).ready(function()
{
$("#ad").click(function()
{
<?php
$queryTot = "SELECT `count` AS total FROM Stats WHERE ip = '$ip'";
$resultTot = $db->query($queryTot);
$data = $resultTot->fetch_assoc();
$count = $data["total"] + 1;
$insert = $db->prepare("UPDATE Stats(count) WHERE ip = '$ip' VALUES(?)");
$insert->bind_param('i', $count);
$insert->execute();
$insert->close();
?>
location.reload();
})
})
</script>
There is a lot of points to consider in your answer.
But very possibly you should use an AJAX solution to do it, and avoid every SQL queries in your HTML pages, because keeping SQL queries there definitely is not a good pratice, according all basic security and code maintenance POVs.
It is not possible to re-write your code here rightly without knowing your project structure, or even your idea, and you must take this answer as an important start point.
Basically, you must define in your server-side application a method which returns pure data, in a JSON format for example, and then use AJAX to access this method according an event (a click, for example), receive its response and modify your client-side, probably with jQuery and JS.
I hope this answer can help you.
I've written a short example for you that you could continue to build on to accomplish what you need. Here's the basic idea.
HTML
<input type="hidden" id="ip" value="<?php echo $_SERVER['REMOTE_ADDR'];?>"/>
jQuery
var ip = $('#ip').val();
$(document).ready(function(){
$('#ad').on('click',function(){
$.ajax({
type: 'POST',
url: 'ajaxUpdateDatabase.php',
data: 'ip='+ ip,
success: function(response){
console.log(response)
//send the user to the ad's page here for example
//you could use location.href='url-to-add-here';
//or if you really want to reload the page for a reason I fail to understand, use location.reload();
}
});
});
});
PHP (ajaxUpdateDatabase.php)
//please note that using UPDATE requires that there is previously an entry with this IP address.
//example using PDO...
$sql = 'SELECT * FROM stats WHERE ip = ?';
$stmt = $pdo->prepare($sql);
$stmt->execute(array($_POST['ip']));
if($stmt -> rowCount() > 0){
$sql = 'UPDATE stats SET count = count + 1 WHERE ip = ?';
$stmt = $pdo->prepare($sql);
$stmt->execute(array($_POST['ip']));
}
else{
//ip-address was not found in the database
//insert query goes here
}
I'm calling ajax from AddSomething.php file as follows
<script>
var dataValue;
$("#schedule").change(function () {
var value = $('#schedule option:selected').text();
var ajaxCheck = $.ajax({
url: 'processClg.php',
type: 'POST',
dataType: 'json', // processClg.php will return string means change to text
data: { id: value },
success: function(data){
dataValue = data;
console.log(dataValue);
}
});
});
</script>
Getting response in Network as follows
[{
"id": "2",
"scheduleName": "abc",
"subject": "Patho",
"university": "xyz",
"facultyName": "Dr",
"scheduleStartDate": "2015-06-05",
"scheduleEndDate": "2015-06-09"
}]
And in console it is showing [Object]
How can I assign the above values to the following PHP variables present in the same page
<?php
$scheduleStartDate ='';//Here How can i assign respected ajax responsevalue
$scheduleEndDate = '';//Here How can i assign respected ajax response value
$qry = "SELECT * FROM `mytable`
WHERE `university` LIKE ''//Here How can i assign value
ORDER BY `university` DESC,student_name ASC";
?>
processClg.php file code
<?php
include "config.php";
$qry = "SELECT * FROM `schedule` WHERE scheduleName LIKE '".$_POST['id']."'";
$res = mysqli_query($link, $qry);
//echo $res;
while($row = mysqli_fetch_assoc($res))
$test[] = $row;
echo json_encode($test);
?>
You can't assign the result of an Ajax call to PHP variables. The PHP has already run on the server, done it's bit and sent the HTML / JavaScript to the browser. At that point you can no longer use PHP as it's a server side language and will only run on the server. Ajax uses JavaScript, which is a client side language. It only runs after the PHP has finished and the server has sent the HTML / JavaScript to the users browser. JavaScript is executed in the clients browser.
You need to rethink what you're doing and where you're doing it. If you need the results of the Ajax call to do something in PHP then do it in your processClg.php file. You do all your PHP first, then send a response to the browser to display something to the user. If the user doesn't need any sort of confirmation or acknowledgement then you can just send the Ajax request and not bother with a response.
It looks like you're trying to dynamically load some University information. What you should do is put this part:
$scheduleStartDate ='';//Here How can i assign respected ajax responsevalue
$scheduleEndDate = '';//Here How can i assign respected ajax response value
$qry = "SELECT * FROM `mytable`
WHERE `university` LIKE ''//Here How can i assign value
ORDER BY `university` DESC,student_name ASC";
into processClg.php after the first query. Then you get the results of the query and pass them back to your HTML page, like this:
$results = array();
$qry = "SELECT * FROM `mytable`
WHERE `university` LIKE ''
ORDER BY `university` DESC,student_name ASC";
$result = mysqli_query($link, $qry);
while ($row = mysqli_fetch_assoc($result))
{
$results[] = $row;
}
echo json_encode($results);
You can store ajax result in php variable by embedding ajax result div into php tag
<?php
$result='<div id="result"></div>';// Here you embed div in php tag and store in php varible
?>
You cann't do this job as you think the way.
For that , you need to assign the return values to any hidden field form value and submit the form.
Also keep in mind for ajax response data keep in the js variable, you need to pass the parameter async:false
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') {
}