ajax success but not sending post data - php

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.')"';

Related

How to use a jQuery data into a PHP code?

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

Pass ID from AJAX to PHP back to Modal

I have a PHP CODE:
if(isset($_POST['id'])){
$id = mysqli_real_escape_string($link,$_POST['id']);
$query = "SELECT * FROM `tb_cform` WHERE `ID`='$id'";
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_assoc($result)){
$message = '<div><h4>Subject: </h4><h5>'.$row['subj'].'<h5></div>';
$message .= '<hr><br>';
$message .= '<div><b>Message:<br>'.$row['message'].'</b></div>';
}
echo $message;
}
I need to pass the value from my AJAX code to the aforementioned code:
$('#messageModal').on('show', function(){
$.ajax({
type: "POST",
url: "viewmessage.php",
datatype: "html",
data:"data-id=" +id ,
success: function(r){
$('#messageBody').html( r );
}
});
});
The link that I am using is using a data-id="73" to pop open a model and populate the information.
My issue is, the value is not being passed and the body of the Modal is not being populated. Can anyone let me know why or what I did incorrect?
Check that your db returns something, so that $result is not null. Otherwise your $message will be empty.
If your query actually returns something and $message is still empty - try changing datatype to json:
JS
$.ajax({
type: 'POST',
url: 'php/server.php',
datatype: 'JSON',
data: {
dataId: someArbitraryId
},
success: function(data) {
var message = JSON.parse(data).message;
$('#message').html(message);
}
});
PHP
if (isset($_POST['dataId'])) {
$message = '';
// Some code
$result = array(
'message' => $message
);
echo json_encode($result);
}
Now even if the $message is empty or null - server should return array with empty string.
in js
data:{dataId : id}, // I'm sure this will work but data:"data-id=" +id, may work as well
in php
$_POST['dataId'] // instead of $_POST['id']
If this not work with you there are some steps you need to do
1- alert(r) on ajax success function and check for errors
2- I don't know what is id and where you get it from so try to alert(id) and see if it output an expected value or not
3- you may need to use shown.bs.modal instead of show take a look at here
4- in js try to get the a data-id by using $(a[data-target="#messageModal"]).data('id') instead of id
so your code should looks like
in js
$('#messageModal').on('shown.bs.modal', function(){
$.ajax({
type: "POST",
url: "viewmessage.php",
datatype: "html",
data:{ dataId : $(a[data-target="#messageModal"]).data('id')},
success: function(r){
$('#messageBody').html( r );
}
});
});
and also in php use $_POST['dataId'] instead of $_POST['id']
So i figured out the issue, it is now displaying the results, however, $(a[data-target="#messageModal"]).data('id'); will not pass the value, i had to use: var id = $("#messageID").attr("data-id");. This is working, but becuase there are multiple instances of #messageID listed, it is only showing the first result becuase you cannot have duplicate ID tags with the same information.  
​
My question is how can i assign or get a value added after #messageID like an array using[ ] to assign a value and have it look for that then get the data-id value to pass?

how do i pass datastring parameter for jquery's .ajax() function properly?

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>');
}
});

$_GET the variable of javascript to php

my ajax is:
add = 'request';
full_val = 'barrack obama';
$.ajax({
url: 'plugins/add_friend.php',
data: full_val+'='+add,
success: function(data)
{
}
});
if the javascript variable value changes depending on the conditions, then how will i $_GET[] the variable full_val? I want it to be something like:
$_GET[full_val]
is there a way to pass the variables of javascript to php?
If you want the literal index full_val, then use it in the query string:
data: 'full_val='+add,
So that in PHP, you'd be able to use $_GET['full_val']
Alternatively, you could also put an object in that field:
data: {full_val: full_val, add: add},
Here is the description:
data
Type: PlainObject or String or Array
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.
Your data just has the values and does not have the keys. See below for how to pass the keys and values.
add = 'request';
full_val = 'barrack obama';
$.ajax({
url: 'plugins/add_friend.php',
data: {full_val:full_val,add:add},
success: function(data)
{
}
});
In your PHP use $_GET['full_val'];
send your values with data parameter correctly and add type:get to define GET method
add = 'request';
full_val = 'barrack obama';
$.ajax({
type: "get",
url: 'plugins/add_friend.php',
data: {'full_val':full_val,'add':add},
success: function(data) {
}
});
Then you will get values on php :-
use $_GET['full_val'] rather $_GET[full_val]
Try Using this
add = 'request';
full_val = 'barrack obama';
$.ajax({
url: 'add.php',
data: 'full_val='+add,
success: function(data)
{
alert(data);
}
});
You can use the .get() method. The variables you can set using an object literal. For example:
$.get("/plugins/add_friend.php", {
add: "request",
full: "Barrack Obama"
}).done(function(data) {
console.log("Status:", data.status);
console.log("Received:", data.received);
});
And the PHP could be done something like this:
$add = filter_input(INPUT_GET, 'add', FILTER_SANITIZE_STRING);
$full = filter_input(INPUT_GET, 'full', FILTER_SANITIZE_STRING);
echo json_encode(array(
'status': 'OK',
'received': "{$add} and {$full}",
));

AJAX POST TO PHP

dataString is :
{"feedback_type":"000","error_type":"","textarea":"blahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblah"}
I used the following code to post to the PHP:
// ajax post
$.ajax({
type: "POST",
url: "core/poster.php" ,
data: dataString,
success:function()
{
alert("Success!");
}
});
return false;
And php file:
<?php
require 'Class_DBOperation.php';
require 'global.php';
// Establish Database Connection
$dbOperation = new class_DBOperation(DBHOST,DBUSER,DBPWD,DBNAME,DBCHARSET);
// Receive dataString
$content=$_POST['feedback_type'];
$run=mysql_query("insert into reports values (NULL, '".$content."')");
?>
The problem is why $content is empty?
What should I do ? any ideas?
Add a response in your success function and alert it
$.ajax({
type: "POST",
url: "core/poster.php" ,
data: dataString,
success:function(response)
{
alert(response);
}
});
And in your poster.php file try adding the following to the top within the PHP tag.
ini_set("display_errors", 1);
var_dump($_POST);
This should give you a place to start and debug what's going on.
This isnt a direct solution, but it may help you find out what is wrong. Try dumping out the contents of your $_POST superglobal, this will inform you of how the data was received. Try something like:
print '<pre>';
print_r ($_POST);
print '<pre>';
Remove your double quotes for parameter names
{
feedback_type: "000",
error_type: "",
textarea: "blahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblah"
}
You're sending a JSON string as the parameter string.
Parameters should be formatted as follows:
foo=bar,foo2=bar2,foo3=bar3 etc...
You could either reformat the string to follow the norm:
JS:
var dataString = "feedback_type=000&error_type=&textarea=blahblahblah";
PHP:
echo $_POST['feedback_type']; // 000
echo $_POST['error_type']; // null
echo $_POST['textarea']; // blahblahblah
or you could pass the JSON string as a POST parameter:
JS:
var jsonObject = {
"feedback_type" : "000",
"error_type" : "",
"textarea" : "blahblah"
}
var jsonString = '{"feedback_type":"000","error_type":"","textarea":"blahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblah"}';
// OR
var jsonString = JSON.stringify(jsonObject);
var dataString = "json_string=" + jsonString;
PHP:
// String - suitable for database input
echo $_POST['json_string']; // String: {"feedback_type":"000","error_type":"","textarea":"blahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblah"}
// Parse into array
$json_array = json_decode($_POST['json_string']);

Categories