Yii ajax call and session handling - php

I stucked in Yii, with an Ajax call "bug". The problem is, that i have to search by checkboxes, wich are stored in SESSION after hitting the search button.
After this, the keywords inserts into SESSION, and i want to print them in a tag-cloud. (with a cross in the corner -> delete this tag).
The removal of these tags is handled by an ajax call:
$(".tags a").click(function(e) {
e.preventDefault();
var class1 = $(this).attr("class");
var id = $(this).attr("id");
$("#checkbox__"+id).removeAttr("checked");
jQuery.ajax({
url: "recipe/removeFromSession",
type: "POST",
data: "id=" + class1+"&rcp="+id,
dataType: "json",
"success": function(data){
location.reload();
},
"error": function(xhr, status, error) {
var err = xhr.responseText;
alert(xhr.status);
},
"cache" : false,
});
});
It calls the removeFromSession action:
public function actionRemoveFromSession() {
$remove = intval($_POST['id']);
unset($_SESSION['searchItems']['category'][$remove]);
unset($_SESSION['recipeSearch']['category'][$_POST['rcp']]);
echo json_encode($_SESSION);
}
The problem is that it doesn't unsets the value. It's still in the session. Any idea? (sorry for grammar mistakes)
Thanks

You can try this:
Set your session:
Yii::app()->session['searchItems']['category'][$keyword] = "Any string";
To unset session:
unset(Yii::app()->session['searchItems']['category'][$remove]);

Related

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

jQuery ajax request awkward issue

So I have this ajax request. When the user clicks an edit link, I fetch the ID of the entry and refresh the page with the data of that entry loaded into a form.
Here's my problem: This only works with the alert showing before the ajax call. When I leave out the alert, I get an ajax error (though the id is being posted) and the PHP page just reloads. Moreover, it only works when I put the newDoc stuff as a success callback. The exact same lines as a complete callback and the page reloads. Moreover, this occurs in Firefox only.
jQuery('a.edit').on('mousedown', function (e) {
e.preventDefault();
var id = jQuery(this).attr('data-title');
alert('test');
jQuery.ajax({
url: document.location,
data: {
id: id
},
success: function (data) {
var newDoc = document.open("text/html", "replace");
newDoc.write(data);
newDoc.close();
},
error: function () {
alert('error');
}
});
});
What can I do?
EDIT: This must be a timing issue. I just noticed that when I click and hold the edit link for a second or so, everything works fine. When I do a short click, it doesn't. So I tried wrapping the ajax in setTimeout(), but that didn't help. Any other ideas?
Try to use location.href in place of document.location,
jQuery.ajax({
url: location.href,
data: {
id: id
},
success: function (data) {
var newDoc = document.open("text/html", "replace");
newDoc.write(data);
newDoc.close();
},
error: function () {
alert('error');
}
});
location is a structured object, with properties corresponding to the parts of the URL. location.href is the whole URL in a single string.
Got it!
The problem is the way Firefox handles the mousedown event. It seems to abort the ajax call as soon as you relase the mouse button. I changed the event to click and everything is fine now.
jQuery('a.edit').on('click', function () {
var id = jQuery(this).attr('data-title');
jQuery.ajax({
url: document.location,
data: {
id: id
},
success: function (data) {
var newDoc = document.open("text/html", "replace");
newDoc.write(data);
newDoc.close();
}
});
});

Why won't my .ajax request work?

