How can i pass $_GET to another php via ajax? - php

Im going to make a kind of explanation about my problem:
Trying to integrate fullcalendar on a web that takes data via mysql & ajax, i want to display booking dates on calendar only if its related with one "house" in particular when this one is clicked.
So, in my php i receive $pisoid = $_GET['piso']; then i use in the same page a js script and i pass that data via post ajax:
var pisoid = "<?php echo $pisoid; ?>" ;
$.ajax({
url: 'process.php',
type: 'POST', // Send post data
data: 'type=fetch',
async: false,
success: function(s){
json_events = s;
}
});
Also i use this:
$('#calendar').fullCalendar({
events: JSON.parse(json_events),
//events: [{"id":"14","title":"New Event","start":"2015-01-24T16:00:00+04:00","allDay":false}],
utc: true,
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
editable: true,
droppable: true,
slotDuration: '00:30:00',
eventReceive: function(event){
var title = event.title;
var start = event.start.format("YYYY-MM-DD[T]HH:mm:SS");
$.ajax({
url: 'process.php',
data: 'type=new&title='+title+'&startdate='+start+'&zone='+zone+'&pisoid='+pisoid,
type: 'POST',
dataType: 'json',
success: function(response){
event.id = response.eventid;
$('#calendar').fullCalendar('updateEvent',event);
},
error: function(e){
console.log(e.responseText);
}
});
$('#calendar').fullCalendar('updateEvent',event);
console.log(event);
});
Then, on my process.php i try to make:
$space = $_POST['pisoid'];
$events = array();
$query = mysqli_query($con, "SELECT * FROM calendar where pisoid='$space'");
while($fetch = mysqli_fetch_array($query,MYSQLI_ASSOC))
{
$e = array();
$e['id'] = $fetch['id'];
$e['title'] = $fetch['title'];
$e['start'] = $fetch['startdate'];
$e['end'] = $fetch['enddate'];
$allday = ($fetch['allDay'] == "true") ? true : false;
$e['allDay'] = $allday;
array_push($events, $e);
}
echo json_encode($events);
Where i put a number instead of $space in my sql query everythings its ok, but in this $space i dont receive a proper number, So how can i make this stuff???

You're passing the data as if it was a URL in the fullcalendar function
Change this:
data: 'type=new&title='+title+'&startdate='+start+'&zone='+zone+'&pisoid='+pisoid,
To:
data: {type: 'new', title: title, startdate: start, zone: zone, pisoid: pisoid}
Like this you're passing different variables (type, title, etc...) To the superglobal you're using in the PHP file.
Explanation:
The data array is constructed as such: 'nameofattribute': variable
And JavaScript will take care of creating the URL/posting the data
Your problem is that you're trying to get the "GET" parameters of the data you're passing (without a key might I add) with the POST variable. Try switching them around, it should help

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

How to insert data to database using multiple array using POST method with ajax:

I read similar answer here in this question: How to insert into MYSQL row from multiple $_POST arrays and How to insert into MYSQL row from multiple $_POST arrays but the problem is these answers do not work in my code. Is it because im using an ajax? and i only get the value of the first array.
If i also place the variable declaration inside the for loop it is not working too.
Here is my ajax:
var name = [];
$('input[name="name[]"]').map(function(){ name.push($(this).val()); }); var studid = [];
$('input[name="studid[]"]').map(function(){ studid.push($(this).val()); }); var nameStr = name != '' ? '&name='+ name : '';
var studStr = studid != '' ? '&studid='+ studid : '';
var dataString = 'subject='+ subject + '&section=' + section + studStr + nameStr;
$.ajax({ type: "POST", url: 'save.php', data: dataString, dataType: "html",
success: function(data) {
$('input#subject-field').val('');
$('input#section-field').val('');
$('input.record-input-forms').val('');
$('#status-message').css({"color":"#39b1c6"});
$('#status-message').html('Save successfully',function(){
$('#status-message').fadeOut(2000); }); },
error:function (xhr, ajaxOptions, thrownError){
alert(thrownError); } });
return false;
});
Here is my php:
if(isset($_POST['studid']) || isset($_POST['name'])){
$studid = array_map(mysql_real_escape_string, explode(",",$_POST['studid']));
$name = array_map(mysql_real_escape_string, explode(",",$_POST['name']));
for ($i=0; $i<count($studid); $i++){
$sql_1 = "INSERT INTO tbl_student(StudentID, StudentName, SubjectID) VALUES ('".$studid[$i]."', '".$name[$i]."', LAST_INSERT_ID())";
mysqli_query($con,$sql_1);
}
}
use mysql_insert_id();
instead of LAST_INSERT_ID()
You're not sending data correctly from the jQuery and its seems you'r mixing arrays and string together.
This is a simple request that posts studid-array from jQuery
var saveData = $.ajax({
type: 'POST',
data: {studid: studid},
url: 'save.php',
dataType: 'html'
});
saveData.done(function(data) {
$('input#subject-field').val('');
$('input#section-field').val('');
$('input.record-input-forms').val('');
$('#status-message').css({"color":"#39b1c6"});
$('#status-message').html('Save successfully',function(){
$('#status-message').fadeOut(2000); });
});
saveData.fail(function(ts) {
alert(ts.responseText);
});
When save.php is called, $_POST['studid'] would be set (if there are anything in the array)
If you instead do like this:
var saveData = $.ajax({
type: 'POST',
url: 'save.php?studid=' + studid,
dataType: 'html'
});
When save.php is called, $_GET['studid'] would be set (if there are anything in the array). The best way though is to use data-option in the ajax-function call (in my first case). If you choose to use this option you would have to serialize the stuid-array before putting it in as a part of an url.
UPDATE
If you want to pass multiple arrays you would have to do something like this:
var saveData = $.ajax({
type: 'POST',
data: {studid: studid, name_arr2: data_arr2},
url: 'save.php',
dataType: 'html'
});

