AJAX

12K

Solutions

7K

Contributors

Asynchronous JavaScript and XML (AJAX) is a group of interrelated Web development techniques used on the client-side to create asynchronous Web applications. With AJAX, web applications can send data to and retrieve from a server asynchronously (in the background) without interfering with the display and behavior of the existing page. HTML and CSS can be used in combination to mark up and style information. The Document Object Model (DOM) is accessed with JavaScript to dynamically display and allow interaction with the information presented.

Share tech news, updates, or what's on your mind.

Sign up to Post

I'm working on a custom WordPress site that uses a BuddyBoss child theme that I've been heavily modiying over the past few months.

I'm currently working on a custom PHP template that's using JQuery's Colorbox plugin to load a PHP file in modal window via ajax.  The popup that contains the PHP file is being displayed without any issues .. and the native WordPress functions within it are working as expected. But the one BuddyPress method that I'm trying to use is not working .. namely "bp_is_my_profile()".  Here is my PHP code:

<?php 
require("../../../../../../wp-blog-header.php");
require('../../../../../../wp-load.php'); 

if ( is_user_logged_in() ) { // THIS METHOD IS WORKING

  if ( bp_is_my_profile() ) { // THIS METHOD IS NOT WORKING

		echo '<p>This is your Buddypress profile page.</p>';

  } else {
		echo '<p>This is NOT your Buddypress profile page.</p>';
  }  

}  else {  
		echo '<p>You are not authorized to access this resource.</p>';  
}
?>

Open in new window


What do I need to add to this PHP file in order for the "bp_is_my_profile()" method to work correctly?  I've already verified that this method DOES in fact work when I call it within a normal PHP template file that's part of my child theme.  I just can't seem to get it to work when calling it from any other PHP file .. despite the fact that I'm loading both the "wp-blog-header.php" & "wp-load.php" files.

Thanks,
- Yvan
0
Free Tool: SSL Checker
LVL 9
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Hello,
Im just trying to get to grips with using Modals and Bootstrap, can anyone look at :

http://dnx.org/eno/

And tell me why the button launches a modal, but the content is not replace with ajax content (from content.html )?


Thanks,
0
I have a web part page displaying 5 web parts. Four of the web parts (Efforts, Phases, Capture Points & Areas) are "provider" web parts, and come from lists that are the sources of 4 lookup columns in the 5th "consumer" web part (Lessons Learned).

The provider web parts are displaying the Title column from the lists.

The Using Javascript/jQuery, I "connected" the 4 provider web parts to the consumer web part, such that when you click on a Title column value, the consumer web part is filtered to show only those records that have the clicked value in the relevant metadata column.

All that is working very nicely.

Now, my requirement is to go one step further, and display the number of items that will be displayed if you click on a Title column value in any of the 4 web parts. If there are none, a "0" should be displayed.

I've constructed a lists service query that successfully returns the number of items that exist for a given, hard-coded, metadata value:
[SiteURL]/_vti_bin/listdata.svc/[ListName]/$count?&$filter=Effort/Title eq 'AAA'

So, the goal is to display such an item count beside the corresponding provider web part value, such as:
Efforts web part:
AAA (10) //assuming there are 10 items in the consumer web part tagged with Effort 'AAA'

Now, I'm bumping up against the current limit of my abilities.

I know that I need code (javascript, rest, ajax, json) for each provider web part with looping to cycle through all of the TD cells that have …
0
This function along with the PHP is sending the email.  What it is not doing is hiding the form and saying "Thanks"...so it is only half working!

The Function
<script>
$(function() {
  $("#myform").on('submit', function(e) {
    e.preventDefault();
    $.ajax({
      url: 'send_mail.php',
      dataType: 'json',
      data: $("#myform").serialize()
    }).done(function(d) {
      if (d.success==true) {
        $("#myform").hide();
        $("#results").text("Thanks!").show();
      }
    });
  });
});
</script>>

