cannot access request array after ajax forwarding - javascript

So i'm currently working on a website that loads a container once a button is clicked and the content is loaded via an AJAX function. The problem is at the PHP side, I cannot access the variable i pass through the AJAX function through my REQUEST array. I'm not sure if it is a problem with BIG TREE CMS I'm using.But i really would appreciate some help.
This is the button i use to call the function:
<div class="button-holder">
<button class="project-btn" data-id='<?=$id?>' onclick="getProject(<?=$id?>)">
<h3 class="btn-text">View Project</h3>
<h3 class="hide-reveal">→</h3>
<h3 class="button-pike"></h3>
</button>
So this is my ajax function:
function getProject(id)
{
var ajaxUrl='ajax/singleProject?id=' + id;
$.ajax(ajaxUrl, {
async: true, complete: getProjectComplete
});
}
function getProjectComplete(xhr, status) {
if (status == false)
{
return;
}
var obj = $.parseJSON(xhr.responseText);
$('.pro-heading').html(obj.company);
$('.pro-subtext').html(obj.project_heading + '(' + obj.start_date + ')');
$('.pro-image').attr('src', obj.project_image);
$('.pro-brief').html(obj.project_brief);
$('.pro-details').html(obj.project_details);
}
and this is my PHP function:
<?php
if (isset($_REQUEST['id']))
$id = $_REQUEST['id'];
$obj = new Projects();
$single = $obj->get($id);
echo json_encode($single);
?>

Related

Do a javascript redirect after an ajax call

I'm trying to use ajax to parse data to be processed on a php page and have php echo a javascript redirect to another page but it is not working. I have read that js does not work after running an ajax call so I will like to know if there s a way around it. This is my code:
html
<form>
<div class="depart_time bottom_white w-40 ml-auto">
<p>Time</p>
<input type="time" name = "return_time" id = "rt">
</div>
<div class = "search_button r_search">
<button id = "r_search" onclick = "return false" onmousedown = "rent()">SEARCH</button>
</div>
</form>
ajax call is a normal xhttp request that gets sent to php for processing after which a redirection should occur:
if(isset($_POST['return_time'])){
echo '<script type="text/javascript">window.location.href="link.html"</script>';
}
Please an help is appreciated. I'm new to using ajax.
EDIT
the ajax code:
gid("r_search").addEventListener("mousedown", rent);
function rent(){
rt = gid('rt').value;
r_search = gid('r_search').value;
form_array = '&rt=' + rt +
'&r_search=' + r_search;
send_data = form_array;
ajax_data('app/rent.php', 'error', send_data);
//gid('error').innerHTML = send_data;
}
function ajax_data(php_file, getId, send_data){
gid(getId).innerHTML = "loading";
var xhttpReq = new XMLHttpRequest();
xhttpReq.open("POST", php_file, true);
xhttpReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttpReq.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
gid(getId).innerHTML = xhttpReq.responseText;
}
};
xhttpReq.send(send_data);
}
please note that 'gid' is for getelementbyid
You have to make bit alteration to your way of redirection.
First you need to make changes in your PHP response
if(isset($_POST['return_time'])){
...
// If you get your process success return 1
if(success) {
echo 1; die();
} else {
// else set some flag that you could get on your AJAX response
echo 0; die();
}
}
Now, get this flag on your AJAX and make changes to your below functions:
function ajax_data(php_file, getId, send_data){
gid(getId).innerHTML = "loading";
var xhttpReq = new XMLHttpRequest();
xhttpReq.open("POST", php_file, true);
xhttpReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttpReq.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if( xhttpReq.responseText == 1 ) window.location.href="URL where you wish to redirect page";
}
};
xhttpReq.send(send_data);
}
I've written this answer for others who come here for help.

cant post value using ajax in zend framework 2

