[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x

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

Hi Guys,
I am using asp.net mvc.
I built a method in  the backend that let me stream file and download to my dom:
Here is my backend method.

Public Function DownloadFiles(attachmentsSelected As String, zipFileName As String) As FilePathResult
        Dim obj As FileDownloads = New FileDownloads()
        ''get file list user choose to download
        Dim filesCol = obj.GetFile(attachmentsSelected).ToList()

        Dim fileSavePath As String = IO.Path.Combine(System.Web.Hosting.HostingEnvironment.MapPath("~/DownLoadAttachments"), zipFileName)
        Using stream = New FileStream(fileSavePath, FileMode.Create)
            Using ziparchive = New ZipArchive(stream, ZipArchiveMode.Create, True)

                For i As Integer = 0 To filesCol.Count - 1
                    'ziparchive.CreateEntryFromFile(filesCol(i).FilePath + "\" + filesCol(i).FileName, filesCol(i).FileName, CompressionLevel.Optimal)
                    ziparchive.CreateEntryFromFile(filesCol(i).FilePath, filesCol(i).FileName, CompressionLevel.Optimal)
                Next
            End Using
        End Using

        Return File(fileSavePath, "application/zip", "Attachments.zip")
    End Function

Open in new window


Now from the front end I do something like that.

 window.location = "/DocumentViewer/DownloadFiles?attachmentsSelected=" + func.downloadFilesList + "&zipFileName=" + uuid;

Open in new window


The issue I have with this approach is - I want to delete the file from my server after the client download it so I need another call to the server ..let's say with ajax and delete, but the problem is I can't predict the time when this URL finish the process of downloading in the backend

Does anyone have an idea how to do it? I was trying Promise but it doesn't really work in this scenario.

Thank you.,
0
Exploring SharePoint 2016
LVL 12
Exploring SharePoint 2016

Explore SharePoint 2016, the web-based, collaborative platform that integrates with Microsoft Office to provide intranets, secure document management, and collaboration so you can develop your online and offline capabilities.

Modal is not working after 1st page when click on "Change" button  in datatable bootstrap:



View Info Modal :
<div id="dataModal" class="modal fade">  
      <div class="modal-dialog">  
           <div class="modal-content">  
                <div class="modal-header">  
                     <button type="button" class="close" data-dismiss="modal">&times;</button>  
                     <h4 class="modal-title">Customer Details</h4>  
                </div>  
                <div class="modal-body" id="customer_detail">  
                </div>  
                <div class="modal-footer">  
                     <button type="button" class="btn btn-gradient-light btn-fw" data-dismiss="modal">Close</button>  
                </div>  
           </div>  
      </div>  
 </div>

Open in new window


Change Info Modal:
 <div id="changeModal" class="modal fade">  
      <div class="modal-dialog">  
           <div class="modal-content">  
                <div class="modal-header">  
                     <button type="button" class="close" data-dismiss="modal">&times;</button>  
                     <h4 class="modal-title">Change Status</h4>  
                </div>  
                <div class="modal-body" id="change_detail">  
                </div>  
                <div class="modal-footer">  
                     <button type="button" class="btn btn-gradient-light btn-fw" data-dismiss="modal">Close</button>  
                </div>  
           </div>  
      </div>  
 </div> 

Open in new window


JQuery :
 $(document).ready(function(){  
      $('.view_data').click(function(){  
           var book_id = $(this).attr("id");  
           /*alert(employee_id);*/
           $.ajax({  
                url:"ajax/viewCustomer.php",  
                method:"post",  
                data:{book_id:book_id},  
                success:function(data){ 
                     $('#customer_detail').html(data);  
                     $('#dataModal').modal("show");  
                }  
           });  
      });  
 });
  $(document).ready(function(){  
      $('.change_data').click(function(){  
           var book_id = $(this).attr("id");
           $.ajax({  
                url:"ajax/updateServiceStatus.php",  
                method:"post",  
                data:{book_id:book_id},  
                success:function(data){ 
                     $('#change_detail').html(data);  
                     $('#changeModal').modal("show");  
                }  
           });  
      });  
 });

Open in new window

1
I have jQuery/Javascript on my page at:
http://www.domain-a.com/page.html

...and I am trying to do a jQuery $.post to:
https://www.domain-b.com/script.asp

But I get this error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at...

On www.domain-b.com I have the following in web.config (this is an IIS server):

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <httpProtocol>
            <customHeaders>
                <add name="Access-Control-Allow-Origin" value="*" />
            </customHeaders>
        </httpProtocol>
    </system.webServer>
</configuration>

Open in new window


...however, I still get the error. I don't have access to .htaccess or anything else on www.domain-a.com. Is it possible for me to resolve this issue, or is it not possible because I don't have access to the www.domain-a.com server? It isn't clear to me if I need to add Access Control to the server where the web page resides, or the server where the target script resides.

Thank you.
0
Here is a simple CSRF class I am using:

<?php
 
namespace Core;
 

/**
 * CSRF protection
 */
class CSRF
{
    /** 
     * Get and store a new CSRF token
     *
     * @return string  A 32-character token
     */
    public static function getToken()
    {   
        $token = new \App\Token();
        $value = $token->getValue();
        $_SESSION["csrf_token"] = $value;
 
        return $value;
    }
 
    /** 
     * Check the token value
     */
    public static function checkToken()
    {   
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            if ( ! isset($_POST['csrf_token'])) {
               header('HTTP/1.0 403 Forbidden');
               exit('Missing CSRF token');

            }
 
            // Get the token from the session and remove it
            $token = $_SESSION['csrf_token'] ?? '';
            unset($_SESSION['csrf_token']);
 
            if ($_POST['csrf_token'] != $token) {
                header('HTTP/1.0 403 Forbidden');
                exit('Invalid CSRF token');

            }   
        }   
    }   
}

