Can't send array to php via ajax and back - php

i am trying to get a button on my page which will eventually be a delete button to work. However because it is a <li> element and not your average submit button with a form etc... i have to use ajax to send all the variables to be processed, at the moment i just want them to be in a state where they can be processed, but at the moment my script doesn't seem to return any value like i want it to and output them.
Hopefully from the code below you will see what i mean, all i need it to do at the moment is just select all the values from the checkboxes which are cehcked and send it to the mail_trash.php, and then just send it back and output the array, just so i can see it is selecting the proper values etc... The actual delete php code is already written and working, this is just to check the Ajax.
Here is the javascript and ajax
<script>
$("document").ready(function (){
$("li.trash").click(function(e){
var db = $(':checkbox:checked').map(function(i,n) {
return $(n).val();
}).get(); //get converts it to an array
if(db.length == 0) {
db = "none";
}
$.ajax({
type: "GET",
url: "mail_trash.php",
data: {'db[]':db },
dataType: "json",
statusCode: {
200: function (response) {
$("#mail_header_name").html(response.mess_id);
}
}
});
});
});
</script>
And here is the script for the mail_trash.php
<?php
include 'connect_to_mysql.php';
$mess_id = $_GET["db"];
echo json_encode($mess_id);
?>
And just to check things the button
<li><a class="trash" href=""> </a></li>
Thank you so much for your help, this has been bugging me for the last couple of hours.

