I have a page called post-blog.php, in here I've set-up a blog entry. I have all this data being saved into one variable. Its displaying this data in an array.
var data = title + content + image + datetime + categories;
How can I send this data to another page called publish.php and redirect the user to that page ?
I've tried to set up a ajax to do this but its not working. Any suggestions ?
$.ajax({
type: 'POST',
cache: false,
url: 'publish.php',
data: data,
success: function( data ) {
alert ( data );
}
});
return false;
});
As per my understanding of the problem, you need to pass the data to a new page and open that page.
If this is your question then this can be done without AJAX, basically AJAX does not even provide solution here. Instead you can just pass all the data to your new page in query format as below -
var page = 'publish.php?title='+title+ '&content='+content+'&image='+image+ '&datetime='+datetime+'&categories='+categories;
Then just change the window location as below
window.location.href = page;
And to get all those variables in your PHP file, do the following in publish.php on top -
if($_GET['title'])
{
$title = $_GET['title'];
}
// similarly get all the data in publish.php file and continue with your page
I am assuming all your variables are strings. If they are not, for example the datetime may be an object, change them into a string first.
Docs say Object must be Key/Value pairs or a string.
Objects work well for this, try something like:
var data = {title: title, content: content, image: image, datetime: datetime, categories: categories};
If your data is coming from a form check out jQuery's serialize.
I've never tried to pass as a string in a POST, but my gut feeling is it would need to be in a format similar to passing the data through the url.
var data = 'title=' + title + '&content=' + content;
Also keep in mind the data in the success function is not the same as what is being passed to the php page. This is what the php page will return. If you're php page returns nothing your alert will be empty. When I'm testing I like to throw something like echo $_POST['title']; in the php file to see something come back.
Here is a similar question that might help too.
Related
I have a script that calls dat from my table and returns it in JSON format. How do I echo out the var nps and data as php variable.
My script:
$.ajax({
type: "POST",
url: "../charts/1-2-4-reports_nps.php?TAG=<?php echo $_SESSION['SectionVar'];?>&From=<?php echo $_SESSION['StartDate'];?>&To=<?php echo $_SESSION['EndDate'];?>",
cache: false,
success: function(data){
var nps = data[0].name;
console.log(nps);
var data = data['data'];
console.log(data);
$("#div1").append($("<div/>", { id: "div2", text: nps }));
}
});
My Json returns:
[{"name":"nps","data":[35]}]
Something like $nps = data['nps'] and echo the result of $nps.
I think initially you were confused about the contexts your code is running in. var nps = data['nps']; is JavaScript. It runs in the browser, and it runs after the page is loaded.
$nps by contrast is a PHP variable, and PHP runs on the server, and it runs before the page is loaded. In fact it is the PHP which creates the HTML, CSS, Script etc which is then downloaded to the browser. After that is downloaded, the JavaScript executes separately.
There is no direct connection between the two languages, other than you can use PHP to generate JavaScript (just like you use it to generate HTML).
Once you understand that, then you realise that to display your nps variable further down the page, you need to use JavaScript to manipulate the web page and insert the data.
The first issue to resolve with that is that the data being returned from the server is coming back as a string that looks like JSON, but not an actual JSON object. You can add
dataType: "json"
to your ajax options, and that tells jQuery to treat the returned data as an object instead of a string.
The next problem is that data is an array, containing a single object, and you were trying to read it like it was just a plain object.
So you get data out of it, and, as you requested, display each value in a new div which gets inserted into an existing div, you can do the following :
function success(data)
{
var nps = data[0].name;
var dt = data[0].data[0];
$("#div1").append($("<div/>", { id: "div2", text: nps }));
$("#div3").append($("<div/>", { id: "div4", text: dt }));
}
You can see a working example (with simulation of the ajax call, but using the correct data structure) here: https://jsfiddle.net/yukot05x/5/
I am trying to find the best method for passing a large array of IDs from one page to the next.
I've built a simple downloadable image site that allows users to select any number of images to download. Right now, when a user selects an image its ID is stored in a JSON string inside a cookie. The problem I've been having is finding the best way to pass the JSON to the review before downloading page.
Currently, I'm sending the JSON as a URL parameter but I'm not sure if this is the smartest solution since the number of IDs in the JSON could reach into the hundreds.
I've looked in PHP sessions but I don't really understand how can I enable the user ability to add/subtract from the variable once the page has been loaded.
$(function(){
$('.download_cart').click(function(){
var urlArray = [];
obj = JSON.parse(getCookie("downloads"));
if(obj != null){
if(obj.items.length !== 0){
$.each( obj.items, function( i, value ) {
urlArray.push(obj.items[i].id);
});
}
}
window.location = cart_url+'?array='+urlArray;
})
});
Try POSTing your data to the new PHP page:
var data = 'urlArray='+urlArray
$.ajax({
type: "POST",
url: 'new_php_page.php',
data: data
});
Now you'll be able to get your variable at $_POST['urlArray'] on your new page.
http://api.jquery.com/jQuery.post/
Consider to pass them in a set of ajax-requests, by 200 (for example, to not overflow input limit) IDs in each request.
Assign urlArray to a hidden field then submit the form, it can parse large no of array to another page
Everything is going well with my ajax code when passing variables, lets say "hello world" but when passing a variable containing such as "hello world http//www.facebook.com" leads to many problems actually.
Actually its the variable "new_textarea" that I am having problem with.
To clarify things out say,
var new_textarea = "hello world"; //successfully saves it to database
but when
var new_textarea = "http://www.facebook.com" // will lead to problems
This is my ajax code:
$.ajax({
url: '/learns/quickpostcomment/'+user_discussion_id+'/'+user_id+'/'+new_textarea+'/'+parent_id,
success: function(data){
}});
And this is my cakephp:
public function quickpostcomment()
{
$post = $this->params['pass'];
$this->ClassroomComment->create();
$this->ClassroomComment->set('classroom_id', $post[0]);
$this->ClassroomComment->set('user_id', $post[1]);
$this->ClassroomComment->set('comment', $post[2]);
$this->ClassroomComment->set('parent_id', $post[3]);
$this->ClassroomComment->save();
die;
}
So far all that I inspected is that whats triggering the problem is the "/" or slashes on the variables when variables contain a url.
Is there any way I can pass a variable to my ajax containing slashes or url?
I need help badly :(
I think you should send a POST request with Ajax instead of a GET. If you build the posted data correctly, you could event get them in your action as you get data from standard Cake forms.
jQuery.ajax({
url : "<?php echo Router::url(array('controller' => 'learns', 'action' => 'quickpostcomment'), true); ?>,
type : "POST",
cache : false,
data : "data[ClassroomComment][user_discussion_id]=" + user_discussion_id + "&data[ClassroomComment][user_id]=" + user_id + "&data[ClassroomComment][new_textarea]=" + new_textarea + "&data[ClassroomComment][parent_id]=" + parent_id,
success : function(data){
}
};
The posted data would then be available in you controller in:
$this->request->data['ClassroomComment']
Try using encodeURIComponent() around your variable new_textarea. See this answer for more information on using encodeURI() and encodeURIComponent.
In your quickpostcomment() action you may need to use the urldecode() function on $post[2]. I can't remember if cake does this automatically for you, but I doubt it does.
I have a jquery/php voting system I'm working on. Once a user clicks a vote button a jquery modal pops open and they must confirm their vote by clicking "Confirm". This will send an ajax request to update the database and what not. After clicking confirm the modal will close. I would like to be able to update the number of votes dynamically on the page. I can easily grab that data from the mySQL table. My question is how does this get sent back for me to then update the html page dynamically?
Currently the page does nothing, so to the user it doesn't look like they've voted. Ideally I'd want to update the total number of votes and also inject an image that shows what they voted for.
function vote(el, id) {
$.ajax({
type: 'POST',
url: '/path/morepath/',
dataType: 'json',
data: {
'action': 'castVote',
'vote': id
},
success: function (data) {}
});
$.modal.close();
}
On the server side, respond to the POST request with a JSON object containing the number of votes and possibly the image path.
Then inside the AJAX callback, data will be that object. Then you can use jQuery to select an element in the DOM and call .text() or .html() on it to update the content.
If you're passing poorly formed data back from PHP, you can make it a bit better by giving it some structure and then making it json for javascript's ease-of-use:
$sqlResult = ...;
$responseArray = array();
$responseArray['result'] = true; //or false if it failed
$responseArray['data'] = $sqlResult;
print json_encode($responseArray);
Before you can really expect the page to respond properly to an ajax response, you must be sure your response data is being parsed correctly.
Inside of your success function, try console.log'ing your response to see what it looks like
console.log(data);
if there is something you can reference in the return data that is reliable, do a check for it:
success: function(data) {
if(data.result == 'true') {
$('someElement.someClass').someFunction();
}
}
You can change the value or html content of the voting number using a few different options such as:
...
success: function(data)
{
var $newTotal = ...//get total from data
$('voteCountContainer').html($newTotal); // or you can also use .val() if it's an input
}
...
Hope that helped,
Dan
Could someone point me in the right direction here?
Basically, I've got this jQuery code snippet:
$('.bggallery_images').click(function () {
var newBG = "url('" + $(this).attr('src');
var fullpath = $(this).attr('src');
var filename = fullpath.replace('img/Bakgrunner/', '');
$('#wrapper').css('background-image', newBG);
// Lagre til SQL
$.ajax({
url: "save_to_db.php",
// The url to your function to handle saving to the db
data: filename,
dataType: 'Text',
type: 'POST',
// Could also use GET if you prefer
success: function (data) {
// Just for testing purposes.
alert('Background changed to: ' + data);
}
});
});
This is being run when I click a certain button. So it's actually within a click handler.
If I understand this correctly, this snippet takes the source if the image I just clicked and strips it so I end up with only the filename. If I do an alert(filename), I get the filename only. So this is working ok.
But then, it does an ajax call to a php file called "save_to_db.php" and sends data: filename. This is correct right? Then, it does a callback which does an alert + data.
Does this seem correct so far?
Cause my php file looks like this:
<?php
require("dbconnect2.php");
$uploadstring = $_POST['filename'];
$sessionid = $_SESSION['id'];
echo ($sessionid);
mysql_query("UPDATE brukere SET brukerBakgrunn = '$uploadstring' WHERE brukerID=" .$_SESSION['id']);
mysql_close();
?>
When I click the image, the jQuery snippet fires and I get the results of this php file as output for the alert box. I think that the variables somehow are empty.
Because notice the echo($sessionid); which is a variable I've created just to test what the session ID is. And it returns nothing. What could be the issue here?
Edit: I just tried to echo out the $uploadstring variable as well and it also returns nothing. It's like the jQuery snippet doesn't even pass the variable on to the php file?
You're trying to send just the filename, but you're retrieving a named form field in your PHP code. So you need to send a named form field:
Change your ajax call like this:
$.ajax({
url: "save_to_db.php",
// The url to your function to handle saving to the db
data: {filename: filename}, // <= Change #1 (give jQuery a simple object)
dataType: 'text', // <= Change #2 ('text', not 'Text')
type: 'POST',
// Could also use GET if you prefer
success: function (data) {
// Just for testing purposes.
alert('Background changed to: ' + data);
}
});
Your PHP script will now receive a POST varible called filename whose value comes from your filename Javascript variable. (You can also use $.post to do this, but it's just a wrapper for ajax anyway...)
Passing a simple object into the ajax call is the easiest way to send fields to the server. jQuery will take the object and create the URL-encoded form data (doing all of the escaping for you) by using the object's keys and field names. So for instance, if you give it this object:
data: {a: 1, b: "testing one two three", c: 3}
...it sends this URL-encoded data:
a=1&b=testing+one+two+three&c=3
(Note how it encodes it for us.) More in the ajax docs (but beware, at present what the docs say about array handling is wrong; see this bug report for details).