Open in new window


Then I have the token in a hidden form field:

<input type="hidden" name="csrf_token" value="<?php echo $csrf_token; ?>">

Open in new window


This is my controller:

 
   public function createAction()
    {
        if($_SERVER['REQUEST_METHOD'] === 'POST') {
            
            $response = [];
            
            $customer = new Customer();
            if($customer->save($_POST)) {
                
                $response['success'] = true;
                $response['message'] = 'Customer successfully added';
                
             } else {
                
                $response['success'] = false;
                $response['message'] = $customer->errors;
            }
            
            echo json_encode($response);
        }
    }

Open in new window


If I wasn't using Ajax and I just called that method in the controller like:

CSRF::checkToken();

Open in new window


then it works fine and the 403 occurs. But since I am using Ajax, the page just hangs and the error shows up in console. So, I click submit and the form validation takes place. If there are errors then I use jQuery /json to show the errors:

        .done(function (data) {
            if (!data.success) {

                unblockUI();
                $.each(data.message, function(index, item) {
                    $( '.alert-danger' ).append(item + "<br>").fadeIn();
                });

Open in new window


Is it possible to make the 403 happen or would I need to do something else? It is no good as is that the page just freezes up and the 403 error is shown in console. In theory, genuine users should never have this happen, but I still want to handle it more elegantly anyway.
0
Hi Guys,
I have implemented progress bar with js and html progress tag.

Here is my sample implementation

<progress id="progressBar" value="0" max="100" style="width:300px; height: 40px;"></progress>
    <span id='status'></span>

  function Progressbarsx(perc) {
      var bar = document.getElementById('progressBar');
      var status = document.getElementById('status');
      status.innerHTML = perc + "%";
      bar.value = perc;
      perc++;
      var sim = setTimeout("Progressbarsx("+ perc +")", 100);
      if(perc == 100){
          status.innerHTML = 100;
          clearTimeout(sim);
      }
    }
    var amountrun = 0
    Progressbarsx(amountrun)

Open in new window

:

That is working fine.
Now I have a scenario in my production environment when I run a lot of ajax call for returning data from server.

I used to using spinning bar that spin until ajax function finish, but now I want to show progress bar and calculate the time until the return come back. exactly like I show in my example.
Now I want to do something like that:

 $(document).ajaxStart(function (val) {
        //call to my progress bar in a real time 
    }).ajaxStop(function (val) {
        //end the call after ajax stop.
    });

Open in new window


Please, let me know what is the idea of doing something like that.

Thank you.
0
Hello Experts!

Please, help. I don't know why this code is not opening modal to a specific record. It only opens the first record on the list. The second link shows the first record when clicked. If I refresh the page and click on the second link first, it shows nothing.

I already tested the id for each list, that is fine.

the message.php
<?php while ($message = $result->fetch_object()): 
  $timestamp = $message->msg_date;
  $date = new DateTime($timestamp);
  $date_posted = $date->format('d M Y h:i A');
?>
                                
<div class="content" id="noticeMessage">
  <a class="content-title" href="#"><?= $message->title; ?></a>
  <p class="content-date"><?= $message->category; ?> | <?= $date_posted; ?></p>
  <p class="content-body"><?= $message->description; ?></p>
  <a class="light-green feed-link learnMore" href="#" data-toggle="modal" data-target="#noticeModal" data-id='<?= $message->msg_id; ?>'>Learn more</a>
</div>
<?php endwhile; ?>

Open in new window

modal dialog:
<div class="modal fade" id="noticeModal" tabindex="-1" role="dialog" aria-labelledby="noticeModalTitle" aria-hidden="true">
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h3 class="modal-title" id="noticeModalTitle">Message Content</h3>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <div id="getNoticeContentDiv"></div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

Open in new window

the modal gets data from: notice_modalForm.php:
<?php
require_once '../.../connect.php';

$query = $conn->prepare("SELECT * FROM tbl_message WHERE msg_id = ?");
$query->bind_param("i", $_POST['id']);
$query->execute();
$result = $query->get_result();
$message = $result->fetch_object();

?>

<div class="content">
	<a class="content-title"><?= $message->title; ?></a>
	<p class="content-date"><?= $message->category; ?> | <?= $message->msg_date; ?></p>
	<p class="content-body"><?= $message->description; ?></p>
	<p class="content-body"><?= $message->details; ?></p>
</div>

Open in new window

using this code:
$('#noticeMessage').on('click', '.learnMore', function(e) {
            e.preventDefault();
            $.ajax({
                url     : 'views/notice_modalForm',
                method  : 'post',
                data    : { id : $(this).data('id') }
                })
                .done(function(data) {
                    $('#getNoticeContentDiv').html(data);
                    $('#noticeModal').modal('show');
                });
            });   
            
        });

Open in new window

Thank you for your help
0
Screen-Shot-2018-10-29-at-11.10.05.png

              $(document).on('click', '#action-unSub', function(){
        $.ajax({
            url: "unsubscribe-manual.php",
            type: "POST",
            data: { email:<?=$v_item['CONTACT_EMAIL'];?> },
            success: function(html){
            
             
            },
            error: function(html){
               
            }
        });
    });

Open in new window


what is the issue ?
0
I am using Ajax to request the data. I am making an array and send it with json_encode so that I will receive the data in my Ajax Success function.
Now, here is my code:

$sql = "SELECT * FROM  mydata where id=15";		
			$rst = mysqli_query($conn,$sql) or die(mysqli_error($conn));					
			if (mysqli_num_rows($rst) > 0)
			{				
				while( $proj_gall_img = mysqli_fetch_array($rst) )
				{							
					$project_gallery_images[] = $proj_gall_img['img_name'];
					//$project_gallery_images.= $proj_gall_img['img_name']."|";
				}
				
			}
			
$projects_name[] = '<span data-id="' . $projects_row['id'].'" data-title="' . $projects_row['project_title'].'" data-detail="' . $projects_row['project_detail'].'" data-mimage="' . $projects_row['project_image'].'" data-mgallery="' . @$project_gallery_images.'"  class="li-txt" style="color:#ff0000;"><a id="myAnc" href="#">'.$projects_row['project_title'].'</a></span>';

Open in new window


The Problem:
I am easily fetched the value of following data attributes, data-id, data-title, data-detail, data-mimage but I am unable to get the value of data-mgallery in my ajax success function because this is an array.

In my this function I need to fetch this data:
jQuery('body').on('click', 'span.li-txt, span.li-txt2', function() {

var pid = jQuery(this).data('id');
var title = jQuery(this).data('title');
var detail = jQuery(this).data('detail');
var mimage = jQuery(this).data('mimage');	

var gallery = jQuery(this).data('mgallery');	
alert('length='+gallery.length);

Open in new window

The value of pid, title, detail and mimage retrieve successfully, but the value of gallery is Array. How to retrieve it?

Alternatively, how can I fetch the data in Ajax Success method?

Need help in this regard.

Thanks
0
I am calling a WEB API method with parameters from Jquery.
When i run in debug mode on the WEB API side, the parameter always appears null.

On the client side, when the value in the dropdown changes, i call the WEB API method. I have an alert there and i can see the proper value.

Why is the parameter showing up as null on the WEB API side?

My Web API code:
  [EnableCors(origins: "*", headers: "*", methods: "*", SupportsCredentials = true)]
        [Route("api/Services/GetAllServiceItemsForSelectedProgram")]
        [HttpPost]
        public IEnumerable<ServiceItems> GetAllServiceItemsForSelectedProgram(List<LoginParameters> loginParam)
        {
            
            List<ServiceItems> retSvcItem = new List<ServiceItems>();
            object cidString = null;
            //
         }

Open in new window


Jquery Ajax call:
function GetSvcItemsForSelectedProgram(selectProgID) {
            
            alert(selectProgID.value); // value coming good here
            $.ajax({
                type: 'POST',
                url: '/api/Services/GetAllServiceItemsForSelectedProgram',
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify({ UserName: 'jeri', CompanyID: 'Shah' , ServiceProgramID : selectProgID.value }),
                success: function (data) {
                    $.each(data, function (i, item) {
                        $('#ddSvcProg').append('<option value="' + item.ServiceProgramID + '">' + item.ServiceProgram + '</option>');
                    });
                },
                failure: function (data) {
                },
                error: function (data) {
                }
            });
        }

Open in new window


Internet explorer - developer tools:
I can see the parameters that i sent and the response is 200.

Thanks in Advance
0
I need to get information from a XML file where this file is auto upload every 30 seconds.
I want to show this information in a website.

Just to show an example, my website is a radio, and I want to show to users what music he listen.
0
Exploring SQL Server 2016: Fundamentals
LVL 12
Exploring SQL Server 2016: Fundamentals

Learn the fundamentals of Microsoft SQL Server, a relational database management system that stores and retrieves data when requested by other software applications.

I have the code below. I am trying to update the table when an attachment is being add and/or deleted.  The table is in a partial view.  The issue is that my model.Attachments is not being updated when I go to submit the entire request.  The table displays the row but the model isn't being updated with the new data.  What am I doing wrong?

<div class="form-group row">
                <div class="col-sm-6">
                    @Html.EditorFor(model => model.AttachmentsJSON, new { htmlAttributes = new { @class = "form-control" } })
                    <table class="table" id="ListofFiles">
                        <thead>
                            <tr>
                                <th>Filename</th>
                                <th>Attachment Type</th>
                                <th>Description</th>
                            </tr>
                        </thead>
                        <tbody>
                            @if (Model.Attachments.Count() != 0)
                            {
                                var idCount = 0;

                                foreach (var item in Model.Attachments)
                                {
                                    idCount = idCount + 1;
                                    <tr id="@idCount">
                                        <td>@item.Filename</td>
                                        <td>@item.AttachmentType.Type</td>
                                        <td>@item.Description</td>

Open in new window

0
Hello Experts!

I want to make certain inputs read-only when NOW() is greater than $LimitDate.

I use the following to populate the DataTable:

{
    orderable: false,
    render: function (data, type, row) {
    return '<input class="form-control form-control-sm" type="text" maxlength="2" size="6" name="cass1[' + row.Enroll_ID + ']" value="' + row.CA1 + '">';
    }
},
{
    orderable: false,
    render: function (data, type, row) {
    return '<input class="form-control form-control-sm" type="text" maxlength="2" size="6" name="cass2[' + row.Enroll_ID + ']" value="' + row.CA2 + '">';
    }
}

Open in new window

The $LimitDate holds the date when the input periods expire.

How can I manipulate the two inputs above so the change to READ-ONLY when NOW() is greater than $LimitDate?

Thank you.
0
Hi,

I've a form to send a ajax request which return a json object from a cURL request. I use the form to query the API using the start and and the end date. I've managed to show the datas returned into a table as suggested in this post https://www.experts-exchange.com/questions/29120674/Convert-json-to-html-table.html
Now my problem is every time a make a new request from my form a new table is shown to the form page just after the table I've obtained with the previous request, is there any way to show only one table, so at every form request the previus data is replaced with the new data?

This is my javascript code:
    $(document).ready(function() {

      // Function to create table layout
      function createTable(data) {
        var table = document.createElement('table');
        var header = table.insertRow();

        for(var h in data[0]) {
          var th = document.createElement('th');
          th.innerHTML = h;
          header.appendChild(th);
        }

        table.classList.add('table','table-bordered');
        data.forEach(function(item) {
          var row = table.insertRow();
          for(var v in item) {
            var cell = row.insertCell();
            if (Array.isArray(item[v])) {
              var subtable = createTable(item[v]);
              cell.appendChild(subtable);
            }
            else {
              cell.innerHTML = item[v];
            }
          }
        })

        return table;
      }

      // 

Open in new window

0
what is a best approach to this -

I am trying to open an existing aspx page , with few controls which  includes html controls line input, select ,  user controls ( ascx) and also custom third party controls like multi select dropdown.

thing  I have tried is to make an ajax call, shown below. I don't know if this is a good approach.

or is it better to, try to convert the aspx page to a ascx page and then load it to the Modal popup.


$.ajax({
       //make a get call to aspx page.
       //on success, append to the modal content div
});
0
I am trying to pass an actionlink parameter to the "Create" action in the controller. I am trying to create and insert a row into the database because I need the "RequestID" for later use.  What I have tried thus far is to create a prop in the my viewmodel named "NewRequestId".  I am calling an ajax "GET" json request to send the requestId to a hidden field on the "Index" view.  The main object here is to have the requestId at the time the "public ActionResult Create()", which is the HttpGet, gets called. The hidden textbox field is being populated but it does not seem to want to pass to the controller.

1. Index
2. GetRequest to
the 3. Create (But I need to have to the requestId from the database at this time)

//this is on the Index.chtml
@Html.ActionLink("Create New", "Create", "Request", null, new { id = NewRequestId, onclick = "GetRequestId();" })

Open in new window


public JsonResult GetRequestId()
{
            Request request = new Request();
            DateTime now = DateTime.Now;

            User userid = requestRepository.GetUserByUserName(Environment.UserName);            

            request.UserName = userid.UserName;
            request.RequestDate = now;
            request.TicketStatusId = 7; // 7 = Created, 1 = Submitted
            request.HasNotifications = false;
            request.AddToWatchList = false;

            db.Requests.Add(request);

            db.SaveChanges();
            
            return new JsonResult { Data = request, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }

Open in new window


//GET: Request/Create
public ActionResult Create(int requestId)
{
Request request = db.Requests.Find(requestId);

//Add the rest of the data to the request record and update that id

db.SaveChanges();

return View(request);
 }

Open in new window


//Javascript function
function GetRequestId(data) {
    var requestId = "";

    $.ajax(
        {
            url: '/Request/GetRequestId',
            //data: { requestId },
            type: "GET",
            dataType: "json",
            success: function (result) {
                $("#NewRequestId").val(result.RequestId);
                requestId = result.RequestId;
            }            
        });
   
    location.href = '/Request/Create/' + $("#NewRequestId").val();
    return false;
};

Open in new window

0
I have calendar control from  ASP.NET AJAX Control Toolkit .
I am trying to customize the background color , and other css properties of the calendar.

Is there any other library or widget , I can use instead of the one from AJAX control toolkit, which is easy to integrate with asp.net and also easy to customize.
1
Trying to send checkbox state to PHP page using Ajax. I am able to send he value of the element but I also need to send the state of the button that will determine if the data is added or deleted from the database. Here is what I have.
<script>

 $(document).on('click', '.favorite-resource-checkbox', function(){  
            var resourceValues = $( this ).val();
		    var user = "<?php echo $user_id; ?>";
	 		var id = $(this).attr('id');
           
           $.ajax({  
                url:"file.php",  
                method:"POST",  
                data:{value: resourceValues , user: user},  
                dataType:"text",  
                success:function(data)  
                {  
                     alert(data);  
                    
                }  
           })  
      });		
	
</script>	

Open in new window


Thanks
1
Ok my problem,

I used ajax with case statements on php end.

function saveAct(){
    
    
    
    
    var testAct = $('#act-data :input').serialize();
    
  
   
    $.ajax({
           type: "POST",
           url: 'controllers/contacts.ajax.php',
           data: { subaction : "saveActDetails" , actForm : testAct},
           dataType: "json" 
        }).success(function (response) {
             
                 console.log(response)
  
      
        }).error(function (response) {
               console.log(" save-act error");
        });
}

Open in new window


so i use the post type,  i use the subaction to trigger the correct case, then im using the actFrom to send form data, now i want to be able to use this data to insert into a table. but im first seeing what i am posting, the return looks a match to the form however i dont think i can use it and add this to a table.


case 'saveActDetails' :

		$response = array(
			'Result' => 'save-act success',
			'data' => $_POST['actForm']
		);


		break;

Open in new window


any solutions ?
1
Whi can iam confirm a java script in any other mobile device and any other emaaddress and run it confidentialy please suggest me that what is the process to run the files that can,t be support the device.thease are the files mean java files or non supported files system can,t be display like zip files,axp,jpg,txt,docx,xisx,pdf,or more forms files.or a video format files that can be have to downloaded queue but system does not support to play and run thank you again
0
Introduction to R
LVL 12
Introduction to R

R is considered the predominant language for data scientist and statisticians. Learn how to use R for your own data science projects.

Twp questions on this page: https://www.gopherstateevents.com/results/cc_rslts/cc_rslts.asp

1) Why is there so much space above and below the horizontal list beginning with "Awards" and how can I minimize that?
2) If I used a data table for the Individual Results, would that increase, decrease, or have no impact on load time?

Thank you!
0
I want to disable a form submit if a div has a message contained within it.

I have a form that checks an external source for some validation. If the validation checks are not met, then a warning message is displayed in a div (dispemail).

I'd like to disable my submit button if a message is displayed in this div.

My form is:
<form action='formprocessor.php' method='post' id='member-add'>
<table cellpadding='5px' cellspacing='5' >
<tr><td>Email</td></tr>
<tr><td><input type='text' name='email' id='email' value=''/><div id='dispemail'></div></td></tr>
<tr><td><input type='submit' value='Submit' style='margin-top:20px; margin-bottom:40px' id='submit'/></td></tr>
</table>
</form>

Open in new window


The Javsacript to call the ajax validation script:
<script type="text/javascript">
$(document).ready(function(){
$("#email").blur(function() {
var email = $('#email').val();
if(email==="")
{
$("#dispemail").html("");
}
else
{
$.ajax({
type: "POST",
url: "check-email.php",
data: "email="+ email,
success: function(html){
$("#dispemail").html(html);
}
});
return false;
}
});
});
</script>

Open in new window


The validation code:
<?php

if(isset($_POST['email'])){
$email=(($_POST['email']));

$curl = curl_init();

curl_setopt_array($curl, array(
    CURLOPT_URL => "https://api.xxxxx.com",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "GET",
    CURLOPT_POSTFIELDS => "{}",
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
    echo "cURL Error #:" . $err;
} else {
    echo $response;
}


$responsetext=json_decode($response, true);

if ($responsetext['result']=='undeliverable'){
$message = $responsetext['email']." is not a valid email - ".$responsetext['reason'];
echo "<p class='error'>$message</p>";

}
else {
$message = $responsetext['email']." is a valid email";
echo "<p>$message</p>";
}



}

?>

Open in new window

0
I'm trying to work with the Oxford Dictionary api to check whether words discovered in my app do actually feature in the dictionary.
Usually I make api calls using jquery and ajax, however this one doesn't receive client-side calls so I'm having to write it server-side in PHP and fire it using ajax from a javascript function.

I'm close, but I can't quite see how to include the authentication parameters in the url call, and my PHP is a bit sketchy at the best of times, so I'm hoping an expert here can help me to get the syntax right. At the moment, the response from the PHP file is simply: "Authentication parameters missing."  - So I'm sure its just my own ignorance about php and cURL holding it back. Can you help by showing me what changes to make in the PHP file below?

Any advice would be warmly received. Thanks...

This is how it looks so far:

For the JS:
function isDictionaryWord(pl){
    
    var isWord = false;
    
    pl = pl.toLowerCase();
    pl = pl.split(' ').join('_');
    
    $.ajax({
            url: "call_oxford_apia.php", 
            method: "post",
            data: { "word":pl},
                success: function(resp){
                    console.log("Oxford Check Shows: " + JSON.stringify(resp))
                    isWord = true;
                },
                 error: function() {
                     isWord = false;
                } 
    });
    
    return isWord;
}

Open in new window


And for the PHP: (filename: 'call_oxford_apia.php')


Open in new window

0
Hi Experts!

I have a question regarding to the file upload code. It is a simple html upload code:

<form class="smart-form" enctype="multiplart/form-data">
........
<fieldset>
        <section>
            <label class="label">File input</label>
            <div class="input input-file">
                  <span class="button"><input type="file" id="file" name="file" onchange="this.parentNode.nextSibling.value = this.value">Browse</span><input type="text" placeholder="Please upload the file in either .txt or .csv or .xls or .xlsx format" readonly="">
            </div>
      </section>
......
</form>

For my javasxript side I have this code: (I posted the information as $_FILES['Info'] to the PHP)

$('#file').change(function() {
      var file = this.files[0];
      var _formData = new FormData();
      _formData.append('Info', file);

      $.ajax({
            type: "POST",
            url: "App/uploader.php",
            dataType: "text",
            contentType: false,
            processData: false,
            data: file
      }).done(function(data){                   
            //console.log(data);
            var rData = JSON.parse(data);
            switch(rData)
            {
                  case 1:
                        $('#fileMsg ').text("SUCCESS!");
                        setTimeout(function(){location.reload(true);}, 1500);
                        break;
                  case 0:
                        $('#fileMsg ').text("FAILURE!");
                        setTimeout(function(){location.reload(true);}, 2500);
                        break;
            }
      });      
});

My issue is this:

When I use the ajax post and get a result as return I need to use setTimeout(function(){location.reload(true).... in order to upload another file. If I don't reload …
0
I have a ajax function which returns some json....

{
	"data": {
		"type": "slide",
		"id": "13",
		"attributes": {
			"slideID": 13,
			"slideGroupID": 1,
			"slideNumber": 2,
			"slideLocation": "Slide1.JPG",
			"slideLive": 1,
			"slideCurrent": 0,
			"slideHasVote": 0
		}
	}
}

Open in new window


How do I access the data using jquery. I need the slideLocation.
I thought this: console.log(data.attributes.slideLocation); but it doesn't work.
0
I have a job that I would like to get bids on...if that still happens on this site.  Here is what I need:

I need this page (https://www.gopherstateevents.com/results/fitness_events/results.asp?event_type=5&event_id=825&race_id=1427) to "scroll" vertically in marquee fashion for large screen display at races.  All I really need is the data table...or the data in the data table...to be visible.  Please let me know if you would be able to help me and what it would cost me.  I have tried to get this going in the "normal" process of doing it myself with EE help but, due to my weakness in JQuery, I just haven't gotten there.

Let me know if you have questions or if you can help me.
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.