I have below jquery AJAX,
var reply_content = $('#summernote_1').code();
$.ajax({
type:"POST",
url: "<?php echo base_url();?>index.php/test/send_reply/"+<?php echo $testinfo->test_id;?>,
data: $("#test_fm").serialize()+'&file=' + file + '&test_subject=<?php echo $testinfo->testsubject;?>' +'&reply_content=' + reply_content,
});
i have file variable is array contains like below
array([0]=> a [1]=>b),
This was returned with other function which i am passing in AJAX,
How can i pass this in AJAX?
var reply_content = $('#summernote_1').code();
$.ajax({
type:"POST",
url: "<?php echo base_url();?>index.php/test/send_reply/"+<?php echo $testinfo->test_id;?>,
data: {$("#test_fm").serialize()+'&file=' + file + '&test_subject=<?php echo $testinfo->testsubject;?>' +'&reply_content=' + reply_content},
});
and you can use serilizeArray()
If you are trying it in php then you can try like this:
$url = urlencode(serialize($your_array))
append $url in the data
data: {$("#test_fm").serialize()+"&file=<?php echo $url; ?>&test_subject=<?php echo $testinfo->testsubject;?>" +"&reply_content=" + reply_content}
and to restore the variable you can use
$arrVar = unserialize(urldecode($_POST['file']))
You can use serializeArray() to create an object you can add too.
Its also a good idea to separate your php from you js where possible to aid readability:
var url = "<?php echo base_url() . 'index.php/test/send_reply/' . $testinfo->test_id;?>";
var test_subject = "<?php echo $testinfo->testsubject;?>";
var data = $("#test_fm").serializeArray();
data.push(
{
file: file,
test_subject: test_subject
}
);
$.ajax({
type:"POST",
url: url,
data: data
});
Related
I need help on how to post and retrieve multiple variables using Ajax Post. I actually needed to retrieve the posted variables for SQL query. See below the Ajax Code where i needed to include variable names selschool, selprogram, selsession to the post
<script>
$("#session").change(function()
{
$("#loding2").show();
var id=$(this).val();
var dataString = 'id='+ id;
var selschool=document.getElementById("selectedschool").val();
var selprogram=document.getElementById("selectedprogram").val();
var selsession=document.getElementById("selectedsession").val();
$("#semester").find('option').remove();
$("#class").find('option').remove();
document.getElementById("selectedclass").value= " ";
document.getElementById("selectedsemester").value= " ";
$.ajax
({
type: "POST",
url: "get_class.php",
data: dataString,
cache: false,
success: function(html)
{
$("#loding2").hide();
$("#class").html(html);
}
});
});
</script>
Also see below PHP script where i wanted to use the posted variable for the query;
<?php
include('dbconfig.php');
if($_POST['id'])
{
$id=$_POST['id'];
// Todo: I actually needed something like where session SELECT * FROM class where session_id=$id and program_id="selprogram" and school_id="selschool"
$stmt = $DB_con->prepare("SELECT * FROM class where session_id=$id ");
$stmt->execute(array(':id' => $id));
?><option selected="selected">Select Class :</option>
<?php while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
?>
<option value="<?php echo $row['class_id']; ?>"><?php echo $row['class_name']; ?></option>
<?php
}
}
?>
Let me explain the solution
consider the ajax call to demo.php
$.ajax({
url: 'demo.php',
type: 'post',
data: {
'name': 'abc',
'phone': '1234567899'
}, //data is in json form
success: function(res) {
console.log(JSON.parse(res)); //parsing because we will pass the data from demo.php in encoded form you will get it.
}
});
now in demo.php you will access data as $_POST['name'] and $_POST['phone']. lets pass the same to ajax call. will store it in array and will pass it.
<?php
$Arr = [];
$Arr[0] = $_POST['name'];
$Arr[1] = $_POST['phone'];
echo json_encode($Arr);
?>
like this, we can pass data to ajax and can pass the data from PHP file to request.
Hope that you got the result. Thank you.
I have data in localStorage and POST successfully to the self php file using ajax as code below:
<script type="text/javascript">
var cartID = JSON.parse(sessionStorage.getItem("magiohang"));
console.log("your cart ID is:"+cartID);
$.ajax({
type: "POST",
url: "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>",
data: {cartID: cartID},
success: function(data){alert("data transfered successfully")}
});
</script>
then I want to recall this data to a variable inside this php file so that I can send it to my email. Code as below:
<?php
$name = "";
error_reporting(E_ALL); ini_set('display_errors', 1);
if (isset($_POST["cartID"])) {
$name = $_POST["cartID"];
}
echo $name."\n";
$values = json_decode($name);
echo "your cartID is: ".$values."\n";
?>
I test it in inspect view there is no error message but the variable $name doesnot have recalled data. Please help me to fix it. Thank you.
You are most likely missing the JSON.stringify call on your data:
$.ajax({
type: "POST",
url: "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>",
data: JSON.stringify({cartID: cartID}),
success: function(data){alert("data transfered successfully")}
});
I am trying to get data from one php page and pass it to another page using Ajax.
JS :
$.ajax({
url: "action.php",
success: function(data){
$.ajax({
url: "data.php?id=data"
}
});
action.php :
<?php
$test= 1;
?>
data.php :
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="" src="action.js"></script>
<?php
$id = $_GET['id'];
echo $id;
?>
First of all, you need to echo your data in action.php, and second, use data parameter of AJAX request to send data to data.php.
Here's the reference:
jQuery.ajax()
So the organization of pages should be like this:
JS :
$.ajax({
url: "action.php",
success: function(data){
$.ajax({
url: "data.php",
data: {id: data},
success: function(data){
// your code
// alert(data);
}
});
}
});
action.php :
<?php
$test = 1;
echo $test;
?>
data.php :
<?php
$id = $_GET['id'];
echo $id;
?>
Try to use $.get() method to get/send data :
$.get("action.php",{}, function(data){
//data here contain 1
$.get("data.php", {id: data}, function(id){
alert(id);
}
});
Just echo $test since just the data printed in page will return as responce to the query request.
action.php :
<?php
$test=1;
echo $test;
?>
Hope this helps.
For example,
Test
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="" src="action.js"></script>
action.js
$('.dataClass').click(function(){
var value=$(this).attr('data-value');
$.ajax({url:"Ajax_SomePage.php?value="+value,cache:false,success:function(result){
alert("success");
}});
});
Ajax_SomePage.php
<?php
$value = $_GET['value'];
echo $value;
?>
To get data as response in ajax call, you need to echo the result from your php page; action.php page.
echo $test = 1;
In your provided code
$.ajax({
url: "data.php?id=data"
} // closing bracket is missing
you are sending the string data as id to data.php page. Instead you have to append the result with the url using + symbol like shown in the below code.
$.ajax({
url: "action.php",
success: function(data){
$.ajax({
url: "data.php?id="+data
})
}
});
I am using CKEditor version 4 and posting data from editor through ajax call however sometimes all the data post successfully and sometimes it just truncates it. As far I know the reason behind this is when editing the data it adds " " which cause this to truncate. Any help how to completely resolve this issue ?
My code
<script type="text/javascript">
var editor = CKEDITOR.replace('message');
function checkSubmit() {
for(var instanceName in CKEDITOR.instances){
CKEDITOR.instances['message'].updateElement();
}
var dataString = "action=<?php echo $_REQUEST['action']; ?>" +
"&id_user=<?php echo $_REQUEST['id_user']; ?>" +
"&sub_id=<?php echo $_REQUEST['subject_id']; ?>" +
"&subject_id=<?php echo $_REQUEST['actual_subject_id']; ?>" +
"&message="+ CKEDITOR.instances['message'].getData()+
"&subject_name="+$("#subject").text() +
"&occurence_name="+$("#occurency").text();
$.ajax({
type: "POST",
url: "data/user-student-data.php",
data: dataString,
success: function(data) {
// close window
parent.closeDistributeModal( 1, "<?php echo $_REQUEST['action']; ?>", <?php echo $_REQUEST['id_user']; ?>,<?php echo $_REQUEST['subject_id']; ?> );
}
});
}
</script>
That is a very difficult way to gather up the data. Try this instead:
var data = {};
data.subject_id = '<?php echo $_REQUEST['actual_subject_id']; ?>';
data.id_user = '<?php echo $_REQUEST['id_user']; ?>';
data.action = '<?php echo $_REQUEST['action']; ?>';
data.sub_id = '<?php echo $_REQUEST['subject_id']; ?>';
data.occurence_name = $("#occurency").text();
data.subject_name = $("#subject").text();
data.message = CKEDITOR.instances['message'].getData();
$.ajax({
type: "POST",
url: "data/user-student-data.php",
data: data,
success: function(returnedData) {
// whatever you had here
}
});
Also
// You can remove the for completely.. THIS:
for(var instanceName in CKEDITOR.instances){
CKEDITOR.instances['message'].updateElement();
}
// Is the same as this (you don't use the instanceName variable at all)
CKEDITOR.instances['message'].updateElement();
i am sending an array from one page to another through ajax.i used JSON object for this purpose.I am able to send but i am not able to capture in the ajax page.Please help me how to capture the array values.
javascript:
var jsonString = JSON.stringify(dataString);
$.ajax({
type: "POST",
url: "ajaxpage.php",
data: {data : jsonString},
cache: false,
success: function(response){
alert("ok");
$('#test').html(response);
}
});
PHP page:
$data = json_decode(stripslashes($_POST['data']));
// here i would like use foreach:
foreach($data as $d){
echo $d;
}
please help me in this regard.
I am stuck up here
If you want to decode the JSON into an associative array, you should specify that in json_decode:
Replace
$data = json_decode(stripslashes($_POST['data']));
With
$data = json_decode(stripslashes($_POST['data']), true);
See json_decode reference for more information
Also, is dataString possibly already a JSON string?
I think this is what you want, I have tried and it works
in your php:
<?php
$data = ($_POST['data']);
foreach($data as $d){
echo stripslashes($d);
}
?>
in your jsvascript/jquery:
<script>
$(document).ready(function(){
$('a').on('click',function(){
var dataString = {
'id':'1',
'name':'peter parker',
'age':'unknown',
'role':'spiderman'
}
$.ajax({
url: "<?php echo $this->webroot;?>test_1.php",
data: {'data':dataString},
type: "POST",
cache: false,
success: function(response){
alert("ok");
$('#test').html(response);
}
});
})
})
</script>
in your html
Click Me
<div id="test"></div>