• 0

Jquery ajax


Question

hi can some one explain to me what is going on with this code please

index.php

<!DOCTYPE html>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script>
var data = 'something-here';
$.ajax({
type: 'POST',
url: 'post.php',
data: data
});
</script>[/CODE]

post.php

[CODE]<?php
ob_start();
var_dump($_POST);
$data = ob_get_clean();
$fp = fopen("textfile.txt", "w");
fwrite($fp, $data);
fclose($fp);
?>[/CODE]

textfile.txt

[CODE]array(0) {
}[/CODE]

why is the $_POST variable empty? and how would i post 2 variables like $_POST['firstname'] and $_POST['lastname']

Link to comment
https://www.neowin.net/forum/topic/1120320-jquery-ajax/
Share on other sites

4 answers to this question

Recommended Posts

  • 0

The jQuery ajax method expects 'data' to be an object, rather than a string.

You should change this line:


var data = 'something-here';
[/CODE]

to this:

[CODE]
var data = { 'firstname': 'John', 'lastname': 'Smith' };
[/CODE]

Thanks been looking for this answer for long time i'm still learning how would i replace "John" with a variable

[CODE]var firstname = 'john';[/CODE]

Link to comment
https://www.neowin.net/forum/topic/1120320-jquery-ajax/#findComment-595329842
Share on other sites

  • 0

ok some more details here is the full script


<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<style>
#tripmeter {
border: 3px double black;
padding: 10px;
margin: 10px 0;
}

p {
color: #222;
font: 14px Arial;
}

span {
color: #00C;
}
</style>
</head>
<body>
<div id="tripmeter">
<p>
Starting Location (lat, lon):<br/>
<span id="startLat">???</span>°, <span id="startLon">???</span>°
</p>
<p>
Current Location (lat, lon):<br/>
<span id="currentLat">???</span>°, <span id="currentLon">???</span>°
</p>

</div>
<script>
window.onload = function() {
var startPos;

if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
startPos = position;
document.getElementById("startLat").innerHTML = startPos.coords.latitude;
document.getElementById("startLon").innerHTML = startPos.coords.longitude;
}, function(error) {
alert("Error occurred. Error code: " + error.code);
// error.code can be:
// 0: unknown error
// 1: permission denied
// 2: position unavailable (error response from locaton provider)
// 3: timed out
});

navigator.geolocation.watchPosition(function(position) {
document.getElementById("currentLat").innerHTML = position.coords.latitude;
document.getElementById("currentLon").innerHTML = position.coords.longitude;

});
}
};

</script>
<script>


$.ajax({
type: 'POST',
url: 'post.php',
data: data
});

</script>
</body>
</html>
[/CODE]

What i'm trying to do is log the current location every 20 seconds and pass it to post.php so it can insert it into a mysql database

Link to comment
https://www.neowin.net/forum/topic/1120320-jquery-ajax/#findComment-595329920
Share on other sites

  • 0

Sounds like an interesting project.

Answering your first question, you can just replace the string with the name of the variable and it will work in exactly the same way:


var firstname = 'john';
var data = { 'firstname': firstname, 'lastname': 'Smith' };
[/CODE]

If you want to perform an action at a particular interval, take a look at the window.setInterval method. It would look something like this (the interval is in milliseconds):

[CODE]
window.setInterval(function() {
// Get position here
// Save position here
}, 20000);
[/CODE]

  • Like 1