Open in new window


The PHP
<?php

$webmaster_email = "ds@mediascrubber.com";
$email_address = $_REQUEST['email_address'] ;

function isInjected($str) {
	$injections = array('(\n+)',
	'(\r+)',
	'(\t+)',
	'(%0A+)',
	'(%0D+)',
	'(%08+)',
	'(%09+)'
	);
	$inject = join('|', $injections);
	$inject = '/$inject/i';
	if(preg_match($inject,$str)) {
		return true;
	}
	else {
		return false;
	}
}

if (!isset($_REQUEST['email_address'])) {
header( "Location: $feedback_page" );
}

elseif ( isInjected($email_address) ) {
header( "Location: $error_page" );
}

else {
mail( "$webmaster_email", "Feedback Form Results", "From: $email_address" );
header('Content-Type: application/json');
echo json_encode($data);

}
?>

Open in new window

0
I am using ajax to output filtered list results on a page. Is it possible to go back to the previous filtered results? Please note I am not wanting to go back to the previous url using history.back()

What would be the best way to do this? Would I need to use URL parameters?
0
Im working with ajax toolkit tabs it is working properly but when i am adding bootstrap css files the tabs css  overwrite
Can u Help me to SOlve this problem?
Thanks in advance
0
Here I come again with this question on how to achieve dynamic content loading when user scroll to the bottom of the page. Currently, my code is loading all the content from the db at once using ajax, but I don't want to load everything at once. I want it to load just like twitter or facebook. Below is my code and what I've been trying to do.

HTML
<html>
<head>
<script>
function yHandler() {
    var wrap = document.getElementById('homeFeed');
    var contentHeight = wrap.offsetHeight;
    var yOffset = window.pageYOffset;
    var y = yOffset + window.innerHeight;
    if (y >= contentHeight) {
        // Ajax call to get more dynamic data goes here, how do I integrate the ajax call here? 
    }
}
window.onscroll = yHandler;

function feed() {
    var xhttp;
    if (window.XMLHttpRequest) {
        // code for modern browsers
        xhttp = new XMLHttpRequest();
    } else {
        // code for IE6, IE5
        xhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xhttp.onreadystatechange = function(response) {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("homeFeed").innerHTML = this.response;
        }
    };
    xhttp.open("GET", "functions/feedUpdate_New.php", true);
    xhttp.send(null);
}
feed();
</script>
</head>
<body>
<div id="homeFeed"></div>
</body>
</html>

Open in new window



PHP - feedUpdate_New.php

<?php
include_once(db_connect.php);
$sql = "SELECT message, audio, firstname, lastname FROM once WHERE username='myname'";
$query = mysqli_query($db_connect, $sql); 
    while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
                    $message = $row['message'];
                    $audio = $row['audio'];
                    $firstname = $row['firstname'];
                    $lastname = $row['lastname'];

echo '<div id="parentContainer">';
      echo $message.'<br />';
      echo $firstname.''.$lastname;
echo '</div>';
}
?>

Open in new window


I have more than 1000 lines returned from my database query back to the ajax call. But I want to use the
function yHandler()

Open in new window

to achieve the dynamic loading, but I'm not just getting how to integrate the ajax call inside my
function feed()

Open in new window

into the yHandler to get the dynamic loading working.
Do I need to add LIMIT into my sql statement? Or is there any other way to get this done?
0
I have a REST call using jQuery Ajax and it works fine on every browser except for IE11.  When I make this POST call,  I get back a 400 error and the data doesn't get written.

Any advise on this would be greatly appreciated.
0
in my partial view, I have used some jquery code for submitting my form.but I got this error.
The required anti-forgery form field"__RequestVerificationToken"
is not present. as you see I have added @Html.AntiForgeryToken() in my partial view and as well I have added [ValidateAntiForgeryToken] on my controller. but I got the error again.I have read all of the questions on the internet but they couldn't help me.