I'm using ajax to post a value as given below,
but data I post wont reach the controllers ajaxAaction
view script (which is a tpl file)
<input type="text" id='taska'>
<button id='submitTo'>button</button>
script
$(document).ready(
function(){
//controller via ajax
$("#submitTo").click(function() {
var message = $('#taska').val();
if (message != '') {
//run ajax
//alert ('not empty');
$.post('index/ajax',
{'message' : message},
//callback function
function (respond) {
//put respond in class show-msg
$(".show-msg").html(respond);
}
);
}
});
and the action
public function ajaxAction() {
//get post request (standart approach)
$request = $this->getRequest()->getPost();
//referring to the index
//gets value from ajax request
$message = $request['message'];
// makes disable renderer
$this->_helper->viewRenderer->setNoRender();
//makes disable layout
$this->_helper->getHelper('layout')->disableLayout();
//return callback message to the function javascript
echo $message;
}
} );
$.post('index/ajax', is the part where I think the error is.
Am I defining the controller and action in the wrong way?
I've been stuck here for a while.
please help
try it with $this->basePath() in <?php echo $this->basePath();?>index/ajax
Solved it by prefixing the rootPath as below
if (message != '') {
//run ajax rootPath
{/literal} $.post("{eval var=$rootPath}/index/ajax", {literal}
{'message' : message},
//callback function
function (respond) {

Combination JQuery and PHP

I'm making a project with the slides of text.
I have in the page a main div that contain the text of each slide.
I saved the content in a database.
I want do this operation:
When I click the arrow for view the next slide, PHP catch from database the content and save it in a variable.
Then with JQuery, I replace the maindiv's content with variable.
It is possible? If not, How can I do it?
Use a ajax request to simulate a post request, and parse the information with php. You will end up with someting like this:
<?php
if( isset( $_POST["slide"] ) {
// Database stuff
// Echo back
echo "Information that you need to get in jQuery";
}
?>
<script>
$("button.next_slide").click(function(){
var ajax;
if (window.XMLHttpRequest) {
ajax = new XMLHttpRequest();
} else {
ajax = new ActiveXObject("Microsoft.XMLHTTP");
}
ajax.onreadystatechange = function() {
if (ajax.readyState==4 && ajax.status==200) {
document.getElementById("some_element").innerHTML = ajax.responseText;
}
}
ajax.open("POST","this_page.php?slide=1&foo=bar&bar=foo",true);
ajax.send();
});
</script>
<button class="next_slide">Next slide</button>
<div id="some_element"></div>
Note: This could be done without jQuery, or with jQuery's $.ajax method. Read more here: http://api.jquery.com/jquery.ajax/
In my understanding, you want to load some data when user click on a particular button and then load it into a div we can achieve it via jQuery ajax and PHP.
HTML
<div class="main_div">
<ul id="list"><!-- Our content will load here --></ul>
Next
</div>
jQuery
jQuery(document).ready(function($){
$('.call_ajax').on('click', function(e){
e.preventDefault();
$.post('ajax.php', { get_slide: true }, function(response){
// We are telling jQuery to parse response as json because in ajax.php we have used json_encode function.
var data = jQuery.parseJSON(response);
$("#list").append('<li>' + data['slide'] + '</li>');
});
})
})
PHP ajax.php
if(isset($_POST['get_slide'])){
//Get slide from db and output it as json, but currently for example purpose we assume that we have a array.
$data['slide'] = 'Your slide text';
echo json_encode($data); die(); // We have used die because we don't won't our script to run any more.
}
I've not tested it, but it will work.

How to make sure that I can scroll up in AJAX chat

I am building a vanilla JS, AJAX chat (so no jQuery or other toolkits). The messages are loaded via AJAX and put in a div that uses overflow-y: scroll; so you can scroll through all the messages.
Because the latest messages appear at the bottom I have a scrollDown() function that scrolls to the end of the div:
function scrollDown()
{
var objDiv = document.getElementById("chatbox");
}
The problem is that I can't scroll up. If I do that I will get to the bottom again. This is because on every ajax call I scroll down. But how can I make sure that if an user is scrolled up in the div (so he/she is reading past messages) that it doesnt scroll down when AJAX gets updated.
I already tried some things with div.scrollHeight, div.scrollTop but unfortunately it didn't work. I also did a lot of Google searches but no luck either and most them were jQuery though. Here is my code;
<script type="text/javascript">
getBerichten();
function getHTTPObject(){
if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
else if (window.XMLHttpRequest) return new XMLHttpRequest();
else {
alert("Your browser does not support AJAX.");
return null;
}
}
function doWork(id, user_id) {
nieuwbericht = getHTTPObject();
if (nieuwbericht != null) {
if( document.getElementById('bericht').value != "")
{
nieuwbericht.open("GET", "ajaxberichten.php?id=" + id + "&user_id=" + user_id + "&bericht="
+ document.getElementById('bericht').value, true);
nieuwbericht.send(null);
document.getElementById("bericht").value = "";
}
}
}
function setOutput()
{
if(httpObject.readyState == 4){
document.getElementById('berichten').innerHTML = httpObject.responseText;
bericht = document.getElementById('chatbox');
scrollDown();
setInterval(getBerichten(),1000);
}
}
function getBerichten()
{
httpObject = getHTTPObject();
if (httpObject != null)
{
httpObject.open("GET", "ajaxgetberichten.php?id=<?php echo $_GET['id'] ?>", true);
httpObject.send(null);
httpObject.onreadystatechange = setOutput;
}
}
function scrollDown()
{
var objDiv = document.getElementById("chatbox");
objDiv.scrollTop = objDiv.scrollHeight;
}
</script>
<div class="postbox">
<div class="post">
<div class="chatbox" id="chatbox">
<div id="berichten"></div>
</div>
<form method="post" action="">
<textarea name="bericht" id="bericht"rows="20" cols="85"> </textarea>
<input name="verstuur" type="button" onclick="doWork(<?php echo $_GET["id"] ?>, <?php echo $user_id ?>);" value="Verstuur"/>
</form>
</div>
</div>
Could somebody please tell me how to fix this without a JS toolkit like jQuery?
Thanks

Ajax not working with javascript. What am I supposed to do?

This is my code where I call the Request for Ajax, than a simple input button which on onClick event send some data to a function called setValue();
This is the code (JS):
//request for ajax XML
<script type='text/javascript'>
function callAjax(){
var XMLObj = false;
if(window.XMLHttpRequest)
XMLObj = new XMLHttpRequest();
else if(window.ActiveXObject)
XMLObj = new ActiveXObject('Microsoft.XMLHTTP');
if(!XMLObj)
return false;
return XMLObj;
}
//var for ajaxobject handle;
var objAjax = callAjax();
function setValue(value, id, num, item){
if(objAjax){
if(objAjax.readyState == 4 || objAjax.readyState == 0){
objAjax.open('POST', 'addview.php', true);
objAjax.send('value=' + val + '&id='+id+'&num='+num+'&item='+item);
}
}
}
//input for sending value to function setValue();
<input type='button' onClick='setValue(1, 2, 3, 4)' />
//and this is where I handle the sent data via php
<?php
if(!$_POST['value'] || !$_POST['id'] || !$_POST['num'] || !$_POST['item'])
exit();
include('config.php');
$value = mysql_real_escape_string($_POST['value']);
$id = mysql_real_escape_string($_POST['id']);
$num = mysql_real_escape_string($_POST['num']);
$item = mysql_real_escape_string($_POST['item']);
mysql_query("UPDATE `window` SET window_val = window_val + ".$value." WHERE window_id = '".$id."' AND window_num = '".$num."' AND window_item = '".$item."' ") or die(mysql_error() );
mysql_close($con);
?>
The php script is working, I tried it with sending data manually ($_GET['']) and it's working. Also I checked the URL with alert('value='+value+'&id='+id...) and all variables are Ok, but the database won't be queried.
If you see, I don't add any function for response, reply from the server. I just only want to send those data and query the data base.
Thank you !
You may be missing
objAjax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
Consider improving your function names: callAjax doesn't call Ajax, it returns a reference to the XHR object. Call it getXhr or something more like what it's actually doing.
If you're ok with jQuery, just call
function setValue(value, id, num, item){
$.post('addview.php', 'value=' + val + '&id='+id+'&num='+num+'&item='+item);
// or the cleaner version
$.post('addview.php', {value: val, id: id, num: num, item:item});
}

Categories