Link to comment
https://www.neowin.net/forum/topic/1120320-jquery-ajax/#findComment-595332454
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • What I like about Paint is using it almost exclusively for cropping and resizing images I get elsewhere--it's quick, easy and cheap... I keep it glued to my taskbar, in fact. Also, the clipping tool comes in handy, as well (hit print scrn on the keyboard and it activates immediately.)
    • I still remember it fondly today. It was so cool to work in 64-color Half Bright mode and 4.096-color HAM mode (interlaced) when x86 was still in 4-color CGA or 16-color EGA low res. C= never realized what it had until it was far too late--the failure of C= was the failure of its top management. The C= Amiga was 20 years ahead of its time, I always thought. It didn't hurt that in only 512k of chip memory, the Amiga could preemptively multitask when Apple was still doing gray scale graphics on tiny screens and along with everyone else was doing cooperative multitasking (running more than one app at a time in resident memory, but you could only run one of them at a time--had to manually switch between them.) I had a ball with AREXX scripting running between programs that had AREXX ports so that when you sent other applications data and instructions, those running applications could process the same in real time to output! Memories...
    • I'm not sure about that, but it at least "does" a version of 7.1 that this brand new card doesn't....
    • Floorp 12.15.2 by Razvan Serea Floorp is a cutting-edge web browser that combines the trusted foundation of Mozilla's Firefox with a unique Japanese perspective, offering users an exceptional online experience. This open-source browser prioritizes privacy, customization, and security. Floorp is transparent, with no user tracking or data sharing, and it's completely open source. With a strict no-tracking policy and full transparency, your personal information remains private. As an open-source project, Floorp not only shares its source code but also its build environment, inviting users to contribute and build their unique versions. The regular updates, based on Firefox ESR, ensure that you always have the latest features and security enhancements. Floorp key features: Strong Tracking Protection: Floorp offers robust tracking protection, safeguarding users from malicious tracking and fingerprinting on the web. Flexible Layout: Customize Floorp's layout to your heart's content, including moving the tab bar, hiding the title bar, and more for a personalized browsing experience. Switchable Design: Choose from five distinct designs for the Floorp interface, and even switch between OS-specific designs for a unique look Regular Updates: Based on Firefox ESR, Floorp receives updates every four weeks, ensuring up-to-date security even before Firefox's releases. No User Tracking: Floorp prioritizes user privacy by abstaining from collecting personal information, tracking users, or selling user data, with no affiliations with advertising companies. Completely Open Source: The full source code for Floorp is open to the public, allowing transparency and enabling anyone to explore and build their own version. Dual Sidebar: Floorp features a versatile built-in sidebar for webpanels and browsing tools, making it perfect for multitasking and quick access to bookmarks, history, and websites. Flexible Toolbar & Tab Bar: Customize your browser with Tree Style Tabs, vertical tabs, and bookmark bar modifications, catering to both beginners and experts in customization. User-Centric Web Experience: Floorp prioritizes user privacy and collaboratively blocks harmful trackers. Floorp 12.15.2 changelog: fix: reset tab drag state on dragend to prevent position offset (#2488) by @Ryosuke-Asano in #2497 fix(workspaces): hide split view wrapper when all tabs are hidden by @Ryosuke-Asano in #2495 fix(split-view): prevent stuck pointer-events:none after drag on web content by @Ryosuke-Asano in #2492 feat(design): add Gecko 152 CSS variable aliases and Lepton compatibility layer by @Ryosuke-Asano in #2494 fix(workspaces): exitOnLastTabClose no longer quits Floorp when closing the last tab by @Ryosuke-Asano in #2498 Download: Floorp 64-bit | 95.0 MB (Open Source) Links: Floorp Website | Github Website | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • I can barely recall getting web results from a file search... I must've turned it off long ago. 26H2 is Insider's Preview build 26300.8697, which I am running, atm. It is not available for people running the standard commercial builds of Windows--only for the beta test Insider's group. But anyway, as mentioned in the thread, this feature has been around for a long time...
  • Recent Achievements

    • Dedicated
      Almohandis earned a badge
      Dedicated
    • Dedicated
      JuvenileDelinquent earned a badge
      Dedicated
    • First Post
      DrWankel earned a badge
      First Post
    • Reacting Well
      DrWankel earned a badge
      Reacting Well
    • Week One Done
      Supreme Spray LV earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      507
    2. 2
      +Edouard
      185
    3. 3
      PsYcHoKiLLa
      84
    4. 4
      Michael Scrip
      78
    5. 5
      Steven P.
      76
  • Tell a friend

    Love Neowin? Tell a friend!