I want to use the value of limit and offset into my PHP code but I can't.
Here is my code:
var maxData = 0;
var limitt=6;
var offsett=1;
$.ajax({
url: "../model/conn.php",
type: 'POST',
data: 'getData='+'&limit='+limitt+'&offset='+offsett,
}).done(function( data ) {
$("#d1 ").html(data);
while (limitt<maxData){
limitt= limitt+6;
offsett=offsett+6;
}
});
<?php
if(isset($_POST['getData'])) {
$serv = "localhost";
$user = "root";
$psrd = "";
$db = "nonc";
$conn = mysqli_connect($serv, $user, $psrd, $db);
$limit=$_POST['&limit'];
$offs=$_POST['&offset'];
$sql = "SELECT * FROM non_confor limit $offs, $limit;";
$resltt = mysqli_query($conn, $sql);
$checkk = mysqli_num_rows($resltt);
?>
When I run my PHP page they show me that I have errors on $limt and $offs, because they don't receuve the data from AJAX.
First thing, you are using POST method for form submission and passing data as a query string which is making an error. Correct that as below:
$.ajax({
url: "../model/conn.php",
type: 'POST',
data: {
'getData': 1, // passing 1 as you are using getData in php.
'offset': offsett,
'limit': limitt
},
}).done(function(data) {
$("#d1 ").html(data);
while (limitt<maxData){
limitt= limitt+6;
offsett=offsett+6;
}
});
After this, you need to make modification in your PHP code as below:
$limit=$_POST['limitt'];
$offs=$_POST['offsett'];
After this, your code should work fine. Hope it helps you.
This is a syntax problem , here is the correction :
$.ajax({
type: 'POST',
url: '../model/conn.php',
data: {
'getData':limit,
'offset':offsett
},
success: function(msg){
// rest of your code
}
});
Data attribute should have as value a json format
Related
There is some way to return value from PHP in to ajax? Or some other way?
simple jQuery call:
$(document).ready(function(){
var quizCount= 1;
$("button").click(function(){
quizCount = quizCount+1;
$("#quiz").load("load-quiz.php",{
quizNewCount : quizCount
});
});
});
PHP form:
$quizNewCount = $_POST['quizNewCount'];
$sql= "SELECT* FROM quiz WHERE quizid =$quizNewCount";
$result = $conn->query($sql);
mysqli_set_charset($conn,"utf8");
if ($result->num_rows > $quizNewCount)
{
return $quizNewCount=1;
}
I try that, but without effect. Anyone know how to do that? I don't wont number, but changing value because database will be increased every month.
Use ajax instead of load. Here is an example code. Use GET instead of POST. Explanation here.
$.ajax({
type: 'GET',
url: 'load-quiz.php',
data: {quizNewCount : quizCount},
success: function (result) {
console.log(result);
}
});
// Ajax calling
post_data = {quizNewCount : quizCount}
$.ajax({
method: 'post',
dataType: 'json',
data: post_data,
url: 'load-quiz.php',
success: function (data) {
result = data;
alert(result)
}
})
// action part or processing part
$quizNewCount = $_POST['quizNewCount'];
$sql= "SELECT* FROM quiz WHERE quizid =$quizNewCount";
$result = $conn->query($sql);
mysqli_set_charset($conn,"utf8");
if ($result->num_rows > $quizNewCount) {
$quizNewCount=1;
//as dataType is json so we need to enocde the data in the json format before sending it
echo json_encode($quizNewCount);
}
var username = $('#username').val();
var dataString = 'username=' + username;
$.ajax({
type: "POST",
url: "signinout.php",
data: dataString,
success: function() {
$('.user').html('<span>Welcome <span id="loggedUser">' + username + '</span>!</span> <a id="signOut" onclick="window.location.reload()">SIGN OUT</a>');
}
});
using the above code, my username variable is not being passed on correctly, I'm assuming something is wrong with the way I coding the datastring parameter but I'm not sure how to do it correctly.
Below is the php code that I am using in signinout.php to insert the username into the database, the username field is not being entered with each new entry into the database.
$username = protect($_POST['username']);
$time = time();
$sql = "INSERT INTO users
(username, join_date)
VALUES
('$username', '$time')";
$result = mysqli_query($cn, $sql) or
die(mysqli_error($cn));
Your "best" datastring depends on your needs in the server side part. As an example, this jquery-ajax call send a object to a server side action (PHP) :
var mydata = null;
mydata = "hellostring=1";
mydata = { title: "some" , value: "thing" };
mydata = [1,2,3];
$.ajax({
cache: false, type: 'post', async: true,
data: mydata,
url: 'some-script.php',
success: function(resp){
console.log("OK",resp);
},
error: function(e){
console.log(e.responseText);
}
});
As result, in your serve side you may have this script, which will return the same as you send:
// some-script.php
<?php
echo print_r($_POST,true);
?>
The outputs, for each kind of data (see the mydata variable) is:
Case: mydata = "hellostring=1";
Array( [hellostring] => "1" )
this mean, in serverside, you can:
$_123 = $_POST["hellostring"];
Case mydata = { title: "some" , value: "thing" };
As result, you get:
Array
(
[title] => some
[value] => thing
)
So you can:
$title = $_POST['title']; $value = $_POST['value'];
Case mydata = [1,2,3];
Surprise, this doesnt work, :) , you should wrap it, in this form:
mydata = { some : [1,2,3] }
So, you can proceed in your server-side the same as the previous case.
Note:
To avoid get hacked: (PHP CASE example) filter your input using:
http://php.net/manual/es/function.filter-input.php
More
In order to have a more advanced data handling in your server side part, (that is: in the script who receive the ajax request) , you can make usage of json, in this way:
Let start by supposing you are sending a object via javascript:
// in your client part,
mydata = { title: "some" , value: "thing", mydog: "sammy" };
..do your ajax call stuff here..
And, in your server side:
<?php
// some-script.php
$obj = json_decode(file_get_contents('php://input'));
echo $obj->title; // output: "some"
echo $obj->value; // output: "thing"
echo $obj->mydog; // output: "sammy"
?>
try passing it as a regular javascript object
var dataObj = {'username': username};
$.ajax({
type: "POST",
url: "signinout.php",
data: dataObj,
Try using data: "username="+username, instead
var username = $('#username').val();
$.ajax({
type: "POST",
url: "signinout.php",
data: "username=" + username,
success: function() {
$('.user').html('<span>Welcome <span id="loggedUser">' + username + '</span>!</span> <a id="signOut" onclick="window.location.reload()">SIGN OUT</a>');
}
});
I tried until this morning to retreive data from Mysql and ajax.
This is my code :
HTML :
$.ajax({
//type:'GET',
url: "/lecture_message_pilote.php",
data: ({location_id:zlid}),
contentType: "application/json; charset=utf-8",
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
var zidpilote = data[0]; //get id
var zmessage = data[1]; //get name
alert(zmessage);
}
});
And PHP :
$result = mysql_query("select * from Test_phoneGAP_message where IDPILOTE = '".$location_id."'");
$array = mysql_fetch_row($result);
echo (json_encode($array));
mysql_close();
I've the error message : UNDEFINED for alert(zmessage);
If I use the PHP request :
$result = mysql_query("select * from Test_phoneGAP_message");
I have a good result. I think my PHP don't take the $location_id.
try to access the parameter via the $_REQUEST["location_id"] element of php.
i.e.
$result = mysql_query("select * from Test_phoneGAP_message where IDPILOTE = '".$_REQUEST["location_id"]."'"); $array = mysql_fetch_row($result);
My jQuery autosave is running the success function, but not updating the MySQL database. What am I doing incorrectly?
jQuery:
function autosave() {
var t = setTimeout("autosave()", 5000);
var translation = $("#doc-translation").val();
if (translation.length > 0) {
$.ajax({
type: "POST",
url: "update-draft-submission.php",
data: translation,
cache: false,
success: function() {
$(".autosaved").empty().append("saved");
}
});
}
}
PHP:
<?php
session_start();
//retrieve our data
$iddoc = $_GET['iddoc'];
$trans = translation;
$transowner = $_SESSION['userid'];
$true = 1;
include "../dbconnect.php";
$query = "UPDATE translations
SET trans='$trans'
WHERE iddoc='$iddoc'
AND transowner='$transowner'";
mysqli_query($query);
mysqli_close();
echo "Saved";
?>
You are not fetching the data in your PHP correctly:
$iddoc = $_GET['iddoc'];
$trans = translation;
iddoc is not passed as a GET parameter anywhere
"translation" is not a variable (neither do I think it is a constant)
Your SQL will break if it does not get the required values in the query.
Update your javascript so:
$.ajax(
{
type: "POST",
url: "update-draft-submission.php",
data: data: {translation:translation,iddoc:"XXX"},
cache: false,
success: function()
{
$(".autosaved").empty().append("saved");
}
});
Replace XXX with your iddoc value.
Then in PHP fetch them as:
$iddoc = $_POST['iddoc'];
$trans = $_POST['translation'];
Hi i have this simple code:
var datastring="123";
$.ajax({
url: 'actualizarimagen.php',
type: 'post',
dataType: 'text',
data: datastring,
cache: false,
success: function(response){
$('.msg1').html(response);
},
error: function(response){
$('.msg1').html(response);
}
});
And in actualizarimagen.php:
$desc_larga = print('<pre>') & print_R($_POST) & print('</pre>');
$insertSQL = sprintf("INSERT INTO prueba (texto) VALUES ($desc_larga)");
I get the success message, but in the database always saves 1. I tried changing everything, the dataType, the success, error, complete functions but it doesn't work. I was searching but any answers couldn't help me.
Thanks.
Edit: Added response
Your datastring should contain data encoded as application/x-www-form-urlencoded
e.g.: var datastring="foo=123";
It is better not to pass a string to jQuery at all. Pass it an object and let it handle the encoding for you.
e.g.: data: { "foo": "123" }
data
Object, String
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
You are just sending up 123 to the server.
It should be something like
var datastring="myField=123";
or
var datastring = {"myField" : 123 };
and with the PHP you would read it
$_POST["myField"]
to send the data, there are format to be followed.
Like
var datastring="var1=123&var2=abcd";
or
var datastring=[{name:'var1',value:123},{name:'var2',value:'abcd'}];
The second format (array of object name value) is like <input type="text" name="var1" value="123"> where html input element has name and value to be posted.
Then, you can get the value by :
$_POST['var1']
or
$_POST['var2']
An example to achieve this easily could be:
JS:
var datastring="123";
$.post('actualizarimagen.php', { datastring:datastring }, function(data){
if(data != 0){
$('.msg1').html('correcto');
} else {
$('.msg1').html('error');
}
});
In your actualizarimagen.php:
if($_POST() && isset($_POST['datastring'])){
/* Connect to DB */
$link = mysql_connect('server', 'user', 'pwd');
if (!$link) {
// No connection
print(0);
exit();
}
$db = mysql_select_db('db', $link);
if (!$db) {
// DB selection error
print(0);
exit();
}
/* Sanitize the value */
$datastring = mysql_real_escape_string($_POST['datastring']);
// I don't understand here what you tried to do with $dec_larga but this is what I thought
$desc_larga = "<pre>".$datastring."</pre>";
/* Insert to DB */
$sql = "INSERT INTO prueba (texto) VALUES ('$desc_larga')";
if(mysql_query($sql,$link)){
// Everything is Ok at this point
print(1);
} else {
// Error happened in your SQL query
print(0);
}
}
In the ajax call:
data: my_var : datastring,
in the php:
$desc_larga = '<pre>'.$_POST['my_var'].'</pre>';
try replacing
type: "post",
with
type: "POST",
and your datastring should be like this :
single=Single&multiple=Multiple&multiple=Multiple3&check=check2&radio=radio1
as explained here:
http://api.jquery.com/serialize/
var datastring = "123";
$.ajax({
url: 'actualizarimagen.php',
type: 'post',
dataType: 'text',
data: {data : datastring},
cache: false
}).always(function(response) {
$('.msg1').html(response);
});
And in actualizarimagen.php:
$desc_larga = '<pre>'.$_POST['data'].'</pre>';
$query = '"INSERT INTO prueba (texto) VALUES ('.$desc_larga.')"';