Send variable to PHP using AJAX - php

I've got a variable that I want to send to my PHP code that is on top of the code but I keep getting an error and undefined. dTotaal is the variable name and it contains a number. All this code is in the same page, so i am posting to the same page.
$('#emailVerzenden').click(function() {
$.ajax({
url: "content.php",
type: "post",
data: ({
totaal: dTotaal
}),
success: function(msg) {
alert('Data saved: ' + msg);
},
error: function(error) {
alert("couldnt be sent " + error);
}
});
On top of my page I've got this code. I'm not sure if it's correct, I am new at this.
if(isset($_POST['emailVerzenden']))
{
$totaal = $_POST['totaal'];
var_dump($totaal);
}
What I wanted was to put the value of the totaal data in $totaal but that is not working. The data is not being sent. I keep getting the error alert().

In your PHP code, you are checking the presence of a variable to use another. For me it should be:
if(isset($_POST['totaal']))
{
$totaal= $_POST['totaal'];
var_dump($totaal);
}

You are on right track but seperate PHP codes with jQuery codes then you will have full control of processing data asynchronously.
index.php
$('#emailVerzenden').click(function()
{
$.ajax
({
url: "content.php",
type: "post",
data:{totaal: dTotaal},
success: function(msg)
{
alert('Data saved: ' + msg);
},
error: function(error)
{
alert("couldnt be sent ".error);
}
});
And in your php file first check whether $_POST data is set
content.php
if(isset($_POST))
{
$totaal= $_POST['totaal'];
var_dump($totaal);
}

Mention your data which you wanna send in html & give it an ID.
<div id="total"> HERE COMES THE VARIABLE YOU WISH TO SEND </div>
Then pick up the data in that <div> by its ID document.getElementById('total').value like below:
var total=document.getElementById('total').value;
<script> var total=document.getElementById('total').value;
$.post('content.php',
{'total':total},
function(response){
if(response == 'YES'){}
});
</script>
Hope this will resolve your problem. Good Luck!

Kind of look like i didnt use preventDefault() thats why it wasnt working.
$('#emailVerzenden').click(function(e)
{
cms=$('#sCms').val();
templates= $('#templates').val();
onderdelen = $('input:checkbox:checked').map(function() {
return this.value;
}).get();
email = $('#email').val();
e.preventDefault();
$.ajax
({
type: "POST",
url:"test.php",
data:{postEmail : email,postOnderdelen : onderdelen,postCms : cms,postTotaal : postTotaal, postTemplates : templates},
success: function(rs)
{
alert("Data saved:" + rs);
},
error: function(error)
{
alert("couldnt be sent" + error);
}
});
e.preventDefault();
});

Related

display the array values-ajax

I want to display the values in datatable. How to retrieve the object value in ajax success function..
AJAX
$(function(){
$(document).on("click", "#submits", function(e) {
e.preventDefault();
var password = $("#password").val();
alert(password);
$.ajax({
type: "POST",
url: "db/add.php",
data: "password="+password,
success: function(results){
alert( "Data Saved: " + results );
var obj = JSON.parse(results);
}
});
e.preventDefault();
});
});
</script>
Perhaps you can try this -
$("#submits").bind("click", function(e) {
$.ajax({
type : "POST",
dataType : "json",
cache : false,
url : "db/add.php",
data : "password="+password,
success : function(results) {
alert("Data Saved: "+results);
var userInfo = JSON.parse(results);
//Output the data to an HTML element - example...
$(".user-name").html(userInfo.patient_name);
}else{
console.log('No user info found');
}
},
error : function(a,b,c) {
console.log('There was an error getting user info.');
}
});
});
//HTML element for data
<p class="user-name"></p>
I've added an HTML element you can simply output the data to. Not sure how you'd like the data to be output but this is simply an example.
Just some quick notes on your code from your original post -
You must set the dataType to json when working with/parsing json. See Documentation.
Once you assign your data to a variable, you need to access that data by declaring the variable and then the data name, such as obj.patient_name.
I've done the best I can to help.
Good luck.
Try this code :
$(results.patient_password).each(function(i,v){
console.log(v.id);
});
use data-type:json,
in your jquery

jQuery AJAX can't work with JSON response

I have a JSON response from my php file like:
[
{"id":"1"},
{"archiveitem":"<small>26.06.2015 12:25<\/small><br \/><span class=\"label label-default\">Bug<\/span> has been submitted by Admin"}
]
And try to fetch this response into a div after button was clicked, however firebug is telling me the message from the error-handler. I can't figure out the problem?
$('#loadarchive').click(function(){
$.ajax({
type: 'post',
url: '/src/php/LoadAdminDashboardArchive.php',
dataType: 'json',
data: {
action : 'getArchive'
},
success: function(results) {
var archiveelements = JSON.parse(results);
console.log(results);
$.each(archiveelements, function(){
$('#archivecontent').html('<div class="mark-read-container"><span class="btn-mark-unread" id="' + this.id + '">Unarchive</span></div><div class="bs-callout bs-callout-default">' + this.archiveitem + '</div>');
});
},
error: function(){
console.log('Cannot retrieve data.');
}
});
});
I tried to run your Code and I get
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
By defining dataType: 'json' your result is parsed already as an Array. So you can do something like:
success: function (results) {
if (results["head"]["foo"] != 0) {
// do something
} else if (results["head"]["bar"] == 1) {
// do something
}
}
this works on my computer:
$.ajax({
type: 'post',
url: '/src/php/LoadAdminDashboardArchive.php',
dataType: 'json',
data: { action : 'getArchive' },
success: function(results) {
console.log(results);
$.each(results, function(){
$('#archivecontent').html('<div class="mark-read-container"><span class="btn-mark-unread" id="' + this.id + '">Unarchive</span></div><div class="bs-callout bs-callout-default">' + this.archiveitem + '</div>');
});
},
error: function(){
console.log('Cannot retrieve data.');
}
});
You can get more information from the console if you dive into it a bit more. Or by logging these two parameters:
error: function(xhr, mssg) {
console.log(xhr, mssg);
}
First
your response is not correct,Correct response should look like this
[{
"id":"1",
"archiveitem":"<small>26.06.2015 12:25<\/small>
<br \/><span class=\"labellabel-default\">Bug<\/span> has been submitted by Admin"
},
{
...
}]
Second
You dont have to parse result ie.JSON.parse is not required since dataType:'json' will probably take care of json.
Finally your success method should look like this:
success: function(results) {
$.each(results, function(ind,el){
$('#archivecontent').html('<div class="mark-read-container"><span class="btn-mark-unread" id="' + el.id + '">Unarchive</span></div><div class="bs-callout bs-callout-default">' + el.archiveitem + '</div>');
});
},
As you are saying message from error-handler is showing.
That means AJAX is never sent to server because of incorrect URL or any other reason.
Use Firebug in Firefox and see the error in console tab.
Also I see your code
dataType: 'json',
data: { action : 'getArchive' },
success: function(results) {
var archiveelements = JSON.parse(results);
}
Do not use JSON.parse(results) because you have already written dataType: 'json', and any type of response is parsed automatically.
I was able to get it working and the problem was quite simple...
I forgot to paste the "button" - source code that initiated the ajax request. It was an Input of type "submit" and therefore the page reloaded by default after the response was retrieved successfully... so e.preventDefault(); was the way to go.
Thanks to all of you.

jQuery / Ajax to get html and save with php

I am trying to get a jQuery script to run behind the scenes with php. It basically will get the contents of a div with jQuery (works) then calls a script with ajax (works) but I need the ajax script that called the php to send the vars to php so I can save the conents.
Here is the code:
<script>
$( document ).ready(function() {
$( ".tweets" ).click(function() {
var htmlString = $( this ).html();
tweetUpdate(htmlString);
});
});
</script>
<script>
function tweetUpdate(htmlString)
{
$.ajax({
type: "POST",
url: 'saveTweets.php',
data: htmlString,
success: function (data) {
// this is executed when ajax call finished well
alert('content of the executed page: ' + data);
},
error: function (xhr, status, error) {
// executed if something went wrong during call
if (xhr.status > 0) alert('got error: ' + status); // status 0 - when load is interrupted
}
});
}
</script>
and my code for saveTweets.php
<?
// SUPPOSED TO receive html conents called htmlString taken from a div
// and then I will write this code to a file with php and save it.
echo $_POST[htmlString];
?>
You have to give a name to the parameter, so that PHP can retrieve it. Change the $.ajax call to do:
data: { htmlString: htmlString },
Then in your PHP, you can reference $_POST['htmlString'] to get the parameter.
Correct your funcion.
function tweetUpdate(htmlString)
{
$.ajax({
type: "POST",
url: 'saveTweets.php',
data: "htmlString="+htmlString,
success: function (data) {
// this is executed when ajax call finished well
alert('content of the executed page: ' + data);
},
error: function (xhr, status, error) {
// executed if something went wrong during call
if (xhr.status > 0) alert('got error: ' + status); // status 0 - when load is interrupted
}
});
}
then on saveTweets.php page write below line, you will get value on that page.
echo '<pre>';print_r($_REQUEST );echo '</pre>';
Using json is better for sending data:
data_htlm=[];
data_html.push({"htmlString": htmlString});
$.ajax(
{
type: "POST",
dataType: "json",
url: "saveTweets.php",
data: JSON.stringify(data_html),
success: function(html)
{
console.log(html);
}
});
now with php you can just do this:
echo $_POST['htmlString'];
You can use the $.post method to post to a PHP page and then retrieve the result from that page in a callback function.

Trying to make AJAX work on simple login form

I have been trying for hours to make this work but I am not getting anything back when doing the ajax call. I am new to Ajax and it could probably be something you will see but that I am unable to. I would appreciate you help. Here is my code.
HTML
<script>
$("#submitlogin").click(function() {
inputs = {
"logInUsername" : $('input[name=logInUsername]').val(),
"logInPassword" : $('input[name=logInPassword]').val()
};
// since this is a username and password combo you will probably want to use $.post
$.ajax ({
type: "POST",
url: "loggnow.php",
data: inputs,
success: function() {
$("#login").html("You are now logged in!");
}
});
});
</script>
loggnow.php
<?php
extract($_POST);
if($_POST)
{
echo 'Yes the ajax posted';
}
?>
Try this :
$(document).ready(function(){
$("#submitlogin").click(function() {
inputs = {
"logInUsername" : $('input[name=logInUsername]').val(),
"logInPassword" : $('input[name=logInPassword]').val()
};
// since this is a username and password combo you will probably want to use $.post
$.ajax ({
type: "POST",
url: "loggnow.php",
data: inputs,
success: function() {
$("#login").html("You are now logged in!");
},
error : function(jqXHR, textStatus, errorThrown){
alert("error " + textStatus + ": " + errorThrown);
}
});
});
});
This will give you an alert if an error occurs in AJAX with details
EDIT:
As Leo pointed it out, your code might be executing too fast, try the modified code above so that you make sure it runs after all the page has loaded
Try to put your function inside
$(function(){
//attach the button click here
});
this way your code will only run after the body loaded (so you are sure that you button exists) - look here
you just need a web server host looks like this:http://127.0.0.1:8084/xxx

Updating div using ajax not working correctly

Sorry but I know something similar to this has already been posted. I have tried every single resource out there and did my research and I still couldn't find out what is wrong with my code. I am using a Ajax Post with php. Everything seems to be working fine except for the fact that the div is not reloading on submit. After I refresh the page what I posted came up. Can someone please tell me what I am doing wrong.
js code:
$(function() {
$('.error').hide();
$('input.text-input').css({
backgroundColor: "#FFFFFF"
});
$('input.text-input').focus(function() {
$(this).css({
backgroundColor: "#C0DDFA"
});
});
$('input.text-input').blur(function() {
$(this).css({
backgroundColor: "#FFFFFF"
});
});
$(".button").click(function() {
// validate and process form
// first hide any error messages
$('.error').hide();
var email = $("input#email").val();
if (email == "") {
$("label#email_error").show();
$("input#email").focus();
return false;
}
var dataString = '&email=' + email;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "../EdinburgCISD/Gorena/Gorena.php",
data: dataString,
success: function(data) {
$("#email").val('');
$("#div").fadeOut(1000);
// Change the content of the message element
$("#div").html(data);
// Fade the element back in
$("#div").fadeIn(1000);
}
});
return false;
});
});​
html code:
This is where I have my div.
<div id="div"> <?php \\database select query ?> </div>
I am new to this website sorry if I posted something wrong...
did you get any error in console (firebug/developer tools) ?
otherwise you can try below
check with alert
$.ajax({
type: "POST",
url: "../EdinburgCISD/Gorena/Gorena.php",
data: dataString,
success: function(data) {
alert(data);//what you get here? are you getting "object" in alert? then you need to specify property or mention dataType
$("#email").val('');
$("#div").fadeOut(1000);
// Change the content of the message element
$("#div").html(data);
// Fade the element back in
$("#div").fadeIn(1000);
}
});
modified your code a bit see the comments, you should specify dataType:html (see the ajax part).
$(function() {
$('.error').hide();
$('input.text-input').css({backgroundColor:"#FFFFFF"});
$('input.text-input').focus(function(){
$(this).css({backgroundColor:"#C0DDFA"});
});//focus ends
$('input.text-input').blur(function(){
$(this).css({backgroundColor:"#FFFFFF"});
});//blur ends
$(".button").click(function() {
// validate and process form
// first hide any error messages
$('.error').hide();
var email = $("input#email").val();
if (email == "") {
$("label#email_error").show();
$("input#email").focus();
return false;
}
//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: "../EdinburgCISD/Gorena/Gorena.php",
data: {email:dataString}, //in the php file do $email = $_POST['email'];
async:false, //not a good practice but you can try with it and without it
success: function(data) {
$("#email").val('');
$("#div").fadeOut(1000);
// Change the content of the message element
$("#div").html(data);
// Fade the element back in
$("#div").fadeIn(1000);
}
}); //ajax ends
return false;
});//click ends
});//document ready ends
update
see this fiddle you will get the idea http://jsfiddle.net/3nigma/LuCQw/ and the delay function is optional i have used it so that the effect is prominent

Categories