Fecting event in Full Calender using codeigniter?

I successfully store and retrive event from database using ajax now how to show this into events in fullcalnder??
Saving event in Database: Using Ajax.
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
defaultDate: '2015-02-12',
selectable: true,
selectHelper: true,
select: function(start, end) {
var title = prompt('Event Title:');
var eventData;
if (title) {
eventData = {
title: title,
start: start,
end: end
};
$.ajax ({
url: "http://localhost/phplec/sms/calendar/test",
type: 'POST',
data: {'title': title, 'start' : start.format(), 'end': end.format()},
success: function(msg) {
alert(msg);
}
});
Controller: Here i Accept Ajax request and connect to DB
function test() {
$this->load->model('calendar_model');
$data = array(
'title' => $_POST['title'],
'start' => $_POST['start'],
'end' => $_POST['end']
);
$this->calendar_model->add_record($data);
echo "working";
}
Now I want To show my database in fullCalander on page laod.
I successfully get event from database and convet it into json now how to show it on view.
function get_records()
{
$data = $this->db->get("calendar_test");
$json_data = json_encode($data->result_array());
var_dump($json_data);
}
How i Show this event Dynamically
$.ajax ({
url: "http://localhost/phplec/sms/calendar/get_records",
type: 'GET',
dataType: "html", //expect html to be returned
success: function(response){
alert(response)
}
I successfully get event json in fullcalander.js now how to pass this to events.
OK from what I understand you want to click on a calendar day, it prompts you for a title, then you submit the data to the DB and then you want to see it again. These are the steps you need to take:
you need to use the events method so that fullcalendar knows how to fetch events when its loaded, like this:
$('#calendar').fullCalendar({
// ....your other methods...
events: 'http://localhost/phplec/sms/calendar/get_records' //this should echo out JSON
});
after your ajax succesfully saves the events in the database, then call the refetchEvents method like this:
$('#calendar').fullCalendar('refetchEvents');
In the end, this is how I would do it:
var myCalendar = $('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
events: 'http://localhost/phplec/sms/calendar/get_records',
defaultDate: '2015-02-12',
selectable: true,
selectHelper: true,
select: function(start, end) {
var title = prompt('Event Title:');
if (title) {
var eventData = {
title: title,
start: start.format(),
end: end.format()
};
$.ajax({
url: "http://localhost/phplec/sms/calendar/test",
type: 'POST',
data: eventData,
success: function(result) {
if(result === "working"){
myCalendar.fullCalendar('refetchEvents');
}else{
alert("Error Message");
}
},
error: function(xhr, status, msg) {
alert(msg);
}
});
}
}
});

PHP: Whois via AJAX

I am extremely bad at AJAX (actually, I just started to learn it).
So, I write whois service on PHP and I want to make it to output the result via AJAX-request.
All I have at the moment is:
my PHP code:
$domain = $_POST['domain'];
$whois = new Whois();
header("content-type:application/json");
$res = $whois->getWhois($domain); // Calls the Whois-query function;
echo json_encode($res);
my JS code:
$('#submit').on('click', function() {
e.preventDefault();
var domain = $('#value').val();
});
$.ajax({
url: 'ajax/whois.php',
type: "post",
data: {'domain': domain, 'action': 'whois'},
dataType: "json",
success: function(json) {
$('#whoisResult').html('<h2>Whois Query result for ' + domain + '</h2>');
$('#whoisContent').html(json.html);
},
error: function(xhr, status) {
$('#whoisResult').html('<h2>Sorry, an error occured. Try again later, please!</h2>')
}
});
As HTML I have an input: <input type="text" id="value"> and the submit button.
I searched for the script examples and tried to make something similar, but it does not work at all...
P.S. Guess you won't hit this question a negative rating :)
P.P.S: As requested, this is my response from PHP:
{"domain":"exp.cm","whois":"[Domain]\nDomain: exp.cm\nStatus: active\nChanged: 2014-02-25T12:22:00.957819+02:00\n\n[Holder]\nType: Legal person\nName: Name, Surname\nEmail: email#example.com\nPhone: Phone here\nAddress: Address goes here\nSome other info\n\nUpdated: 2014-03-18T18:12:35.717462+00:00\n"}
In this case you don't need the JSON datatype, just return html.
Additionally, you'll want the ajax request to be inside the click event. In your click event, you also forgot to pass the e parameter.
$domain = $_POST['domain'];
$whois = new Whois();
header("content-type:text/html");
$res = $whois->getWhois($domain); // Calls the Whois-query function;
echo $res;
js:
$('#submit').on('click', function(e) {
e.preventDefault();
var domain = $('#value').val();
$.ajax({
url: 'ajax/whois.php',
type: "post",
data: {'domain': domain, 'action': 'whois'},
//dataType: "json",
success: function(html) {
$('#whoisResult').html('<h2>Whois Query result for ' + domain + '</h2>');
$('#whoisContent').html(html);
},
error: function(xhr, status) {
$('#whoisResult').html('<h2>Sorry, an error occured. Try again later, please!</h2>')
}
});
});

Zend and Jquery (Ajax Post)

I'm using zend framework, i would like to get POST data using Jquery ajax post on a to save without refreshing the page.
//submit.js
$(function() {
$('#buttonSaveDetails').click(function (){
var details = $('textarea#details').val();
var id = $('#task_id').val();
$.ajax({
type: 'POST',
url: 'http://localhost/myproject/public/module/save',
async: false,
data: 'id=' + id + '&details=' + details,
success: function(responseText) {
//alert(responseText)
console.log(responseText);
}
});
});
});
On my controller, I just don't know how to retrieve the POST data from ajax.
public function saveAction()
{
$data = $this->_request->getPost();
echo $id = $data['id'];
echo $details = $data['details'];
//this wont work;
}
Thanks in advance.
Set $.ajax's dataType option to 'json', and modify the success callback to read from the received JSON:
$('#buttonSaveDetails').click(function (){
var details = $('textarea#details').val();
var id = $('#task_id').val();
$.ajax({
type: 'POST',
dataType: 'json',
url: 'http://localhost/myproject/public/module/save',
async: false,
// you can use an object here
data: { id: id, details: details },
success: function(json) {
console.log(json.id + ' ' + json.details);
}
});
// you might need to do this, to prevent anchors from following
// or form controls from submitting
return false;
});
And from your controller, send the data like this:
$data = $this->_request->getPost();
echo Zend_Json::encode(array('id' => $data['id'], 'details' => $data['details']));
As a closing point, make sure that automatic view rendering has been disabled, so the only output going back to the client is the JSON object.
Simplest way for getting this is:
$details=$this->getRequest()->getPost('details');
$id= $this->getRequest()->getPost('id');
Hope this will work for you.

Categories