So I'm trying to pass 2 datas from AJAX to PHP so I can insert it in my database but there seems to be something wrong.
My computation of the score is right but it seems that no value is being passed to my php file, that's why it's not inserting anything to my db.
AJAX:
<script type = "text/javascript" language="javascript">
$(document).ready(function() {
$("#finishgs").click(function(){
var scoregs = 0;
var remarkgs = "F";
var radios = document.getElementsByClassName('grammar');
for (var x=0; x<radios.length; x++){
if (radios[x].checked) {
scoregs++;
}
else
scoregs = scoregs;
}
if (scoregs >= 12){
remarkgs = "P";
}
else{
remarkgs = "F";
}
});
});
$(document).ready(function() {
$("#GTScore").click(function(event) {
$.post(
"dbinsert.php",
{ scoregs:scoregs , remarkgs: remarkgs},
function(data){
$('#inputhere').html(data);
}
);
});
});
PHP:
if( $_REQUEST["scoregs"] || $_REQUEST["remarkgs"]) {
$scoregs = $_REQUEST['scoregs'];
$remarkgs = $_REQUEST['remarkgs'];
}
There is an extra closing bracket );, you should remove. Try this:
$(document).ready(function() {
$("#GTScore").click(function(event) {
event.preventDefault();//to prevent default submit
$.ajax({
type:'POST',
url: "dbinsert.php",
{
scoregs:scoregs ,
remarkgs: remarkgs
},
success: function(data){
$('#inputhere').html(data);
}
});
});
And in php, you need to echo the variable or success/fail message after you insert data into the database:
echo $scoregs;
echo $remarkgs;
Related
I want to show notifications when new row inserted.I've achieved it through the below code,
Ajax
<script>
var old_count = 0;
var i=0;
setInterval(function(){
$.ajax({
url : "shownotify",
success : function(data){
if (data > old_count)
{
if (i == 0)
{old_count = data;}
else{
$('#notify').html("New user");
old_count = data;
}
} i=1;
}
});
},1000);
</script>
Now I want to show the count of new users which I returned from controller,
public function shownotify()
{
$action=DB::table('users')->where('admin_action_at', 'null')->count();
$data=Move::count();
return compact('action', 'data');
}
How do I get it in ajax function?Can anybody help?
You need to pass the array $data but you are passing a string.
public function shownotify()
{
$action=DB::table('users')->where('admin_action_at', 'null')->count();
$data=Move::count();
$return_array = compact('action', 'data');
return json_encode($return_array);
}
And make a little change in your ajax success callback function like:
success : function(data){
if (data.data > old_count)
{
if (i == 0)
{old_count = data.data;}
else{
$('#notify').html(data.data + "New user");
old_count = data.data;
}
} i=1;
Please help,
I have a dynamically generated set of button-incremented inputs. First i store id's and values into localstorage, and everything goes fine and i can see all the id-value pairs, but i cannot send the data using AJAX call.
Here's what it looks like:
The AJAX is assigned on button click:
<script>
$("#send_order").click(function (e) {
if (localStorage) {
if (localStorage.length) {
for (var i = 0; i < localStorage.length; i++) {
var pid = localStorage.key(i);
var value = localStorage.getItem(localStorage.key(i));
$.ajax({
url: "update.php?pid="+pid+"&qty="+value,
success: function(){
alert( "Прибыли данные: ");
}
});
}
} else {
output += 'Нет сохраненных данных.';
}
} else {
output += 'Ваш браузер не поддерживает локальное хранилище.';
}
)};
</script>
But nothing happens when the button is clicked.
What i do wrong?
While your code looks fine it is little inefficient to send your localstorage data one by one in a loop. It makes more sense to convert your localstorage to a json string and send everything at the same time. You can json_decode the json string in your php update script. Also I included a function to test if localStorage is available by trying to write in it. This is more reliable then if(localStorage)
$("#send_order").on("click", function () {
var output='';
if(localStorageTest() === true){
console.log('localStorage is available');
if(localStorage.length){
var data=JSON.stringify(localStorage);
$.ajax({
type: "GET",
url: "update.php?data="+data,
success: function(){
alert( "your data is send correctly!");
}
});
}else{
output += 'localStorage is empty\n';
}
}else{
output += 'localStorage is not available\n';
}
})
function localStorageTest(){
var test = "test";
try {
localStorage.setItem(test, test);
localStorage.removeItem(test);
return true;
} catch(e) {
return false;
}
}
I'm trying to pass the value of the dropdown menu to the PHP variable $anno, so the print_r() function at the end can use the realtive $coefficiente variable (which depends on $anno).
<select name="anno">
<option>1940</option>
<option>1941</option>
<option>1942</option>
</select>
<?php
$importo = "100";
$anno = $_POST["anno"];
if ( $anno == "1940" ) { $coefficiente = "10"; } ;
if ( $anno == "1941" ) { $coefficiente = "20"; } ;
if ( $anno == "1942" ) { $coefficiente = "30"; } ;
print_r(($importo*$coefficiente)/1936.27); echo '€';
?>
Can this be "AJAXified"?
At this time when I choose the dropdown option, the print_r function isn't updated. Do I need a submit button?
If you want to calculate your formula in the same page, don't use PHP use Javascript
<select name="anno">
<option>1940</option>
<option>1941</option>
<option>1942</option>
</select>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
// We bind our AJAX handler to the onChange event of the select element
$("select[name='anno']").on('change', function(e) {
var importo = "100";
var anno = $(this).val();
var coef = "";
if (anno == 1940) { coef = 10; }
if (anno == 1941) { coef = 20; }
if (anno == 1942) { coef = 30; }
alert(importo*coef/1936.27 + "€");
})
});
For PHP handling, use AJAX (warning I couldn't test this!)
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
// We bind our AJAX handler to the onChange event of the select element
$("select[name='anno']").on('change', function(e) {
$.ajax({
type: "POST",
url : "your_php_script.php",
data: { anno: $(this).val() },
})
.done(function(data) {
alert(data);
})
.fail(function(jqXHR, textStatus, errorThrown) {
alert("Something went wrong!\n" + errorThrown);
});
})
});
My ajax call goes and enters a record into a database (it's the first part of a form recording data) so I need it to return the id from the database entry.
Problem is, it's firing twice, so it's making 2 database entries each time.
I tried using a $count and while($count>0) in my php code to make sure that wasn't looping - and I didn't think it was, so the problem lies in my jQuery.
I tried putting the preventDefault on my submit button click function and that didn't work either.
Here's my code:
$(document).ready(function(){
$('#wpgstep1').one('click',function(){
// validate form fields are all filled in
var budget=$('#budget').val();
if(budget=='')
{
$('#budgeterror').show();
}
var yellowpages=$('#ads-yellowpages').val();
var flyers=$('#ads-flyers').val();
var brochures=$('#ads-brochures').val();
var radiotv=$('#ads-radiotv').val();
var none=$('#ads-none').val();
var other=$('ads-other').val();
var otherstatement=$('ads-other-statement').val();
var cust_id=$('#cust_id').val();
if(other !='')
{
if(otherstatement==='')
{
$('#adsothererror').show();
}
}
else
{
otherin='0';
}
if(yellowpages==="on")
{
yellowpagesin='1';
}
else{
yellowpagesin='0';
}
if(flyers==="on")
{
flyersin='1';
}
else
{
flyersin='0';
}
if(brochures==="on")
{
brochuresin='1'
}
else
{
brochuresin='0';
}
if(radiotv==="on")
{
radiotvin='1';
}
else
{
radiotvin='0';
}
if(none==="on")
{
nonein='1'
}
else
{
nonein='0';
}
var dataString='cust_id=' + cust_id + '&step=1&budget=' + budget + '&yellowpages='+yellowpagesin + '&flyers=' + flyersin + '&brochures=' + brochuresin + '&radiotv='+ radiotvin + '&none='+ nonein + '&other=' + otherstatement;
$.ajax({
type: "POST",
url: "submitwpg.php",
data: dataString,
dataType:'json',
success: function(data)
{
alert(data);
var i="";
var p=eval (data);
for (i in p)
{
$('#wpgpart2').append('<input type=hidden name=wpgid value=' + p[i] + '>');
}
$('#wpgform1').hide();
$('#wpgform2').show();
}
});
return false;
});
});
Make a global var
var form_submitting = false;
Above your ajax call
if(form_submitting == false){
form_submitting = true;
//your ajax call
}
In your success function of your ajax call
form_submitting = false;
if your submit button is inside of a form, it may be possible that your ajax function is executing and then your form is posting regularly. You could try turning your
<input type='submit' />
into
<button type='button' onclick='validateAndAjaxFunction(); return false;'></button>
I'm trying to pass a variable via jquery ajax call. I'm not exactly sure how to do it properly. I get the lon lat coordinates through another html5 script.
How do i get the coordinates on the other side? I tried $_GET(lat).
I'm also not sure if i'm able to use the location.coords.latitude in a different < script >.
$.ajax({
cache: false,
url: "mobile/nearby.php",
dataType: "html",
data: "lat="+location.coords.latitude+"&lon="+loc.coords.longitude+,
success: function (data2) {
$("#nearbysgeo").html(data2);
}
});
These scripts are above the jquery code
<script type="text/javascript">
google.setOnLoadCallback(function() {
$(function() {
navigator.geolocation.getCurrentPosition(displayCoordinates);
function displayCoordinates(location) {
var map = new GMap2(document.getElementById("location"));
map.setCenter(new GLatLng(location.coords.latitude, location.coords.longitude), 12);
map.setUIToDefault();
var point = new GLatLng(location.coords.latitude, location.coords.longitude);
var marker = new GMarker(point);
map.addOverlay(marker);
}
})
});
</script>
<script type="text/javascript" charset="utf-8">
function getLocation(){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error);
} else {
document.getElementById("output").innerHTML = "Your browser doesn't handle the GeoLocation API. Use Safari, Firefox 4 or Chrome";
}
}
function success(loc){
console.log(loc);
strout = "";
for(l in loc.coords){
//strout += l +" = " +loc.coords[l] + "<br>";
}
strout += '';
strout += '<center><img src="http://maps.google.com/maps/api/staticmap?center='+loc.coords.latitude+','+loc.coords.longitude+'&markers=color:blue%7Clabel:Y%7C'+loc.coords.latitude+','+ loc.coords.longitude+'&zoom=15&size=400x250&sensor=false¢er=currentPosition"></center>';
document.getElementById("output").innerHTML = strout;
document.forms['newPostForm'].lat.value = loc.coords.latitude;
document.forms['newPostForm'].lon.value = loc.coords.longitude;
document.getElementById("coords").innerHTML = '';
document.getElementById("coords").innerHTML = 'CURRENT: Lat:' + loc.coords.latitude + ' Lon:' + loc.coords.longitude;
}
function error(err){
document.getElementById("output").innerHTML = err.message;
}
function clearBlog() {
document.getElementById("listview").innerHTML = '';
}
</script>
ADDITIONAL INFO:
It works if I use this line. So i guess i can't use loc.coords.latitude this way.
data: "&lat=43&lon=-79.3",
Well i hacked it for now to get it working. I filled two hidden form elements on the page with lon and lat values. Then used 'document.forms['newPostForm'].lat.value' to create a line like this.
data: "&lat="+document.forms['newPostForm'].lat.value+"&lon="+document.forms['newPostForm'].lon.value,
Still would like an actual solution.
Here's some code from a project I'm working on. Very simple.
$.post("../postHandler.php", { post_action: "getRecentPosts", limit: "10" }, function(data){
$("#post-list").html(data);
You can switch out .post with .get with no other changes, like so:
$.get("../postHandler.php", { post_action: "getRecentPosts", limit: "10" }, function(data){
$("#post-list").html(data);
Data is passed in name value pairs like so.
{ post_action: "getRecentPosts", limit: "10" }
Rewrite:
$.get("mobile/nearby.php", { lat: location.coords.latitude, lon: loc.coords.longitude }, function(data2){
$("#nearbysgeo").html(data2);
});
$lat = preg_replace('#[^0-9\.]#', '', $_GET['lat']);
You probably can use location.coords.latitude if it is defined before.
jQuery.ajax(
{
url : 'mobile/nearby.php',
data : {
'action' : 'update',
'newname' : 'enteredText',
'oldname' : 'original_html',
'userid' : '10'
},
success : function(msg){
if(msg == 1)
{
alert('success');
}
}
});
this is the proper syntax of jQuery.Ajax(); function