@model Dentistry.Areas.ViewModels.UserViewModel

<div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
        <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
    </button>
    <h4 class="modal-title custom_align" id="Heading">ویرایش کاربران</h4>

</div>

@if (Model != null && Model.UserId != string.Empty)
{
    <div class="modal-body" id="editModal">
        <form id="#myForm">
          @Html.AntiForgeryToken()
            <div class="form-group">
                @Html.HiddenFor(a => a.UserId)
            </div>
            <div class="form-group">
                <label>نام کاربری</label>
                @Html.TextBoxFor(a => a.UserName, new { @class = "form-control" })
                @Html.ValidationMessageFor(a => a.UserName)
            </div>
            <div class="form-group">
                <label>نام</label>
                @Html.TextBoxFor(a => a.FirstName, new { @class = "form-control" })
                @Html.ValidationMessageFor(a => a.FirstName)
          

Open in new window

0
Hi Experts,

I have a page which has a Ajax call to a search function, which is working fine with the search button, which calls it. When I added a function to capture the enter key to trigger the click attribute of the search button, now the the function is firing, pulls back the correct search records for a flash, but then the page completely reloads with the original value of the page. What I'm not understanding is how the default value of the page is loading, since it's not hitting the database call again. Any ideas?

Thanks,
Steve
0
On Demand Webinar - Networking for the Cloud Era
LVL 9
On Demand Webinar - Networking for the Cloud Era

This webinar discusses:
-Common barriers companies experience when moving to the cloud
-How SD-WAN changes the way we look at networks
-Best practices customers should employ moving forward with cloud migration
-What happens behind the scenes of SteelConnect’s one-click button

I have been messing around creating an Ajax application using OpenSUSE, MariaDB, php and Firefox.   I had most of it working but now i can not get it to process the returned xml from my php application  

I have walked through the code using firebug and when i get to  xmlHttp.onreadystatechange = handleStatus(lineID);   handleStatus is called but after xmlHttp.send(null);  I just execute the next line (just a filler to set a breakpoint) and then exit the function, handleStatus is not called so I don't process the xml.  

If I examine the xmlHttp object it shows xmlHttp.readyState is 4 and the xml returned from chInfo.php

I have checked the error logs and there are no issues with my PHP code.  It just does a read of a database table, builds the xml and returns it.  

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><response><subBox><name>sub4</name></subBox><lines><select><ID>24</ID><desc><line1<desc></select></lines><response>

Any ideas on what I have done wrong?
Ajax1.txt
0
Hi,
I am making a http patch request using an  ajax call on chrome to url - https://api.github.com/repos/owner...
My page url is localhost:8080.
This call is failing. In the network tab i see an option request being made in red.
I read some places that patch request that  is cross origin will be preflighted.
Which i think means that it will be first checked with github that patch is allowed in cross origin.
But github docs says its open to cross origin request.
How do i achieve my goal ?
Also please mention some good video or articles on cross origin / preflight etc.

Thanks
0
Hi,

I have a contact form with an XML that loads the contact information in the contact form. I am busy adjusting this. Instead of a dropdown, I want to build an ajax life search. Can someone help with that? I like to hear it

Thanks
test.xml
test3.php
0
I've actually been able to get this working on the editor in pages and posts using the code below. But haven't been able to get it to work for the new editor added to text widgets. I read that wordpress is using jQuery now for those text widgets, but even trying this without a hook, just adding the script sitewide to test doesn't work:

<script type="text/javascript">
jQuery( document ).on( 'tinymce-editor-setup', function( event, editor ) {
    if ( editor.settings.toolbar1 && -1 === editor.settings.toolbar1.indexOf( 'blockquote' ) ) {
        editor.settings.toolbar1 += ',blockquote';
    }
});
</script>

Open in new window


I tried that just to see if the new method wordpress says you can use to add more buttons would even affect the editor in the text widget, but it doesn't even add the blockquote icon as expected. So of course I can't poke around to try to figure out what would target the link option.

This is the code that does work for the editor in pages and posts:
<?php
function newtablink()
{
 ?>
<script type="text/javascript">
    jQuery(function () {
       jQuery('input#wp-link-target').prop('checked',true);
    });
</script>  
<?php
}

add_action( 'before_wp_tiny_mce', 'newtablink' );
?>

Open in new window


Anyone have any thoughts or suggestions on how to go about this for the widget? Below is a screenshot for a visual of where and what I'm trying to work with.
(If you wonder why we want to do this: we have some sites that have more external links than internal. So we want the people adding or editing content or widgets to be able to just enter the url without having to open in extra settings box. We don't want to add a plugin that automatically tries to auto add the target="_blank" as pages render because we want to still have individual control. Some of the people editing have very limited skills, so we want to try to simplify anything we can for some of the sites.)

Screenshot of the box that opens when adding a link in the editor.
0
I am using a jQuery tabs package (SolidTabs) to present several jQuery/BootStrap (BootGrid) Ajax forms on the same page. iframes are not an option. As its name implies, BootGrid displays a table of records, along with the ability to add a new record or edit an existing one, taking advantage of Ajax, using json and PHP.
I have not wanted to mess with the main js file. I'm thinking I should just be able to change the various HTML id's, and I should be fine. So far, that has not been successful.

My perhaps naive question is - other than using an iframe, is there some way of containing these separate grid forms so that I could use the same id assignments on the same page?
0
I am using code provided by Marco Gasi, and I made some modification to the php to give me 2 results. How can I post the two different results from the php file

<?php

$price = 7.99;

$qty = filter_input(INPUT_POST, "qty");

$total_price = 0;

$total_tax = 0;

if (isset($qty)){

      $shipping = $qty <= 4 ? 9.95 : 14.95;

      $total_price = ($price * $qty) + $shipping;

        $total_tax = $total_price * .0825;
}

echo $total_price;
echo $total_tax;

HTML :   (I want two separate results PRICE and TAX, and the way it is working right now is 1 string file with BOTH results)

<h3><font size="6">Total price is <span id="total-price">$ 15.98</span></font></h3>
                              <h3><font size="6">Taxes <span id="total-tax">$ 1.32</span></font></h3>
      </td>
<script src="https://code.jquery.com/jquery-3.0.0.min.js"  integrity="sha256-JmvOoLtYsmqlsWxa7mDSLMwa6dZ9rrIdtrrVYRnDRH0="  crossorigin="anonymous"></script>
            <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
            <script type="text/javascript">
                  $(document).ready(function () {
                                //reset quantity value when page reloads
                        $('#qty').val(2);
                                // intercept 'change' event for the quantity input
                        $('#qty').on('change', function () {
                                        // get the value of the quantity input
                              var qty = $(this).val();
                                        //perform an Ajax call…
0
I am trying to upload a file with my form submission using ajax but I keep getting and undefined index error for the "file" field.


$(document).ready(function() {
   $('form').submit(function(e) {
      e.preventDefault();
      var form = $("#form1").serialize();
      $(".alert").hide();
      $.ajax({
       url: 'functions/add-news-ajax.php',
       type: 'POST',
       dataType: 'json',
       data: form,
       beforeSend: function() {
        $("#btn-add").hide();
        $("#loader").show();
       },
      })

      .done(function(data) {
         if (!data.success) {
        // validation errors

Open in new window


This isn't the final upload script I will use. I just grabbed it off the net for testing. I have tried other scripts and I get exactly the same error:

 $fileName = time().'_'.basename($_FILES["file"]["name"]);
    
    //file upload path
    $targetDir = "../uploads/";
    $targetFilePath = $targetDir . $fileName;
    
    //allow certain file formats
    $fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
    $allowTypes = array('jpg','png','jpeg','gif');
    
    if(in_array($fileType, $allowTypes)){
        //upload file to server
        if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){
            //insert file data into the database if needed
            //........
            $response['message'] = 'ok';
        }else{
            $response['message'] = 'err';
        }
    }else{
        $response['message'] = 'type_err';
    }

Open in new window


My file field:

<div class="form-group">
	<label for="usr">Image to upload:</label>
	<input id="uploadImage" type="file" name="file">
</div>

Open in new window


The form:

<form id="form1" method="post" enctype="multipart/form-data">

Open in new window

0
Hello,

I have piece of code here. I am trying to create something like a quiz application. In  <h4>Add question</h4> part, I can add a question if I want to and I store all the details I entered into the database by making an ajax call. Upon success, this piece of code gets replaced by the same code with other data so that the user can enter all the details. What I am trying to do is once I add a question in 'Add question' part, then I should be able to display it throughout the quiz. How can I do a post for new_questions in ajax and send it to the controller?

Can anyone suggest me how to do proceed with this?

Any kind of suggestion would be helpful.
   
<?php
foreach($substeps as $row) {
 ?>
 <div id='img_div'>
      <h2 id="stepslist_<?php echo $row->stepid;?>" class="step"><p><?php echo $row->stepname;?></p></h2>
      <img src='http://localhost/project/uploads/<?php echo $row->image; ?>'>
</div>
<?php } ?>
 <?php
      foreach($questions as $each){
      ?><br><br>
      <input type="text" name="questions[]" class='form-control' id="questions_<?php echo $each->questionid; ?>"  value="<?php echo $each->questionname; ?>" disabled/><br/>
   
    <h4>Add question</h4>
    <input type="text" class="form-control" name="newquestion[]"  id="new_questions_<?php echo $each->questionid; ?>" /><br>
    <h4>Answer:</h4>  <select class="form-control" name="answer[]" id="answer" required>
 <option value="">Select</option>
 <option value="no">no</option>
 <option 

Open in new window

0
What am I doing wrongly in these code? I want to update user password without refreshing the page, but this is not working as my code stops at  
_("pmessage").innerHTML = 'please wait ...';

Open in new window

on the jquery/ajax code. The Ajax seems not to be firing as my DB is not updated with the new password. Below are my codes:

HTML
<form id='pform' method='post'>
<div id='entercurrent'>Enter Current Password:</div>
<input id='current' name='current' type='password'>
<div id='enternew'>Enter New Password:</div>
<input id='newpwd' name='newpwd' type='password'>
<div id='enterconfirm'>Confirm New Password:</div>
<input id='confirmpwd' name='confirmpwd' type='password'>
<input id='passsubmit' type='submit' value='Update Password'>
</form>
<div id='pmessage'></div>

Open in new window


Ajax
$(document).ready(function() {
    $("#passsubmit").click(function(event) {
        event.preventDefault();
        var cp = $("#current").val();
        var np = $("#newpwd").val();
        var cf = $("#confirmpwd").val();
        dataString = "cp=" + cp + "&np=" + np + "&cf=" + cf;
        _("passsubmit").style.display = "none";
        _("pmessage").innerHTML = 'please wait ...';

        $.ajax({
            type: "POST",
            url: "functions/changePwd.php",
            data: dataString,
            success: function() {}
        });
    });
});

Open in new window


PHP -  functions/changePwd.php
if(isset($_POST['cp'])) {
    $currentpwd = $_POST['cp'];
    $newpwd = password_hash($_POST['np'], PASSWORD_DEFAULT);
    $confirmnewpwd = password_hash($_POST['cf'], PASSWORD_DEFAULT);
}
$sql = "UPDATE users SET password='$newpwd' WHERE username='$log_username'";
$query = mysqli_query($db_connect, $sql);

Open in new window

0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE
LVL 4
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

I am displaying records from the database like this:

$(document).ready(function(){
			$.ajax({
				url: 'functions/list-articles-delete.php',
				dataType: 'json',
				method: 'POST',
				success: function(data) {
				 $.each(data, function(item){
					var tr_str = "<tr>"
					+ "<td>" + data[item].n_title + "</td>"
					+ "<td>" + data[item].n_dateTime + "</td>"
					+ "<td><button class='btn btn-danger' id='deletebut' data-id='" + data[item].id + "'>Delete</button></td>";
					 $( "#output" ).append(tr_str);
						
					 $( "#deletebut" ).on('click', function(){
						// display id of associated record
				}); 
			});			
		},
	});
});

Open in new window


When I click on any of the buttons I want it to console.log() the id of the associated record but not quite sure how to do this?
0
I'm trying to reload ajax data on click event which pops up a modal

implementationlog is a global variable as well as impviewlogjobid

any help much appreciated

$('#implementationLogModal').on('shown.bs.modal', function (e) {

            report = 8;
            var logparam = "{'report':'" + report + "','jobid':'" + impviewlogjobid + "'}";
            var logparameters = JSON.stringify(logparam);

            if ($('#implementationLogTable th:contains(Log)').length == 0) {
                var header = '<thead id="implementationLogTable-Header"><tr><th class="text-center">Log</th><th>Log Date</th></tr></thead>';
                var footer = '<tfoot id="implementationLogTable-Footer"><tr><th class="text-center">Log</th><th>Log Date</th></tr></tfoot>';
                $("#implementationLogTable").append(header);
                $("#implementationLogTable").append(footer);

                implementationLog = $("#implementationLogTable").DataTable({
                    dom: 'lfrtip',
                    oSearch: { "bRegex": false, "bSmart": true },
                    deferRender: true,
                    bFilter: true,
                    bSearchable: true,
                    processing: false,
                    bRetrieve: true,
                    bSortable: true,
                    lengthMenu: [[10], [10]],
                    stripeClasses: [],
                    destory: true,
                    ajax: {
                        "url": 

Open in new window

0
Hi experts I am using a small script (posted below) to get the location for my web form. I am able to display the location. I want to turn that location into a php variable to use in a text input somewhere else on my web form. Any suggestion on how I should do this? I  tried to use $_GET but I may have done it wrong.
Script:
<script>

$.get("https://ipinfo.io/json", function (response) {
   
   $location=$("#address").html("Location: " + response.city + ", " + response.region);
    //$("#details").html(JSON.stringify(response, null, 4));
}, "jsonp");
</script>

Open in new window

Area in html I am trying to put the script result into
Address:<input type="text" name="Address"   style="width: 150PX;" value="(location here)">

Open in new window


Thankyou for any feedback
0
I had this question after viewing how to get id from url using php and Jquery.

This is the php:

$url = filter_var($_GET['id'], FILTER_SANITIZE_URL);
$stmt = $link->prepare("SELECT `n_title`, `n_dateTime`, `n_article` FROM `news` WHERE `id` = ?");
$stmt->bind_param("i", $url);

if (!$stmt->execute()) echo "Execute Error: ($stmt->errno)  $stmt->error";
$result = $stmt->get_result();

if ($result) {
	$row = $result->fetch_assoc();
	$n_title = sanitize($row['n_title']);
	$n_dateTime = sanitize(row['n_dateTime']);
   $n_article = sanitize($row['n_article]);
	
	$news_detail[] = array(
	
		"n_title" =>$n_title,
		"n_dateTime" => $n_dateTime,
           "n_article" =>$n_article
	
	);
	
} else {
	
	echo "No record found";
}

$stmt->close();
echo json_encode($news_detail);

Open in new window


This is the jQuery/Ajax:

myApp.onPageInit('article', function (page) {
   var id = page.query.id;
   $$.ajax({
	   url: "news-detail.php",
	   type:"GET",
           data: {id: id}, 
	   success: function(data) {
		console.log(data);
		 
	   },
   });
});

Open in new window


Perhaps I want to show the title at the top of the page and the date at the bottom of the page. Do I need to put everything into divs?

So, at the top of the page I would have <div id="news-headline"></div> and at the bottom of the page I might have <div id="article-date"></div>.

Is that the correct way to do it? And if so, how would I get the values into those divs? When using a while loop for lost of records I used:

$$.each(data, function(item) {

Open in new window


but since I am not looping through records, and only getting one row, I am not entirely sure how to get that data.
0
I want to store 1 when checkbox is checked and 0 when not checked. But my code is only able to store 1 in my database, even though my function returned both 'true' and 'false' appropriately, my database only shows 1 for both checked and unchecked. Below is my code:

Jquery/Ajax

function checkCheckboxState() {
    if ($('input[id*="mobile"]').prop('checked') == true) {
        // execute AJAX request here
        $.ajax({
            type: 'POST',
            url: 'functions/mobilecheck.php',
            data: { 'checked': true },
        });

    } else {
        $.ajax({
            type: 'POST',
            url: 'functions/mobilecheck.php',
            data: { 'checked': false },
        });
    }
}

Open in new window


PHP
<?php
if(true){
    $sql = "UPDATE useroptions SET mobilecheck='1' WHERE username='$log_username'";
    $query = mysqli_query($db_connect, $sql);
} else {
    $sql = "UPDATE useroptions SET mobilecheck='0' WHERE username='$log_username'";
    $query = mysqli_query($db_connect, $sql);
}

?>

Open in new window

0
I am using ajax and jQuery to to query the database and display records from the database. I am then appending the results. The trouble I am having is that when the user taps (this is a mobile app) the article they want to view, it should take them to the details of that particular article. In order to do that I need to send the ID of that article to the detail page.

This is the jQuery  (I am using Framework7 which uses $$ instead of $). This lists the articles.

function newsFeed() {
	$$.ajax({
		url: "newsfeed.php",
		type: "POST",
		dataType: "json",
		success: function (data) {
			$$.each(data, function (item) {
				$$("#newsFeed").append(`

					<li>
						<a href="article.html?$id={data[item].id}" class="item-link item-content">
							<div class="item-media"><img src="img/${data[item].n_pic}" width="80"></div>
								<div class="item-inner">
								<div class="item-title-row">
									<div class="item-title news-headline">${data[item].n_title}</div>
								</div>
							<div class="item-text"></div>
									<div class="date-time">${data[item].n_dateTime}</div>
							</div>
						</a>
					</li>	
				`);
			});
		},
	});
}

Open in new window


I want to GET that id that is being sent in PHP:

$url = filter_var($_GET['id'], FILTER_SANITIZE_URL);
$stmt = $link->prepare("SELECT `n_title` FROM `news` WHERE `id` = ?");
$stmt->bind_param("i", $url);

if (!$stmt->execute()) echo "Execute Error: ($stmt->errno)  $stmt->error";
$result = $stmt->get_result();

if ($result) {
        $row = $result->fetch_assoc();
	$n_title = sanitize($row['n_title']);
	echo $n_title;
	
} else {
	
	echo "No record found";
}

$stmt->close();

Open in new window


This is the jQuery that is trying to get the results:

myApp.onPageInit('article', function (page) {
   $$.ajax({
	   url: "news-detail.php",
	   type:"POST",
	   success: function(data) {
		   console.log(data);
	   }
	   
   })
});

Open in new window


The error I get is:

Undefined index: id

So, I guess that php is not able to get the id being passed in the jQuery.
0

AJAX

12K

Solutions

7K

Contributors

Asynchronous JavaScript and XML (AJAX) is a group of interrelated Web development techniques used on the client-side to create asynchronous Web applications. With AJAX, web applications can send data to and retrieve from a server asynchronously (in the background) without interfering with the display and behavior of the existing page. HTML and CSS can be used in combination to mark up and style information. The Document Object Model (DOM) is accessed with JavaScript to dynamically display and allow interaction with the information presented.