EDIT:
I will try to explain what I want to do a bit better. I am displaying a table with all the fields retrieved from a database using an ajax call to a php file (eg. other.php) in my main.php. What I am trying to figure out is once the table is displayed to screen and the call is in the other.php file, can I implement an update query within other.php to update a field in the database with a user input? Does that make sense?
Thanks.
Yes, it's possible. Assuming that you have a form that the user fills before clicking in the menu, you can add this values in your ajax call.
For example, assuming that you have a search button
<input type='text' name='search' id='search' />
You can pass this to your php with get or post (type of request)
$.ajax({
url: "somefile.php",
type: "POST",
data: "search=" + $('#search').val(),
success: function(data){
//do something...
}
});
And in your somefile.php you can access the value with $_POST['search'] or $_GET['search'] (depending of the type of the request).
I think with this you can adapt to your reality. More samples you can get in the JQuery docs.
Related
I am fairly new to posting on StackOverflow so I hope that my post follows the correct criteria, if it doesn't I apologise. I shall try to keep my question and explanation of my issue as short as possible.
I am trying to create a input field which allows the user to update their About section on their profile for other users to be able to see. I have looked at similar posts but none of them really had solutions that matched my problem from what I could find.
I am using a form with a POST method which has a hidden field that includes the value of the userId and stores the string from the input field. I am using an Onclick function associated to the button with the id = "post" which calls an Ajax request which stores the value of the input into a variable known as var text which I want then to be stored into a database with the userId and the comment. However, the console returned "an empty string" (image linked at the very bottom). I am not to sure how to figure it out since I am still very new to using Ajax, and I'm trying to learn as much as I can.
myAccount.php
<h2>About</h2>
<form method='POST' id="postForm">
<input type='hidden' name='posterId' value="<?php echo $user['userId']?>">
<input name="post" id='post' value="">
<br/>
<br/>
<button type="button" onclick='setComment()' name='submit'>Post it</button>
</form>
main.js
function setComment() {
var text = $("#post").val();
$.ajax({
type: 'POST',
url: 'setAbout.php',
data: {'text': text},
success: function(data) {
console.log(data);
}
});
}
Return "an empty string"
Note: If you post a solution please include an explanation as to why you took that particular approach since I am here to learn. Thank you!
<input type='hidden' name='posterId' value="<?php echo $user['userId']?>" id = 'posterId'>
function setComment() {
var text = $("#post").val();
var posterId=$('#posterId').val();
$.ajax({
type: 'POST',
url: 'setAbout.php',
data: {'text': text, 'posterId':posterId},
success: function(data){
console.log(data);
}
});
}
you are checking for the variable posterId in your PHP script, which you have not set while doing the ajax call.
and in the script you are just running the prepared query, you are not returning anything as response to your request. So even if the request succeeds, you will not get anything in the response to print in your console
You, post with AJAX: {text} variable but in PHP code, you want to get {posterId} variable. Why? Change your variable name and sure in JS and PHP code the same name variable. And in AJAX request, PHP cannot return nothing. So in PHP code, you should use 'echo' for returning.
I would like to submit some data. Weather this be using a form, or onClick execute some AJAX, I'm not sure.
For example, I have this input
<input id='inpamount' type="text" name="amount" value="2.00" onkeyup="pad();validatemin();product()">
Now say if I wanted to send this data to a PHP file, using post ( i could just add a form). But then, without reloading the page (I can do this), how could I fetch a response (using AJAX).
Essentially I would like a user to be able to press a button, then to submit the inputs to a php file, and then get the output and assign it to a variable (I know how to do this, I just want to be able to get the data.
The php execute takes a few centiseconds because it comunicates with SQL. (If this matters).
I have considered using invisible forms but it didn't seem to work
If anyone could point me in the right direction, that would be great.
Something like this?
$(document).ready(function(e) {
$('#inpamount').click(function() {
var data = 'myValue=' + $(this).val();
$.ajax({
url: "yourscript.php",
type: "POST",
data: data,
cache: false,
success: function(scriptOutput) {
//handle the result
}
}
});
return false;
});
});
I'd like to update a form, more exactly I wish to display an extra scroll menu, depending on the user's choice in a first scroll menu.
I have a page, mypage.php page on which there is a form. Here it is :
<form method="post" action="wedontcare.php" enctype="multipart/form-data">
<label for="base">3 - Select a DB </label><br />
<?php
include 'functions.php';
offers_choice_DB();
if (isset($_POST['base_name_choice'])){
offers_choice_table($_POST['base_name_choice']);
}
I have a separated file "functions.php" where are declared all the functions I use here. offers_choice_DB() displays a scroll menu where I can select a database (actually, this function performs a MySQL query and echoes the result in a scroll menu). If the user selects a database, then $_POST['base_name_choice'] exists. And it does, because when i only work with PHP/HTML, all is doing fine.
My purpose is to allow the user to select a database, then for this database I'd like to display a second scroll menu that displays some tables from this DB. This scroll menu will only be displayed if a POST value has been set. The offers_choice_table($_POST['base_name_choice']) function takes this value as an argument, then echoes the HTML for the scroll menu, containing the tables. Here we are !
Oh, and the submit button is not important here, because I want to have my second scroll menu displayed before the user clicks on the submit button, so we just disregard the target page, ok ?
Before, everything was OK : I used tests, conditions (isset...) but it was not dynamic, I had to call other pages, ...etc. And now I want, as you guessed, to use jQuery to refresh mypage.php as soon as the user selects a database so that an extra menu appears.
I started to listen to a change in my scroll menu, but then I don't know what to do to refresh my page with a POST parameter containing the selected database. Anyway, here is my code :
<script type="text/javascript">
$( '#base_name_choice' ).change(function() {
var val = $(this).val(); //here I retrieve the DB name
alert( val ); //I notify myself to check the value : it works
$.ajax({
type: 'POST', //I could have chosen $.post...
data: 'base_name_choice='+val, //I try to set the value properly
datatype: 'html', //we handle HTML, isn't it ?
success: function(){
alert( "call ok" ); //displays if the call is made
//and here...???? I don't know whatto do
}
})
});
</script>
Here it is...any help will be appreciated ! Thanks :)
Regards
The issue here is that your page is rendered first (html + php preprocessing). That means that once your page is rendered, you won't be able to make direct php method calls such as offers_choice_table or change the $_POST parameters.
How you normally do this, is by making an AJAX call from your javascript to a PHP script/method which than generates the second menu based on the parameter that the user chose.
So, you don't need this part:
if (isset($_POST['base_name_choice'])){
offers_choice_table($_POST['base_name_choice']);
}
because you will call "offers_choice_table" method with an ajax call.
You make the ajax call to a url which will return the second menu
$.ajax({
type: "GET",
url: "generate_second_menu.php",
data: { base_name_choice: val},
success: function(data){
alert( "call ok" ); //displays if the call is made
// here you can append the data that is returned from your php script which generates the second menu
$('form').append(data);
}
})
You should use GET instead of POST, in your new PHP file:
if (isset($_GET['base_name_choice'])) {
offers_choice_table($_GET['base_name_choice']);
}
You SHOULD check if the variable has a value set, especially if your function is expecting one. You can use whatever functions you want in this file, it is like any other PHP file you would write. Include any files that you want.
You should make sure to avoid SQL injection when using a GET or POST value in a query: How can I prevent SQL injection in PHP?
In the .ajax() call, there is a callback function success, this runs if the server response is good (i.e. not a 404 or 500). There first parameter in that function is what the server returned. In your case, it would be the HTML you echoed out. You can use jQuery to append the response to an element:
$.ajax({
type: "GET",
url: "generate_second_menu.php",
data: { base_name_choice: val},
success: function(data) {
// it looks like you're only returning the options of the select, so we'll build out the select and add them
var $newSelect = $('<select></select>');
$newSelect.append(data);
// and then add the select to the form (you may want to make this selector for specific)
$('form').append($newSelect);
}
});
i am developing a site with html and php ...
what i have done so far for like button on my page is as follow(concept is same only name is different on facebook it is like and on my site it is Points Up )
<form method="post">
<input type="hidden" value="<?php echo $posts[postid]; ?>" name="postid">
<input type="submit" name="pointsup" value="Points Up" />
</form>
the above will create the button with name Points Up.
if(isset($_POST['pointsup']))
{ in this if block i have written all queries to update database and user interface and all
}
what i want is instead of that button there should be some link witch will run my sql code.
i also tried JavaScript but it doesn't help anything
Thanks in advance for your answers!
When you are working with a single anchor tag (hyperlink), you should send your parameters by GET method. in case, /your/address/rate.php?id= and check $_GET['id'] in PHP (validate/sanitize/...)
also, you can send your requests as POST by using AJAX.
this is a sample for jQuery:
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
take a look here
but if you want to use pure JavaScript, you should work with XMLHttpRequest object. take a look here.
You should do something like:
Find where you should point your link to and what parameters are needed, i will call it $url. It can involve such things like creating additional files, refactoring your code, etc...
Write js method which will send request to $url. I will call this method sendPointsUp;
Create link which will react to onClick event and call sendPointsUp with desired parameters from there.
What you can do is just add a link with an id so you can reach it easily with jquery.
Create a php-page where you do the query and other stuff (security check, cookie, whatever you want to do), and finally attach an ajax event to the link to call your php-page.
Print the link in your page:
Vote up
Create php
<?php
// do the query and other stuff, return the result in json format
// if you want to do something with the result (for example display the votes)
Javascript
$('#voteup').click(function(e){
$.ajax({
url: "your/url/to/phpfile",
}).done(function(data) {
// rewrite link to undo vote or whatever you want
// do something with the returned data
});
});
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.