When I make a .post() request such as
var data = $(this).serialize();
$('form').on('submit', function(event) {
event.preventDefault();
$.post('server.php', data, function(data) {
$('#data').append('<p>' + data + '</p>');
});
});
everything's working - the name from the database appends to the #data element withing the p tags. But, when I try to pass data as an object like this
var data = $(this).serialize();
$.post('server.php', {id: data}, function(data) {
$('#data').append('<p>' + data + '</p>');
});
than it doesn't work. I tried changing the argument of the function within the .post() to id and probably every combination of names for .post()'s arguments and variables within the PHP file also, without success. Here's the working intact PHP file compatible with the first version of my .post() request in this question:
<?php
$id = $_POST['id'];
$connection = new mysqli('localhost', 'root', '', 'dummy_db');
$query = 'SELECT name FROM dummy_db_table WHERE id = "' . $id . '"';
$result = $connection->query($query);
$row = $result->fetch_assoc();
echo $row["name"];
$connection->close();
?>
Please note that the name of the input field for the ID in the HTML file is 'id'. I do understand that it is this name attribute within HTML which helps PHP determine the value of it, but how is it doing so without me specifying the connection with the PHP through form's action attribute? I'm doing this exclusively through AJAX (.post()) and AJAX is not telling PHP anything specific about THAT id field. What am I missing here? Also, how would I go about sending the object of values instead of a single one through .post()'s data attribute? Thank you.
You have not add the form code here so lets assume your form have two fields name and address.
Actually you need to put the serialize() function under the event. Like
$('form').on('submit', function(event) {
event.preventDefault();
var data = $(this).serialize();
$.post('server.php', {id: data}, function(data) {
$('#data').append('<p>' + data + '</p>');
});
});
Now on your server.php file if you print the following line:
$id = $_POST['id'];
echo $id;
this will show you the results like: name=iffi&address=UK
I hope this will help you more.
Related
i use this code for on change
<script>
$('.BIR').change(function() {
var id = $(this).val(); //get the current value's option
$.ajax({
type:'POST',
dataType: "json",
url:'assets.php',
data:{'id':id,MainM : IR},
success:function(data){
$("#IRd").html(data);
}
});
});
</script>
i send multi variable form this javascript to the assets.php successfully
<?php
$id = $_POSt['id'];
$MainM = $_POST['MainM'];
// some php functions here to get the final data
$Otp = "xxxxx";
$name = "bbbbb";
?>
i want to pass this data back to the javascript..
if i passed one i use this
echo $Otp;
this works fine , but i want to pass this 2 variables or more .. but i don't know how to do this .. so please help.
I think the ideal way to be to use json. something like
echo json_encode(['Otp': $Otp, 'name': $name])
On your php side would work, and then you could use that data in your success function like such :
success:function(data){
//you can then use your data like object properties, for an example
const name = data.name;
const Otp = data.Otp;
}
Put the variable in an array on assets.php page like below
$newArray['Otp'] = "xxxxx";
$newArray['name '] = "bbbbb";
echo json_encode($newArray);
Add this in javascript
success:function(data){
var text = "OTP: "+data.Otp+" Name: "+data.name;
$("#IRd").html(text);
}
Can some body help me get the current value from this option tag
to account.php as a session variable or anything ..
// loadsubcat.php This code is for dependent dropdown
$query = mysql_query("SELECT * FROM table_cmsjob WHERE VesselID= {$parent_cat}");
while($row = mysql_fetch_array($query))
{
echo "<option value='$row[jobName]'>$row[jobName]</option>";
}
var javascriptVariable = $('#sub_cat').val();
I know this can be solve using ajax but I don't know how.
I will use the javascript variable as a reference for a couple of checkboxes under it but first must be passed as a php variable.
you ajax will look like this,
$.ajax({
type: 'POST',
url: "account.php",// path to ajax file
data: {javascriptVariable:javascriptVariable},// you can pass values here in key value pairs.
success: function(data) {
alert(data);
}
});
You can send n number of key => value pairs.
like
parent_cat:100
Next:
echo $_POST['javascriptVariable']; // <--- grabbing ajax data here
$query = mysql_query("SELECT * FROM table_cmsjob WHERE VesselID= {$parent_cat}");
while($row = mysql_fetch_array($query))
{
echo "<option value='$row[jobName]'>$row[jobName]</option>";
}
what ever echoed in php file will come in ajax success data,
alert(data) will alert what you had echoed in php. you can use that in your html file.
I have some divs with class content-full which are created according to the data stored in a MySQL table. For example, if I have 3 rows there will be 3 divs.
When I click on any of the divs then the data associated with the ID for that div should be displayed inside div content-full. However, the content associated with the last div appears when I click on any of the divs because I am not passing any kind of variable ID that can be used to specify the clicked div.
<script type="text/javascript">
$(document).ready(function() {
$(".content-short").click(function() { //
$.ajax({
type: "GET",
url: "content.php", //
dataType: "text",
success: function(response){
$(".content-full").html(response);
}
});
});
});
</script>
content.php
<?php
include "mysql.php";
$query= "SELECT Content FROM blog limit 1";
$result=mysql_query($query,$db);
while($row=mysql_fetch_array($result))
{
echo $row['Content'];
}
mysql_close($db);
?>
Is there an alternate way to do this or something that I need to correct for it to work?
Thanks
First off, you will have to pass actual data to the your PHP script. Let's first deal with the JavaScript end. I am going to assume that your HTML code is printed using php and you are able to create something like the following: <div class=".content-short" data-id="2" />:
$(".content-short").click(function() {
// get the ID
var id = $(this).attr('data-id');
$.ajax({
type: "post",
url: "content.php",
data: 'id=' + id
dataType: "text",
success: function(response){
$(".content-full").html(response);
}
});
});
Next up is reading the value you passed in using the script:
<?php
include "mysql.php";
// Use the $_POST variable to get all your passed variables.
$id = isset($_POST["id"]) ? $_POST["id"] : 0;
// I am using intval to force the value to a number to prevent injection.
// You should **really** consider using PDO.
$id = intval($id);
$query = "SELECT Content FROM blog WHERE id = " . $id . " limit 1";
$result = mysql_query($query, $db);
while($row=mysql_fetch_array($result)){
echo $row['Content'];
}
mysql_close($db);
?>
There you go, I have modified your query to allow fetching by id. There are two major caveats:
First: You should not use the mysql_ functions anymore and they are deprecated and will be removed from PHP soon if it has not happened yet!, secondly: I cannot guarantee that the query works, of course, I have no idea what you database structure is.
The last problem is: what to do when the result is empty? Well, usually AJAX calls send and respond with JSON objects, so maybe its best to do that, replace this line:
echo $row['Content'];
with this:
echo json_encode(array('success' => $row['Content']));
Now, in your success function in JS, you should try to check if there a success message. First of, change dataType to json or remove that line entirely. Now replace this success function:
success: function(response){
$(".content-full").html(response);
}
into this:
success: function(response){
if(response.success) $(".content-full").html(response);
else alert('No results');
}
Here the deprecation 'notice' for the mysql_ functions: http://php.net/manual/en/changelog.mysql.php
You can look at passing a parameter to your script, generally like an id by which you can search in the db.
The easiest way to achieve this is by get parameters on the url
url: "content.php?param=2",
Then in php:
<?php $param = $_GET['param'];
...
This has been an ongoing issue for me. You all have already helped so much. However, I am stuck again. I cannot get my .ajax() to run. For some reason the .click() won't even work without if(field != text) above my .ajax() call, but I digress.
My question is: Why is my ajax() not functioning properly and if this gets fixed will the table is have displayed update after the query is sent to the database without a page refresh?
Here is my script:
<script type="text/javascript">
$(document).ready(function()
{
$(".edit_td").click(function()
{
$(this).children(".text").hide();
$(this).children(".editbox").show();
}).children('.editbox').change(function()
{
var id=$(this).closest('tr').attr('id');
var field=$(this).data('field');
var text=$(this).val();
var dataString = 'id= '+ id +'&field= '+ field +'&text= '+ text;
alert("made variables");
if(field != text)
{
alert("in if");
$.ajax({
type: "POST",
url: "table_edit_ajax.php",
data: dataString,
cache: false,
success: function(html)
{
$("#first_"+ID).html(first);
$("#last_"+ID).html(last);
}
});
}
else
{
alert('Enter something.');
}
});
// Edit input box click action
$(".editbox").mouseup(function()
{
return false
});
// Outside click action
$(document).mouseup(function()
{
$(".editbox").hide();
$(".text").show();
});
});
</script>
Here is my table_edit_ajax.php
<?php
//connect to DB
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
echo 'in table_edit';
$id = mysqli_escape_String($_POST['id']);
$table = "owners";
$field = mysqli_escape_String($_POST['field']);
$text = mysqli_escape_String($_POST['text']);
$query = "UPDATE ".$table." SET ".$field."='".$text."' WHERE ".$table."_id = '".$id."'";
mysqli_query($query);
//close connection
mysqli_close($con);
?>
The first argument to all mysqli functions is the connection, statement, or result object.
$id = mysqli_escape_String($con, $_POST['id']);
$table = "owners";
$field = $_POST['field'];
$text = mysqli_escape_String($con, $_POST['text']);
$query = "UPDATE ".$table." SET ".$field."='".$text."' WHERE ".$table."_id = '".$id."'";
mysqli_query($con, $query);
$field shouldn't be escaped, since it's not a string value. Therefore, you need to validate it carefully, to prevent SQL injection. Perhaps instead of allowing the client to submit the field name to update, have them submit an integer, which you look up in an array to convert to a field name.
In your AJAX call, you may have a problem due to not encoding your parameters properly. Change the dataString assignment to:
var dataString = { id: id, field: field, text: text };
Then jQuery will encode it for you.
you are sending a data string
var dataString = 'id= '+ id +'&field= '+ field +'&text= '+ text;
and retrieving it through $_POST.
first check what is in $_POST
and use $_GET instead of $_POST
and change post in ajax to get
and what is first and last in success callback??
Hi I'm trying dynamically remove database entries using JS and AJAX without refreshing whole page.
Here is my data.php file:
<?php
require_once('db.php');
if (isset($_GET['list'])) {
$query = "SELECT * FROM message";
mysql_query("SET NAMES 'UTF8'");
$qq=mysql_query($query);
$i = 1;
echo '<div id="rezult">';
while($ff = mysql_fetch_array($qq)){
echo '<div id="id'.$ff['id'].'">'.$i++.'. Name: '.$ff['name'].' Message:'.$ff['message'].'</div>';
}
echo '</div>';
}
?>
With this code I'm retrieving a data from mysql table:
index.php
function list() {
$.get('data.php?list=1', function(o) {
$('#list').html(o);
});
}
How to dynamically delete desired entry without refreshing a page?
tried to add this code below as a link to the entry, but it getting cut javascript:$.post( like that.
<a href="javascript:$.post('delete_post.php', { id: '$ff[id]' } );" class='delete_post' title='delete post'>delete post</a>
Thanks for advices
Be careful!, if someone make a call to your php file data.php?list=ANYNUMBER he will be able to delete any row, be sure you are using security tools to avoid that.If you use ajax and Jquery I think it will be easier.
try something like this:
$.ajax({
type: "POST",
url: "list.php",
data: { list: "1", session_id: session_ID }
}).done(function( msg ) {
alert( "Data deleted: " + msg );
});
where session_id is the value of the field (in your example is 1), session_id is when someone go to your page you assign him a SESSION_ID, after he click the delete button, you compare if the session ID that you assign is equal to the the session_id from the server (you avoid people from another site to call your list.php). If session_id from the ajax is equal to session session_id on the server allow to delete take a look to this: PHP Session Security