Calling different POST variables using Ajax - php

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({...});
});

Related

refresh page content not using .load in ajax

I am using .load to update my list, but this is not right approach as it get nested each time. what would be the alternate. I am new to Ajax.
$(document).on('click','#npDelete',function(){
var dataId = $(this).data("id");
alert(dataId);
$.ajax({
type:'get',
url:"{!! URL::to('deleteproject') !!}",
data:{'id':dataId
,},
success:function(data){
console.log('success');
console.log(data);
console.log(data.length);
$("#projects1").load("projects");
},
error:function(){
},
});
});
Projects is the page which contains the list of projects from database. So each time I delete a project the list is updated, its working fine but each time the ajax request is called plus one(+1) time
The quick and dirty solution would be to:
Import only the #projects1 element instead of the whole document
Replace the contents of the existing document's #projects1 element's parent element (so that the #projects1 element itself is replaced)
Such:
$("#projects1").parent().load("projects #projects1");
… but a nicer solution would be to have {!! URL::to('deleteproject') !!} return JSON that gave a true or false response and then delete the element that was actually clicked:
Add var $clicked_element = $(this); above var dataId = $(this).data("id"); and the you can $clicked_element.remove() when the request is successful. (Or possibly something like $clicked_element.parents("tr").remove() … but I'm having to speculate as to what your HTML looks like).
NB: Your HTML implies that you have multiple elements with the id #npDelete. This is invalid HTML. Don't do that. Use a class to identify a group of related elements. Use an id only to identify a unique element.
do
$("#projects1").html("projects");
and i suggest you use
$(document).ready(function(){});
or
$("#target").on('click',function(){});
at the beginning of your code instead of using $(document).on('click',function(){});

How do I post to a new php page with jquery

I am trying to post the element information that jQuery pulls, when a user clicks on table cell, to a new page that will use that information (an id in this case) in a sql query. i.e., the user clicks a cell and the job he/she clicks has an id of 25, that is to be passed to my php page that queries the database for the job with that id and then populates the page with said information. The user can then alter the information from the query and submit it to update the database table. I have the id from the click function and a success alert tells me that the info was posted. The problem is that when the page is opened it states that the posted name index is undefined.
Here is my script to get the information:
<script>
$(document).ready(function()
{
$("table.jobs tbody td#job").click(function()
{
var $this = $(this);
var col = $this.text();
var LeftCellText = $this.prev().text();
if (col == '')
alert("Please pick another column");
else
$.ajax(
{
type:"POST",
url:"../php/jobUpdate.php",
data:"name=" + LeftCellText,
success: function()
{
window.location = "../php/jobUpdate.php";
}
});
});
});
</script>
and here is the simple php page it is sending to:
$name = $_POST['name'];
echo $name;
I am new to jQuery, and I cannot figure out why this is not working?
When you use ajax, the second page ../php/jobUpdate.php processes the data sent by the first page, and returns a value (or even a huge string of html, if you want).
The first page receives the new data in the ajax routine's success function and can then update the current page. The updating part happens in the success: function, so you're on the right track.
But in your success function, you are redirecting the user to the 2nd page -- after already being there and processing the data. Redirecting them is probably not what you want to do.
Try replacing this:
success: function()
{
window.location = "../php/jobUpdate.php";
}
with this:
success: function(data)
{
alert(data);
}
If you want to see how to update the first page with the data received via ajax, try adding an empty DIV to your html, like this:
<div id="somestuff"></div>
Then, in the success: function of the ajax routine, do this:
$('#somestuff').html(data);
(Note that the term "data" can be any name at all, it only needs to match the name used in the function param. For example:
success: function(whatzup) {
alert(whatzup);
}
From your comment to my previous post, it seems that you don't need ajax at all. You just need a form in your HTML:
<form id="MyForm" action="../php/jobUpdate.php" method="POST">
<input type="hidden" id="jobID" name="yourJobID">
</form>
Note that forms are invisible until you put something visible inside them.
You can have select controls (dropdowns) in there, or all form elements can be invisible by using hidden input fields (like the HTML just above), which you can populate using jQuery. Code to do that would look something like this:
<script>
$(document).ready(function() {
$("table.jobs tbody td#job").click(function() {
var $this = $(this);
var col = $this.text();
var LeftCellText = $this.prev().text();
//Set value of hidden field in form. This is how
//data will be passed to jobUpdate.php, via its `name` param
$('#jobID').val(LeftCellText);
if (col == '')
alert("Please pick another column");
else
$('#myForm').submit();
});
});
</script>
If you add more values to your form to send over to jobUpdate.php, just ensure that each element has a name, such as <input type="text" name="selectedJobType"> (this element, type="text", would be visible on screen).
In the jobUpdate.php file, you would get these values thus:
$SJT = $_POST['selectedJobType'];
$id = $_POST["yourJobID"];
//Use these vars in MySQL search, then display some HTML based on results
Note that the key referenced in the $_POST[] array (selectedJobType / yourJobID) is always identical to the name specified in the HTML tag. These names are case sensitive (and spelling counts, too).
Hope this isn't TMI, just wish to cover all the bases.
On your success function causing the window to reload will delete any of the variables passed in via .ajax.
What you can try is returning the data and use it in the existing page.
success: function(msg) {
$('#someDiv').append(msg);
}
The reason the index is not defined is because you are using a string in the data-argument, however, that is actually an array-like object. :)
data: { name: col }
that should be the line you need to change. Otherwise I have not seen any problems. Also if I can give you a little idea, I wouldn't use POST actually. In fact, I'd use GET. I can not confirm if that is saver or not, but using $_SERVER["HTTP_REFFERER"] you can check from where that request is coming to determine if you want to let it pass or not.
The way I would suggest is, that you sent the ID in a GET-request and have the PHP code return the data using json_decode(). Now in jQuery, you can use $.getJSON(url, function(data){}) - which is, for one, shorter and a bit faster.
Since you probably will crop the URL yourself here, make sure that you use a function like intVal() in JS to make sure you are sending an intenger instead of a malicious string :)

Can't send array to php via ajax and back

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"

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,

how to refresh the data being loaded on the form after showing it off?

I have a a div, wherein, it displays the data, and beside it, is an edit button..if one clicks the edit button, it hides the div and shows a different div with input forms which allows the user to update the data..the problem now is, when the user submits the form, my script updates the data and hides this input forms and shows again the former div of data display, the data shown is not updated....my question now is,, how to show the updated data after the script show() it again ?
here's my jquery ajax code
$(function(){
$('#profileinfoedit').click(function(){
$('#profileinfomain').hide();
$('#profileinfoajax').show();
$('form#pdetails').submit(function(){
var cvid = $('#cvid').val();
var resumetitle = $('#resumetitle').val();
var name = $('#name').val();
var dob = $('#dob').val();
var gender = $('input[name=gender]:checked').val();
$.ajax({
type: "POST",
url: 'classes/ajax.personalupdate.php',
data: $("form#pdetails").serialize(),
success: function(data){
alert(data);
$('#profileinfoajax').hide();
$('#profileinfomain').show();
}
});
return false;
});
});
});
$('#datepicker').datepicker();
So location.reload is just refreshing the page, which as you have discovered is a quick and dirty fix.
If you want to do it without a page refresh, you would have to regenerate the html for just the 'profileinfomain' element from data received back from ajax.personalupdate.php. I would assume you would only want to do this on "success".
One approach would be to have the success data contain the html needed to regenerate the 'profileinfomain' element html. So perhaps have php return back data.profileinfomain_html, and then:
$('#profileinfomain').html(data.profileinfomain_html);
which will replace the inner content of the profileinfomain element.
If you are working in a framework of some sort, have the profileinfomain inner html content be a partial template included in so you only have to maintain its html in one place.
was able to sort it out via
$('#profileinfomain').show('normal',function(){
location.reload();
});
but, isn't there any better way to do this?

Categories