It's not li.trash. It's a.trash because trash is a class of the a element. As such the first three lines of the js should be:
<script>
$("document").ready(function (){
$("a.trash").click(function(e){
and then so on with the rest of you code. I haven't checked the rest of your code necessarily, although I am pretty iffy about $(':checkbox:checked') as I don't think that's correct jquery.... To start off, I'd suggest fixing the first selector I mentioned, checking the second with jquery docs and then jshinting/jslinting your code. (Javascript only)

I don't know if its a typo in the question itself or the issue with your script but name of th e parameter while passing is "db" but on the server side you are expecting "mess_id"

Related

How can I use a jQuery var in some php code?

I know there are a few topics on this subject, but after I spent 2 or 3 hours trying to get something good out of them, I just decided to ask this question on a specific point.
So here is my problem : I have got a table and I am using a jQuery function to select a row of this table. Now what i actually want to do is getting the text content of the div contained in the first td of the row.
I already used a getter on it and I am checking the getted value with an alert as you can see in th following code :
$("#myRow").click(function() {
$(".selectedRow").removeClass("selectedRow").addClass("unselected");
$(this).addClass("selectedRow").removeClass("unselected");
var myValue = $(".selectedRow .firstTd div").text();
alert('myValue');
});
So now, what I am trying to do is to send the myValue variable through an ajax request by replacing my alert by this piece of code :
$.ajax({
type: 'get',
url: 'index.php',
data: {"myValue" : myValue},
success: function(rs)
{
alert(myValue);
}
});
Then, back to my php code, I am tring to observe the obtained variable by using an echo, just like this :
<?php echo $_GET['myValue']; ?>
But there is just no way for me to know if my page got it beacause the echo just prints nothing... So i was wondering if someone could do something for me. Thanks.
PS : Oh, by the way ; I don't really know if this can matter, but my page index.php already receives data by a post.
You can't, but read this, php is on the server, while js usually runs on the client, but your ajax trick can work. Just do some processing in the recieving php.
I usually put my ajax recieving end in a different file, and process the rest by the variables posted.
Just try to put the $_GET['myValue']; into an if, or a switch.
Do a var dump of the request var to see if anything is coming through:
<?php
var_dump($_REQUEST);
If not, do a console.log() on 'myValue' to make sure it exists before sending the ajax request - the issue may lie in your js rather than you php.
If you are POSTing data then adjust accordingly - e.g.
$.ajax({
type: 'post',
url: 'index.php',
data: {"myValue" : myValue},
success: function(data)
{
console.log('successfuly posted:');
console.log(data);
}
});
then:
<?php echo $_POST['myValue']; ?>
If you were using GET your data would be in the url, e.g:
index.php?myValue=something
I'm not sure if you are aware of that, but you should wrap you function in document ready statement as below.
Next, call the AJAX request on some action, in this case we can use a click on the row in table.
$(document).ready(function () {
$("#myRow").click(function() {
$(".selectedRow").removeClass("selectedRow").addClass("unselected");
$(this).addClass("selectedRow").removeClass("unselected");
var myValue = $(".selectedRow .firstTd div").text();
alert('myValue');
$.ajax({
type: 'get',
url: 'index.php',
data: {"myValue" : myValue},
success: function(data)
{
console.log('you have posted:' + data.myValue);
}
});
});
});
Okay so it seems that i totally misunderstanded on the way that the $.ajax function works.
I now do use the $.post function (which is actually the same), this way :
$.post('pageElement.php', { myValue : $(".selectedRow .firstTd div").text() },
function(data) { $("#test").html(data); }
);
The url "pageElement.php" refers to a page containing this code :
<div><?php echo $_POST['myValue']; ?></div>
The function called at the end of the process just puts this code into a div of my original page, so i can use it as a php variable now and then send it to another page through a form.

Calling different POST variables using Ajax

I'm still new to jQuery and stuck trying to figure this one out, hope someone can help. I have this jQuery code that needs to pass different values depending on the clicked element. Each element created has a unique number in it's ID (which is needed). If I manually change the jQuery code to a specific ID and call, for example:
http://mysite/examplepost?effect=113
This will work. But I need to have $('#div- ...different numbers here...') to be able to handle multiple elements on the same page. I already have the PHP side producing different values using:
if($_GET['effect'] == $id){
I just need this to work with ajax so that it doesn't reload the page.
Example:
$('#div-113').on('click', function() {
var dataString = 'effect=113';
jQuery.ajax(
{
type:'GET',
url:'?',
data: dataString,
success: function(data){
alert('Works');
}
}
);
});
Any help would be appreciated.
I would give all your divs a common classname (i.e. myClickableDiv) and also a specific data-id.
This way you can target all your divs by that common classname, rather than having to figure it out depending on how the id is formed. The data-id allows you to only provide very specific information to the click handler (like an integer), without having to parse the id.
HTML:
<div class=".myClickableDiv" id="div-XXX" data-id="XXX">My Div</div>
JS:
$('.myClickableDiv').on('click', function() {
var dataString = $(this).attr('data-id');
jQuery.ajax({...});
});

Can a variable go to a hidden PHP page using jQuery?

My PHP page
<ul id="upvote-the-image">
<li>Upvote<img src="image.png" /></li>
</ul>​
is currently successfully sending variable to javascript
$("#upvote").each(function(index) {
var upthis = $(this).attr("rel");
var plusone = upthis;
$.post("upvote.php", {
'plusone': plusone
});
alert(plusone);
});​
(The alert in the code is for testing)
I have multiple images using the rel tag. I would like for each to be able to be upvoted and shown that they are upvoted on the page without loading a new page.
My question, and problem: what is my next step? I would just like to know how to send a value to upvote.php. I know how touse mysql to add an upvote, just not how to send a value to upvote.php, or even if my javascript code opens the page correctly.
thanks
I think you need something like this:
<ul id="upvote-the-image">
<li><span rel="50" id="upvote">Upvote</span><img src="image.png" /></li>
</ul>​
<span id="result"></span>
$("#upvote").click(function(index) {
var upthis = $(this).attr("rel");
var oOptions = {
url: upvote.php, //the receiving data page
data: upthis, //the data to the server
complete: function() { $('#result').text('Thanks!') } //the result on the page
};
$.ajax(oOptions);
}
You dont need an anchor, I changed it for a span, you can test asyc connection using F12 in your browser
Your javascript never opens the php page, it just sends data to it, and receives an http header with a response. Your php script should be watching for $_POST['plusone'] and handle database processing accordingly. Your next step would be to write a callback within your $.post function, which I recommend changing to the full ajax function while learning, as it's easier to understand and see all the pieces of what's happening.
$.ajax({
type: 'POST',
url: "upvote.php",
data: {'plusone': plusone},
success: function(IDofSelectedImg){
//function to increment the rel value in the image that was clicked
$(IDofSelectedImg).attr("rel")= upthis +1;
},
});
You'd need some unique identifier for each img element in order to select it, and send it's id to the php script. add a class instead of id for upvote and make the id a uniquely identifiable number that you could target with jquery when you need to increment the rel value. (From the looks of it, It looks like you're putting the value from the rel attribute into the database in the place of the old value.)
A good programming tip here for JQuery, Don't do:
<a href="javascript:return false;"
Instead do something like:
$(function(){
$('#upvote').on('click', function(event){
event.preventDefault();
$.post('upvote.php', {'plusone': $(this).attr('rel')}, function(data){
alert('done and upvoted');
});
});
});
That is a much better way to handle links on your DOM document.
Here are some Doc pages for you to read about that coding I use:
http://api.jquery.com/on/
http://api.jquery.com/jQuery.post/
Those will explain my code to you.
Hope it helps,

Using ajax for form submission with multiple forms generated by php on page

I have a page with multiple forms that do the same thing, acting as a like button for each post in the page, and right next to it the number of likes inside a div named "likes".$id, so I can identify where to write the likes count after the ajax call. I was trying to use jQuery ajax function, but I couldn't set what div to write the results of the function.
$.ajax({
type:'POST',
url: 'likepost.php',
data:$('#like').serialize(),
success: function(response) {
$('#like').find('#likediv').html(response);
}
});
And how would I access the data on likepost.php? I am terrible with javascript, so I hope someone could help me and explain how the jQuery function really works, because I've been copying and pasting it without really knowing what I was doing.
Would this work?
$(function () {
$("#likebutton").click(function () {
var id = $('input[name=id]'); // this is me trying to get a form value
$.ajax({
type: "POST",
url: "likepost.php",
data: $("#like"+id).serialize(), // the form is called like+id e.g. like12
success: function(data){
$("#likes"+id).html(data); // write results to e.g. <div id='likes12'>
}
});
});
});
I put this in the code but when the button is clicked, the usual post refreshing page is done. Why is that?
Making a mini-form, serializing it, and POSTing it seems like a lot of heavy lifting when all you really want to do is send the ID to the likepost.php script.
Why not just retrieve the ID and post it to the script?
First let's break down your function:Type is the type of the request we're making, you specified POST here. This means in your PHP file you'll access the data we're sending using $_POST. Next up is URL which is just the url of where you're sending the data, your php file in this case.
After that is data, that is the data we're sending to the url (likepost.php). You're serializing whatever has a ID of "like" and sending it to the php file. Finally success is a function to run once the request is successful, we get a response back from the PHP and use it in the function to output the response.
As for the multiple forms I'd recommend doing something like:
http://www.kavoir.com/2009/01/php-checkbox-array-in-form-handling-multiple-checkbox-values-in-an-array.html
Here's documentation on the stuff we talked about, if you're every confused about jquery just break it down and search each part.
http://api.jquery.com/serialize/
http://api.jquery.com/jQuery.ajax/
you can try :
function submitform(id) {
var jqxhr = $.post('./likepost.php',$("#"+id).serialize(), function(data) {
$("#"+id).find('#likediv').html(data);
}, "json")
return false;
}
in form:
<form method="post" id="likeForm" onsubmit="return submitform(this.id);">
<input..... />
<input type="submit" value="Submit" />
</form>
in likepost.php add first line:
if ($_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest") {
header("location: " . $_SERVER['HTTP_REFERER']);
exit();
}
you can see more : http://api.jquery.com/serialize/
working for me.

Ajax Post PHP Div Refreshing

It is me again. I am getting so frustrated with this code it is not even funny. It's not that I am wanting to post it again. It is just that now I understand the where the problem was in the code and wanted to see if you guys can help me figure the last part out.
Basically I am trying to refresh a div without reloading the entire page. It's killing me. Here is some more information on it:
here is my js file first
$(function() {
$(".button").click(function() {
// validate and process form
// first hide any error messages
var email = $("input#email").val();
//var dataString = '&email=' + email; commented out
var dataString = email;
//try insted this //alert (dataString);return false;
$.ajax({ type: "POST", dataType:'HTML',
//or the appropiate type of data you are getting back
url: "http://www.edshaer.com/EdinburgCISD/Gorena/Gorena.php", data: {email:dataString},
//in the php file do $email = $_POST['email'];
//not a good practice but you can try with it and without it
success: function() {
$("#div").fadeOut($("#div").html());
$("#div").fadeIn($("#div").html());
$("#email").val('');
// Change the content of the message element
// Fade the element back in
} });
//ajax ends
return false; });
//click ends
});//document ready ends
Now the problem that I am running into with this code is on the Ajax part. After placing the alert(), I have relized that if I use the function() like this:
success: function(data)
Then the alert came out blank. The reason behind it is that my URL is going to my php file, but my div that I am trying to refresh is on my html file. Meaning if I do this:
success: function(data) {
$("#div").html(data)}
I am sending blank data because it's trying to get the div from my php file instead of my html file.
Now if I do this:
$("#div").html()
Then that gives me the div that is in my html file.
By knowing what is going on now, Can you guys please help me???
My dear you should generate some sort of html in your php file that you want to generate in your div. Then you will see that you are having some content in data in the success function. This is an easy approach.
But there is also some other approach that is more efficient but it needs some sort of search. This is the implementation of Client Side Scripting. You can do this with the help of a jquery plugin jquote2. I hope it will work for you.
You're using
$("#div").fadeOut($("#div").html());
$("#div").fadeIn($("#div").html());
Both are wrong, jQuery .fadeIn() and .fadeOut() arguments are either [duration,] [callback] or [duration,] [easing,] [callback]. None take HTML as input.
Try changing
$("#div").fadeOut($("#div").html());
to
$("#div").fadeOut();
and moving it outside the $.ajax call to hide the previously showed (if any) results before the post and also change
$("#div").fadeIn($("#div").html());
to
$("#div").html(result).fadeIn();
Also change
success: function()
to
success: function(result)
Hope it helps.
This might be a problem relating to the response from the php script. Jquery doesn't always correctly render the Ajax response as html.
Setting dataType: html in the $.ajax({ ... }) call can help. Also setting header("Content-Type: text/html"); at the top of your php ajax script.

Categories