The code I want to work:
$.ajax({
type: "POST",
url: "_Source/ajap/ajap.nlSrch.php",
data: { sndJson : jsonData },
dataType: "json",
processData: false,
success: function(html) {
$("#srchFrm").append(html);}
});
The code that works:
$.ajax({
type: "POST",
url: "_Source/ajap/ajap.nlSrch.php",
data: { sndJson : jsonData },
success: function(html) {
$("#srchFrm").append(html);}
});
Unfortunately when I send the first one my post data looks like this "Array ()" and when I use the later I get this "Array ( [sndJson] => [\"8\",\"3\",\"6\",\"7\"] )".
I know that there has to be a simple explanation but I haven't been able to figure it out.
Help please!
Try sending your data in a query string...
$.ajax({
type:"POST",
url:"_Source/ajap/ajap.nlSrch.php?json="+jsonData,
dataType:"json",
success: function(data) {
$("#srchFrm").append(data);}
error: function(xhr, ajaxOptions, thrownError)
{alert("Error!");}
});
You can use shorthand $.post instead of using low level ajax class --- because you don't need to advanced handling. So, this one will be great enough.
$(document.ready(function(){
$("#submit_button").click(function(){
$.post('php_script.php', {
// here's what you want to send
// important -- double quotes, 'cause It's evals as valid JSON
"var1" : "val1"
"var2" : "val2"
}, function (respond){
try {
var respond = JSON.parse(respond);
} catch(e){
//error - respond wasn't JSON
}
});
});
});
PHP code:
<?php
/**
* Here you can handle variable or array you got from JavaScript
* and send back if need.
*/
print_r($_POST); // var1 = val1, var2 = val2
?>
Back to your question,
Why my .ajax request doesn't work?
This is because JavaScript throws fatal error and stops further code execution.
You can catch and determine the error occasion, simply by adding
try {} catch(){} block to the statement you think may occur any error
When you specify dataType: json, jQuery will automatically evaluate the response and return a Javascript object, in this case an array. You're taking the result and adding it as html to #srchForm, so it does not make sense to convert it to a javascript object. Use dataType: html, or none at all.
http://api.jquery.com/jQuery.ajax/
The following examples above are not reusable. I am a huge fan of reuseable code. here is my solution.
Software design 101:
DRY Don't repeat your self. You should wrap your code into an object. This way you can call it from anywhere.
var Request = {
version: 1.0, //not needed but i like versioning things
xproxy: function(type, url, data, callback, timeout, headers, contentType)
{
if (!timeout || timeout <= 0) { timeout = 15000; }
$.ajax(
{
url: url,
type: type,
data: data,
timeout: timeout,
contentType: contentType,
success:function(data)
{
if (callback != undefined) { callback(data); }
},
error:function(data)
{
if (callback != undefined) { callback(data); }
},
beforeSend: function(xhr)
{
//headers is a list with two items
if(headers)
{
xhr.setRequestHeader('secret-key', headers[0]);
xhr.setRequestHeader('api-key', headers[1]);
}
}
});
}
};
Usage:
<script type="text/javascript">
var contentType = "applicaiton/json";
var url = "http://api.lastfm.com/get/data/";
var timeout = 1000*5; //five seconds
var requestType = "POST"; //GET, POST, DELETE, PUT
var header = [];
header.push("unique-guid");
header.push("23903820983");
var data = "{\"username\":\"james\"}"; //you should really deserialize this w/ a function
function callback(data)
{
//do logic here
}
Request.xproxy(requestType, url, data, callback, timeout, header, contentType);
</script>

Ajax call will not work

I have this method that I want to run a php file using ajax and then reload the page.
function winA()
{
var x = "<?php echo $id;?>"
$.ajax({ url: 'w.php5' ,
data: { id: x },
success: function(data) {
window.location.reload()
}
});
}
This is what I have and I've looked it over endless times for flaws, made sure the php variable is reading properly and made sure the function is truly being called. The php file works properly when called w.php5?id=1
Why won't this ajax call work?
Thanks in advance for the help, Aaron.
function winA()
{
var x = "<?php echo $id;?>"
$.ajax({ url: 'w.php5' ,
data: { id: x },
success: function(data) {
window.location.reload()
}
error:function (xhr, ajaxOptions, thrownError)
{
alert(xhr.status);
alert(thrownError);
}
});
}
This way it will show alert in case of ajax error
Also, if in chrome, press the combination Ctrl+Shift+I for developer tools and check network tab to see if w.php5 is called, and what is the response. Dont know tools for other browser but there should be something like that
There are 2 alternatives.
If you want to post some other data, use this
.ajax({
type: 'POST',
url:'w.php5',
data: {id: '<?php echo $id; ?>'},
success: function(resp){
console.log(resp);
},
dataType:'json'
});
If you go this way, your ID is going to be stored in $_POST array => *$_POST['id']*
If you want to just get some data by ID you post, use this
.ajax({
type: 'GET',
url:'w.php5?id=<?php echo $id; ?>',
success: function(resp){
console.log(resp);
},
dataType:'json'
});
If you go this way, your ID is going to be stored in $_GET array => *$_GET['id']*
You're missing a semicolon here:
var x = "<?php echo $id;?>"
Should be:
var x = "<?php echo $id;?>";
//set the method
POST or GET
type:'GET'; or type:"POST"
That url is probably missing a leading forward-slash, assuming you are trying to access a url like www.myurl.com/w.php?id=5
Try
url: '/w.php?id=5',
If that doesn't work, you need to inspect the request using a developing tool within Chrome or Firefox.
You can also var_dump the $_GET or $_POST in w.php, as the response will expose the output.

Execute php script with JS [duplicate]

Is it possibe to simply load a php script with a url with js?
$(function() {
$('form').submit(function(e) {
e.preventDefault();
var title = $('#title:input').val();
var urlsStr = $("#links").val();
var urls = urlsStr.match(/\bhttps?:\/\/[^\s]+/gi);
var formData = {
"title": title,
"urls": urls
}
var jsonForm = JSON.stringify(formData);
$.ajax({
type: 'GET',
cache: false,
data: { jsonForm : jsonForm },
url: 'publishlinks/publish'
})
//load php script
});
});
Edit:
function index() {
$this->load->model('NewsFeed_model');
$data['queryMovies'] = $this->NewsFeed_model->getPublications();
$this->load->view('news_feed_view', $data);
}
simple
jQuery and:
<script>
$.get('myPHP.php', function(data) {});
</script>
Later edit:
for form use serialize:
<script>
$.post("myPHP.php", $("#myFormID").serialize());
</script>
like this ?
$.get('myPHP.php', function(data) {
$('.result').html(data);
alert('Load was performed.');
});
There are various ways to execute a server side page using jQuery. Every method has its own configuration and at the minimum you have to specify the url which you want to request.
$.ajax
$.ajax({
type: "Get",//Since you just have to request the page
url:"test.php",
data: {},//In case you want to provide the data along with the request
success: function(data){},//If you want to do something after the request is successfull
failure: function(){}, //If you want to do something if the request fails
});
$.get
$.get("test.php");//Simplest one if you just dont care whether the call went through or not
$.post
var data = {};
$.post("test.php", data, function(data){});
You can get the form data as a json object as below
var data = $("formSelector").searialize();//This you can pass along with your request

Categories