I'm still new to JQuery and trying to learn how to submit form without page refresh...
What I want is, when the form is submitted, the value of what I type on "headline" and "subheadline" can be passed into php variable (So I can echo/insert data to database, etc)
So, I put
"<? echo $_POST['headline']; ?>"
on
<span class="save-notice">Your change has been saved! <? echo $_POST['headline']; ?></span>
but when I fill the form and click the submit button, it only shows "Your change has been saved!". Which means, the variable can't be passed to PHP.
The HTML and the JS is combined into 1 file. I left the URL method on .ajax because it is processed in the same file.
HTML FORM
<div id="submit-form">
<form action="" id="select-block" class="general-form">
<div class="input-wrap">
<input class="clearme" name="Headline" value="Your headline here" id="headline"/>
</div>
<div class="input-wrap">
<textarea class="clearme" name="Sub-Headline" id="subheadline">Sub Headline Here</textarea>
</div>
<input type="submit" class="submit-btn" value="SAVE" />
<span class="save-notice">Your change has been saved! <? echo $_POST['headline']; ?></span>
</form>
</div>
And the JQUERY CODE
<script type="text/javascript">
$(function() {
$(".save-notice").hide();
$(".submit-btn").click(function() {
var headline = $("input#headline").val();
var subheadline = $("textarea#subheadline").val();
var dataString = 'headline='+ headline + '&subheadline=' + subheadline;
alert(dataString)
$(".save-notice").hide();
$.ajax({
type: "POST",
url: "",
data: dataString,
success: function() {
$(".save-notice").show();
}
});
return false;
});
});
</script>
I saw on several example/tutorial on the internet if it can be done like that. Can you advise?
See
http://api.jquery.com/serialize/
Instead of adding code to click handler
$(".submit-btn").click(function() { ... }
use submit handler
$("#select-block").submit(function() {
// your code
var dataString = $(this).serialize();
});
The $_POST['headline'] in your save-notice was generated when the page was loaded. The PHP ran, and output an HTML file.
When you make your AJAX request, the page returned to the AJAX call would contain your new value, but your current page does not.
You can either post to a different page, have that page return a value, then use JavaScript to change the value of the div.
Or, you can try to extract the data from the returned HTML page.
$(".save-notice").hide();
$.ajax({
type: "POST",
url: "",
data: dataString,
dataType: 'html', // the page returned
success: function(data) {
// get the data from the returned page
$(".save-notice").html($('.save-notice', data).html());
$(".save-notice").show();
}
});
Using Firebug's console feature, you can see the server's response to your AJAX call. The response is evaluating the $_POST var like you want it to, but since the AJAX call happens behind the scenes, you don't see it.
To get your script working without much modification, try this (no PHP is necessary):
Replace <? echo $_POST['headline']; ?> with <span id="yourheadline"><span>
Insert $('#yourheadline').html(headline); on the line before $(".save-notice").show();
Another thing I would suggest is serializing your form to create the dataString var, instead of doing it input by input. If your inputs were named headline and subheadline instead of Headline and Sub-Headline...
var dataString = $("#select-block").serialize();
...would accomplish the same thing as:
var headline = $("input#headline").val();
var subheadline = $("textarea#subheadline").val();
var dataString = 'headline='+ headline + '&subheadline=' + subheadline;
You already have the values in the javascript variables:
var headline = $("input#headline").val();
var subheadline = $("textarea#subheadline").val();
You can do something like this:
$.ajax({
type: "POST",
url: "foo.php",
data: {headline: headline, subheadline: subheadline},
success: function() {
$(".save-notice").show();
}
});
or like this:
$.post("foo.php", { headline: headline, subheadline: subheadline },
function(data) {
$(".save-notice").show();
}
);
You can see that, data is passed in the key value pair:
{ headline: headline, subheadline: subheadline }
You can access it using $_POST like $_POST['headline'] and $_POST['subheadline']
Related
I need to use a localStorage value in a PHP file to update values in my database. I know that I need ajax to achieve this, I can't get it to work.
My localStorage item is named option and it exists (checked in browser and stored the value in a div)
$(document).ready(function(){
$.ajax({
type: "POST",
url: "activity.php",
data: { storageValue: localStorage.getItem('option') },
success: function(data){
alert('success');
}
});
});
PHP Example:
$option = $_POST['storageValue'];
mysql_query("...SET x = '".$option."'...");
echo 'Update complete';
I dont see any post data nor do I get a response.
Thank you!
Your page:
<form>
<input type="hidden" value="thedatayouwanttopost" id="option"/>
</form>
<script src="Your_Js_File.js"></script>
Your JS file:
document.getElementById('option').submit(); // This submits the form
var storageValue = $('#option').val(); // This gets the value of the form once it has been posted to the .php file
$(document).ready(function(){
$.ajax({
type: "POST",
url: "activity.php",
data: { storageValue:storageValue },
success: function(data){
alert('success');
}
});
return false; // This stops the page from refreshing
});
Your PHP file to callback the data to AJAX and display the alert (activity.php):
...
$option = $_POST['storageValue']; // This is the post value of your hidden input on your page
mysql_query("...SET x = '".$option."'...");
?><input type="hidden" id="option" value="<?php echo $option; ?>"><?
// The input above posts the value of 'option' on your page back to your Ajax and spits out the request.
...
I'm trying to show a specific div depending on the result of a SQL query.
My issue is that I can't get the divs to switch asynchronously.
Right now the page needs to be refreshed for the div to get updated.
<?php
//SQL query
if (foo) {
?>
<div id="add<?php echo $uid ?>">
<h2>Add to list!</h2>
</div>
<?php
} else {
?>
<div id="remove<?php echo $uid ?>">
<h2>Delete!</h2>
</div>
<?php
}
<?
<script type="text/javascript">
//add to list
$(function() {
$(".plus").click(function(){
var element = $(this);
var I = element.attr("id");
var info = 'id=' + I;
$.ajax({
type: "POST",
url: "ajax_add.php",
data: info,
success: function(data){
$('#add'+I).hide();
$('#remove'+I).show();
}
});
return false;
});
});
</script>
<script type="text/javascript">
//remove
$(function() {
$(".minus").click(function(){
var element = $(this);
var I = element.attr("id");
var info = 'id=' + I;
$.ajax({
type: "POST",
url: "ajax_remove.php",
data: info,
success: function(data){
$('#remove'+I).hide();
$('#add'+I).show();
}
});
return false;
});
});
</script>
ajax_add.php and ajax_remove.php only contain some SQL queries.
What is missing for the div #follow and #remove to switch without having to refresh the page?
"I'm trying to show a specific div depending on the result of a SQL query"
Your code doesn't seem to do anything with the results of the SQL query. Which div you hide or show in your Ajax success callbacks depends only on which link was clicked, not on the results of the query.
Anyway, your click handler is trying to retrieve the id attribute from an element that doesn't have one. You have:
$(".plus").click(function(){
var element = $(this);
var I = element.attr("id");
...where .plus is the anchor element which doesn't have an id. It is the anchor's containing div that has an id defined. You could use element.closest("div").attr("id") to get the id from the div, but I think you intended to define an id on the anchor, because you currently have an incomplete bit of PHP in your html:
<a href="#" class="plus" ?>">
^-- was this supposed to be the id?
Try this:
<a href="#" class="plus" data-id="<?php echo $uid ?>">
And then:
var I = element.attr("data-id");
Note also that you don't need two separate script elements and two document ready handlers, you can bind both click handlers from within the same document ready. And in your case since your two click functions do almost the same thing you can combine them into a single handler:
<script type="text/javascript">
$(function() {
$(".plus,.minus").click(function(){
var element = $(this);
var I = element.attr("data-id");
var isPlus = element.hasClass("plus");
$.ajax({
type: "POST",
url: isPlus ? "ajax_add.php" : "ajax_remove.php",
data: 'id=' + I,
success: function(data){
$('#add'+I).toggle(!isPlus);
$('#remove'+I).toggle(isPlus);
}
});
return false;
});
});
</script>
The way i like to do Ajax Reloading is by using 2 files.
The first: the main file where you have all your data posted.
The second: the ajax file where the tasks with the db are made.
Than it works like this:
in the Main file the user lets say clicks on a button.
and the button is activating a jQuery ajax function.
than the ajax file gets the request and post out (with "echo" or equivalent).
at this point the Main file gets a success and than a response that contains the results.
and than i use the response to change the entire HTML content of the certain div.
for example:
The jQuery ajax function:
$.ajax({
type: 'POST', // Type of request (can be POST or GET).
url: 'ajax.php', // The link to the Ajax file.
data: {
'action':'eliran_update_demo', // action name, used when one ajax file handles many functions of ajax.
'userId':uId, // Simple variable "uId" is a JS var.
'postId':pId // Simple variable "pId" is a JS var.
},
success:function(data) {
$("#div_name").html(data); // Update the contents of the div
},
error: function(errorThrown){
console.log(errorThrown); // If there was an error it can be seen through the console log.
}
});
The PHP ajax function:
if (isset($_POST['action']) ) {
$userId = $_POST['userId']; // Simple php variable
$postId = $_POST['postId']; // Simple php variable
$action = $_POST['action']; // Simple php variable
switch ($action) // switch: in case you have more than one function to handle with ajax.
{
case "eliran_update_demo":
if($userId == 2){
echo 'yes';
}
else{
echo 'no';
}
break;
}
}
in that php function you can do whatever you just might want to !
Just NEVER forget that you can do anything on this base.
Hope this helped you :)
if you have any questions just ask ! :)
This code, if click on text inside div class="example4DOMWindow" sends defined values to php and then get back php data and in popup window displays data received from php.
Here is example http://jsfiddle.net/rigaconnect/q3RcV/1/
This is ajax that sends and receives data
$(document).ready(function()
{
var one = $("#first_var").text();
var two = $("#second_var").text();
$.ajax({
type: "POST",
url: '__popup-window_ajax.php',
data: {var1: one, var2: two },
dataType: "json",
success: function(data) {
$('#load').html(data);
}
});
});
This part of code displays popup window (sample here http://swip.codylindley.com/DOMWindowDemo.html)
<body>
<div id="first_var" class="example4DOMWindow" style="width: 50px;">text one</div>
<div id="second_var" class="example4DOMWindow" style="width: 50px;">text two</div>
<script type="text/javascript">
$('.example4DOMWindow').openDOMWindow({
eventType:'click',
windowSourceID:'#example4InlineContent',
});
</script>
<div id="example4InlineContent" style="display:none">
<div>
<div id="load"></div>
</div>
</div>
</body>
And this is php file code
$p_one = $_POST['var1'];
$p_two = $_POST['var2'];
$test = $p_one. '<br>test<br>'. $p_two;
echo json_encode($test);
The code sends to php only var that is defined. Like var one = $("#first_var").text(); So if no var inside ajax code, nothing send. And sends all vars.
Necessary the code to send to php only clicked text. User clicks on text one, sends text one and do not send text two; clicks on text two, sends only text two.
Here https://stackoverflow.com/a/17622947/2360831 / http://jsfiddle.net/aGWGn/5/
clicked text is passed as value to javascript.
Tried to put all together like this
$(document).ready(function(){
document.body.onmousedown = whichElement;
var output = document.getElementById("load")
function whichElement(e) {
e = e || window.event;
var targ = e.target || e.srcElement;
if (targ.nodeType===3) {// defeat Safari bug
targ = targ.parentNode;
}
output.innerHTML = targ.innerHTML;
}
//var one = $("#first_var").text();
var one = targ;
var two = $("#second_var").text();
$.ajax({
type: "POST",
url: '__popup-window_ajax.php',
data: {var1: one, var2: two },
dataType: "json",
success: function(data) {
$('#load').html(data);
}
});
});
But the code does not pass var one = targ; to php file (var two also does not pass).
From my understanding the main question is how to pass var targ or var output(?) to var one....
Please, advice what is incorrect
Update
Changed data to data: {var1: output, var2: two },
and in popup window see
[object HTMLDivElement]
test
text two
text two
Changed to var one = targ.innerHTML; but does not work....
Changes to get to work
Changed var output = document.getElementById("load") to var output = document.getElementById("load1")
In html added <div id="load1"></div>
And changed
//var one = $("#first_var").text();
var one = targ;
var two = $("#second_var").text();
to var one = $("#load1").text();
Now seems work. But think the code need improvements
From what I understand, you need to pass only the clicked text to php, right?
If so, you don't need all that code from the moment you are using jquery. You just need to attach a 'click' event handler to .example4DOMWindow and send only the text of the clicked div.
index.html:
<body>
<!--
<script src="jquery-2.0.3.js"></script>
<script src="jquery.DOMWindow.js"></script>
-->
<div id="first_var" class="example4DOMWindow">text one</div>
<div id="second_var" class="example4DOMWindow">text two</div>
<div id="example4InlineContent" style="display:none">
<div id="load"></div>
</div>
<script>
$(document).ready(function() {
$('.example4DOMWindow').openDOMWindow({
eventType:'click',
windowSourceID:'#example4InlineContent',
});
$(".example4DOMWindow").on('click', function(event){
$.ajax({
type: 'POST',
url: '__popup-window_ajax.php',
data: { 'clickedText' : $(this).text() },
success: function(data) {
$('#load').html(data);
}
});
});
});
</script>
</body>
__popup-window_ajax.php:
<?php
$var = $_POST['clickedText'];
echo json_encode($var);
?>
When ever I pass a value from a form using submit to a php file using load, $.get or post and try to receive data or load it in general as shown below, I just get ruturned a null or undefined value. Anyone know what im doing wrong ?
iNDEX.HTML
`
<script type = "text/javascript">
$(document).ready(function(){
$("#NewOrgForm").submit(function(){
var name = $("#companyname").val();
$(".content").load("NewEntry.php",{Name: name});
});
});
</script>
<form id="NewOrgForm">
<p> Name: <input type="text" id="companyname" value="" /> </p>
<p> <input type="submit" value="Submit New Entry" id="submit" /> </p>
</form>
NEWENTRY.PHP
<?php
$companyname = $_POST['Name'];
echo $companyname;
?>
`
From some of the comments you posted it looks to me like you are incorrectly collecting data from the form. Have you tried making an alert to see if the name variable is actually set? Also try using firebug or something to see the exact URL you're loading.
Perhaps try using a directly passed event reference to the function and fetch the fields from there instead of using an absolute selector. Might help.
Is there actually an element in your HTML that has the class "content"?
Try making use of the callback function so that you are aware that the load actually ran:
$('#result').load('ajax/test.html', function() {
alert('Load was performed.');
});
The above code is taken from the jquery site (http://api.jquery.com/load/)
UPDATE: The more I look at this, the more I think that you are probably better going w/.post (http://api.jquery.com/jQuery.post/)
UPDATE2: What happens if you try this:
$(document).ready(function(){
runOnLoad('content');
});
function runOnLoad(className){
var name="peter";
var ajaxData = {"Name": name};
var url="NewEntry.php";
var contentToReturn="";
$.ajax({
type: "POST",
url: url,
data: ajaxData,
datatype: "html",
success: function(html) {
contentToReturn="Success! It returned "+html+"<br>";
$('div.'+className).html(contentToReturn);
},
error: function(html) {
contentToReturn="Failure! It returned "+html+"<br>";
$('div.'+className).html(contentToReturn);
}
});
return;
}
If you're just doing a POST, it should look something like:
<script type = "text/javascript">
$(document).ready(function(){
$("#NewOrgForm").attr({
"method": "POST",
"action": "NewEntry.php"
}).submit();
});
</script>
although why even use jquery for this, then...just set method and action attribs on your form element...
What happens is that I'm able to add and delete records from form using jQuery and PHP scripts to MYSQL database, but I am not able to update data which was retrieved from the database. The file structure is as follows:
index.php is a file with jQuery functions where it displays form for adding new data to MYSQL using save.php file and list of all records are view without refreshing page (calling load-list.php to view all records from index.php works fine, and save.php to save data from form)
-> Delete is an function called from index.php to delete record from MySQL database (function calling delete.php works fine)
-> Update is an function called from index.php to update data using update-form.php by retriving specific record from MySQL table, (works fine)
Problem lies in updating data from
update-form.php to update.php (in
which update query is written for
MySQL)
I have tried in many ways - at last I had figured out that data is not being transferred from update-form.php to update.php; there is a small problem in jQuery AJAX function where it is not transferring data to update.php page. Something is missing in calling update.php page it is not entering into that page.
Please find the link below to download all files which is of 35kb (virus free assurance):
download mysmallform files in ZIPped format, including mysql query
<pre>
<body>
<div class="container">
<form id="submit" method="post">
<fieldset>
<legend>Enter Information</legend>
<label for="Name">Name : </label>
<input id="name" class="text" name="name" size="20" type="text">
<label for="gender">Gender : </label>
<input id="gender" class="text" name="gender" size="20" type="text">
<label for="dob">DoB : </label>
<input id="dob" class="date" name="dob" size="20" type="text"> <button> Add </button>
</fieldset>
</form>
<div class="name_list"></div>
<div class="update_form"></div>
</div>
<script type="text/javascript">
$(document).ready(function(){
function loadList(){
$.ajax({
url: "load-list.php",
cache: false,
success : function(html){
$(".name_list").html(html);
}
});
}
loadList();
$("form#submit").submit(function() {
// we want to store the values from the form input box, then send via ajax below
var x=window.confirm("Are you sure you want to delete this item?")
var name = $('#name').attr('value');
var gender = $('#gender').attr('value');
var dob = $('#dob').attr('value');
if (x==true){
$.ajax({
type: "POST",
url: "save.php",
data: "name="+ name +"& gender="+ gender +"& dob="+ dob,
success: function(){
loadList();
}
});
}
return false;
});
$(".delete_button").live("click", function(){
//this deletes the row clicked on with an alert and then reloads the list
var id = $(this).attr("id");
var x=window.confirm("Are you sure you want to delete this item?")
if (x==true){
$.ajax({
type: "POST",
url: "delete.php",
data: "id="+ id,
success: function(){
loadList();
}
});
}
return false;
});
$(".update_button").live("click", function(){
//this loads the update form
var id = $(this).attr("id");
$.ajax({
url: "update-form.php",
data: "id="+ id,
cache: false,
success: function(html){
$(".update_form").html(html);
}
});
return false;
});
$("#updateform").ajaxform("submit",function(){
//$("form#update").live("submit",(function() {
// we want to send via ajax and empty the html from the update_form element
var name = $('#name_update').attr('value');
var gender = $('#gender_update').attr('value');
var dob = $('#dob_update').attr('value');
var id = $('#id').attr('value');
alert (name);
$.ajax({
url: "update.php",
type: "POST",
data: "name="+ name +"& gender="+ gender +"& dob="+ dob,
error: function(){
alert('Error loading document');
},
success: function(){
alert (" i am in success below load list ");
$(".update_form").empty();
loadList();
}
});
return false;
});
});
</script> </body>
</pre>
I copy-pasted your code into a php file and get a "$ is not defined" error in javascript. I look at your code tells me that you have not included the jquery file. Try using firefox as the browser and firebug for debugger to avoid such minor issues.
You know, JQuery also has a post function. Nothing wrong with using normal html to handle requests. Not everything must be run through listeners.
function updateQuery(){
var name = $('#name_update').attr('value');
var gender = $('#gender_update').attr('value');
var dob = $('#dob_update').attr('value');
$.post('update.php', { name:name, gender:gender, dob:dob }, function(data){
if(data == 'success')
{
$(".update_form").empty();
loadList();
}
else
{
alert('fail');
}
});
}
sometimes jquery does not like single variable $.post requests. have you tried passing a second null variable?
I have not looked at your code. If add and delete work, then update should also unless you're overlooking something obvious or you're just falling for the same single variable garbage I had happen.