When I'm passing the two variables to my php I get Notice: Undefined index : name & Notice: Undefined index : parsed.
When I'm adding an echo for each variable, I get nothing.
Nothing is added in my database.
name = "myName";
parsed = someCode.toJSON();
parsed = JSON.stringify(parsed, null, '\t');
parsed = parsed.replace(/[\n\t]+([\d\.e\-\[\]]+)/g, '$1');
$.ajax({
url: 'js/function/scriptSave.php',
type: 'POST',
dataType: 'JSON',
data: {name : name, parsed : parsed},
success: function(result) {
alert("Success");
},
error: function(err){
alert('Error'+err);
}
});
The Ajax always returns me the error case : Error [object Object]
When I'm replacing my variables with text, everything works:
data: {name : 'name', parsed : 'parsed'}
And when I remove the json variable only it works.
I really don't understand what happens here..
[EDIT]
The variable containing the name is ok. But when I only put the variable containing the json, it doesn't work. But what is the problem with this variable ?
So far, I have tried:
var obj = {}; obj.name = 'myName'; obj.parsed = someCode.toJSON();
{data : JSON.stringify(obj)}
///////
{'name' : name, 'parsed' : parsed}
///////
{parsed : JSON.stringify(parsed)}
Here's my php:
<?php
if (!#mysql_connect('localhost', 'user', 'pwd')) {
die("Error");
} else {
mysql_select_db('database');
}
$parsed = $_POST["parsed"];
$name = $_POST["name"];
mysql_query("INSERT INTO object(name, parsed) VALUES ('".$name."', '".$parsed."')");
?>
[EDIT 2]
When I'm changing dataType from JSON to TEXT the ajax is in success case, but nothing is inserted in DB...
When I'm looking in my devTools in chrome everything semm to be ok :
General
Request Method :POST
Status Code: 200 OK
Response Headers
Content-Type: text/html
Request Headers
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Form Data
name : myName
parsed : {"another" : "value"}
[EDIT 3]
The problem seems to come from the json size... When I'm excluding some fields, everything seems to work. The problem is that in my databse, my field which will contain my JSON, is a LongText... The JSON size doesn't have to be the problem..
obj should be send as string, when calling the Ajax POST method.
So, combine the data into one Object and stringify it with JSON.stringify() method.
var obj = {};
obj.name = "your name";
obj.parsed = { "another" : "value" };
$.ajax({
url: 'js/function/scriptSave.php',
type: 'POST',
dataType: 'JSON',
data: JSON.stringify(obj),
success: function(result) {
alert("Success");
},
error: function(err){
alert('Error'+err);
}
});
Just remove the JSON.stringify().
Related
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?
i'm really stuck in ajax,
i don't have problem with simply sending values using form tag to PHP file.
but i want to make my program a bit more fancy using jquery and ajax.
and i'm totally stuck for few days.
what i'm trying to do is when i click on some text (study progress in my code), it turns into an editing box
and when i finish editing, it sends to variable "name" and update in PHP.
so i have to somehow send the value in the editing box in ajax,
but i keep having
" Undefined index: name "
i searched on google a lot, but i couldn't find the answer for me.
can i get some help from here?
i want to put the values of what i edited to the variable name ;
and want to check on server side.
how can i put the values of what i edited to variable name and send
to php in POST and check on server?
here is code that i made so far.
======HTML======
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/.../jquery/3.2.0/jquery.min.js"></script>
<div id="fullname">study progress</div>
<script>
$('#fullname').click(function(){
var name = $(this).text();
$(this).html('');
$('<input></input>')
.attr({
'type': 'text',
'name': 'fname',
'id': 'txt_fullname',
'size': '50',
'value': name
})
.appendTo('#fullname');
$("#txt_fullname").focus().val("").val(name);
});
$(document).on('blur','#txt_fullname', function(){
var name = $(this).val();
$.ajax({
type: 'POST',
url: 'practice_check.php',
data : { "name" : name },
success: function(){
$('#fullname').text(name);
alert(name);
location.replace("practice_check.php");
}
});
});
</script>
======PHP ( practice_check.php ) ======
<?php
$name = $_POST["name"];
echo $name;
?>
You were wrong. You need to specify the url and if you want to get data in PHP you need to add data. I made a simple code. You can check full detail at this link : http://api.jquery.com/jquery.ajax/
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. 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
var name = 'abc';
$.ajax({
url: 'practice_check.php',
type: 'POST',
data: {name: name},
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
first your ajax should be like this
$.ajax({
type: 'POST',
url: 'practice_check.php',
data : { "name" : name },
dataType: 'JSON',
success: function(response){
//response will be the output of practice_check.php
$('#fullname').text(name);
alert(response.data);
}
});
in you practice_check.php
$name = $_POST["name"];
// do your functions here .. then echo response like for example
if(strlen($name) < 3){ echo "oops invalid name"; }
else { echo "successfully checked with no errors"; }
I am trying to get some data sent to a PHP page to update PHP Session variables. I have tried several different examples that I found here but just can't seem to get any to work. The data is never received on the PHP page.
Here is my Javascript/jQuery:
var str, ProductID, sessionValues= [];
ProductID = "1";
str = {"ProductID": ProductID, "State": "UNCHECKED"};
sessionValues.push(str);
ProductID = "2";
str = {"ProductID": ProductID, "State": "CHECKED"};
sessionValues.push(str);
var postObj = {"sessionData": sessionValues};
console.log(postObj);
$.ajax({
type: 'POST',
contentType : 'application/json',
data: {'data': JSON.stringify(postObj)},
url: 'setSession.php'
}).done(function(response){
console.log(response);
}).fail(function(jqXHR, textStatus, errorThrown){
alert('FAILED! ERROR: ' + errorThrown);
});
This is what my data object looks like:
Then on the PHP side all I get is an error that I supplied an invalid argument to foreach. No matter how many times I repeat the sessionValues.push(str) my browser always reports 528 bytes sent.
<?php
$data = json_decode($_POST['data']);
print_r($data);
foreach ($data->sessionData as $key => $value) {
echo "$key => $value";
}
?>
You need to remove contentType : 'application/json', because that is not what you are sending.
When you do send as application/json properly ... stringifying the whole object , not just parts of it, then $_POST will be empty and you have to access the data using json_decode(file_get_contents('php://input'))
There is also no need to stringify your other object...jQuery will form encode it for you and you can access it as array
Try
JS
$.ajax({
type: 'POST',
data: {'data': postObj},
url: 'setSession.php'
}).done(function(response){
PHP
<?php
$data = $_POST['data'];
foreach ($data['sessionData'] as $key => $value) {
echo "$key => $value";
}
?>
Since some browsers caches the ajax requests, it doesn't responds as expected. So explicitly disabling the cache for the particular ajax request helped to make it work. Try to modify charlietfl's request as below:
$.ajax({
type: 'POST',
data: {'data': postValue},
cache: false,
url: 'postAjaxHandling.php'
}).done(function(response){
});
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.')"';
I am trying to send simple data to theservre, and I need a "rough and ready" way to do this.
This is what I have so far:
var emails = ['a#123.com', 'b#123.com', 'c#123.com'];
var ruff_json = "{ 'emails': [";
for (i in emails)
ruff_json += ((i == 0) ? '' : ', ') + '\''+emails[i]+'\'';
ruff_json += '] }';
jQuery.ajax({
type: 'POST',
url: '1.php',
data: ruff_json,
dataType: "json",
timeout: 2000,
success: function(result){
//do something
},
error: function (xhr, ajaxOptions, thrownError){
//do something
}
});
Using Firebug, I can see that the data is POSTed to the server - however, at the server, there is no data ($_POST is empty) - what am I doing wrong?
We post all of our data with json.
var myobj = { this: 'that' };
$.ajax({
url: "my.php",
data: JSON.stringify(myobj),
processData: false,
dataType: "json",
success:function(a) { },
error:function() {}
});
then in php we do
<?php
$json = json_decode(file_get_contents("php://input"), true);
// Access your $json['this']
// then when you are done
header("Content-type: application/json");
print json_encode(array(
"passed" => "back"
));
?>
This way we don't even mess with the post variables, and in general, its faster than having jQuery process them.
Your data field should contain an object with key-value pairs, because it gets encoded as POST key-values pairs.
data = {my_json: encoded_string};
Then on the PHP side you can access the data as:
$data = json_decode($_POST['my_json']);
PHP populates $_POST by parsing the data received. However, it only knows form-encoded data, JSON data cannot be parsed automatically. So $_POST will be useless in this case. You need to get the raw post data and parse it with json_decode.