I'm attempting to access a PHP file by clicking a button using AJAX and jQuery

I am just starting to learn the basics of jQuery and AJAX. I have already attempted to solve this problem by checking previous answers on Stackoverflow, but the code provided did not work for me. I have created two pages, index.php and testing.php, with a button on the index page. However, when I click on the button, nothing happens and it does not pass to testing.php. I am using jQuery and AJAX functions for this.

HTML file (index.php)

<input type='submit' name='Result' value='Show Graph' id='Result' onclick='return go_graph();'/>

I have also tried calling the function in JavaScript, but it is not working.

jQuery File

<script type="text/javascript">
    $(document).ready(function(){
        alert(projectID);

        $('#Result').click(function(){
            var clickBtnValue = $(this).val();
            $.ajax({
                url: "testing.php?projectID="+projectID+"&clickBtnValue="+clickBtnValue,
                success: function(results){
                    res=results;
                    alert('haii');
                },
            });
        });

        function go_graph(){
            alert(projectID);
            $.ajax({
                url: "testing.php?projectID="+projectID,
                success: function(results){
                    res=results;
                    alert(res);
                },
            });
        }
    });
</script>

Answer №1

You seem to have a syntax error in your $.ajax. Take a look at this:

$.ajax({
    url:"test3.php?projectID="+projectID+"&clickBtnValue="+clickBtnValue,
   success:function(results){
     res=results;
     //alert(res);
     alert ('haii');
    } //was missing
    });

  });
 });

Also, update this line:

<input type='submit' name='Result' value='Show Graph' id='Result' onclick='return go_graph();'/>
to
<input type='button' name='Result' value='Show Graph' id='Result' onclick='return go_graph();'/>

Complete code snippet below:

 <input type='submit' name='Result' value='Show Graph' id='Result' onclick='return go_graph();' />
<script src="http://code.jquery.com/jquery-latest.min.js"
        type="text/javascript"></script>

<script>
  $(document).ready(function(){
    var projectID = 1;
  alert(projectID);
  $('#Result').click(function(){
  var clickBtnValue = $(this).val();
  $.ajax({
    url:"testing.php?projectID="+projectID+"&clickBtnValue="+clickBtnValue,
   success:function(results){
     res=results;
     //alert(res);
     alert ('haii');
    }
    });

  });
 });
 function go_graph(){

    alert('go');
     $.ajax({url:"testing.php?projectID="+projectID,
    success:function(results){
     res=results;
     alert(res);
     }

  });

    }
</script>

Answer №2

To solve this issue, implement the return statement:

handleResponse:function(data){
     response=data;
    return response;

Answer №3

<script type="text/javascript">
function display_graph()
{
    alert(pID);
     $.ajax({
      url:"display.php",
      data:projectID="+pID,
    success:function(response){
     graphData=response;
     alert(graphData);
     }

  });

    }
</script>

Answer №4

Have you attempted to execute PHP files asynchronously using AJAX and retrieve the response? If this is the case, consider invoking the preventDefault() function within your jQuery click event listener.

$('#Results').click(function(event){
event.preventDefault();
//paste the remainder of your code here
});

By doing so, you can stop the form submission and allow the AJAX request to fetch the output created by the PHP scripts in an asynchronous manner.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to upload a file without finalizing the form submission?

I have been working on a task to upload a file using ajax and php without refreshing the page when submitting. My code seems to be functioning well and alerts a valid message when I use the preg_match function. However, when I include the rest of the valid ...

What is the reason behind AngularJS throwing an error related to bad augmentation?

Whenever I try to update the src link in my Angular code from version 1.2.2 to 1.5.0, I encounter an error. The code works perfectly fine with 1.2.2, but switching to 1.5.0 throws an error. I want to upgrade it to 1.5.0, so what changes do I need to make ...

Creating a fading effect on an image in relation to another dynamic image

I am currently facing an issue in my code where I am trying to make one image fade in next to another, regardless of the position of the movable image on the screen. The movable image can be controlled using arrow keys, and when I move it across the screen ...

Attempting to remove options in a Multiple Choice scenario by selecting the X icon beside each one

I'm working on a multiple choice quiz and I'd like to add a button or icon resembling X in front of each option (even in front of the radio button), so that when I click on it, only that specific option is deleted. How can I achieve this? For in ...

Find a specific value within a complex array of objects in Angular 2

Recently delving into Angular 2, I am seeking guidance on the best approach for a particular use-case. My array of Objects is structured as follows: users : Array<Object> = [{ id: 1, tags: [{ name: 'foo', age: 21 ...

How to dynamically change the color of a button in a list in Vue.js when it is clicked

I am working on a dynamic list of buttons that are populated using an array of objects: <div class="form-inline" v-for="(genre, index) in genreArray" :key="index" > ...

The authentication for npm failed with a 401 error code when attempting to log in

When attempting to sign in to npm using the command npm login and providing my username, password, and email, I am encountering the following error message: The Registry is returning a 401 status code for the PUT request. Even though I have used the sa ...

What causes req.body to display as an empty object in the console during a POST request?

Having some trouble with my code. The middleware is supposed to return parsed data in the console as an object accessed by req.body, but it keeps returning an empty object for some reason. Check out Code and Console Snapshot 1 View Code and Console Snapsh ...

What is the best way to effectively test jQuery's .ajax() promises using Jasmine and/or Sinon?

There is a simple function that returns a jQuery .ajax() promise: CLAW.controls.validateLocation = function(val, $inputEl) { return $.ajax({ url: locationServiceUrl + 'ValidateLocation/', data: { 'locationNam ...

Clicking the Less/More button using jQuery

In my current setup, I have a code snippet that loads and displays two comments initially. There is also a button labeled More comments which, when clicked, fetches and shows the remaining comments using AJAX. Upon clicking the More comments button, it tr ...

A step-by-step guide to implementing the PUT function in AngularJS using Mongoose

My attempt to send a GET request to the Mongo works fine, but I'm having trouble getting the PUT request to work. My suspicion is that there might be an issue with the path from the controller to the router. I've already tried using both update() ...

Using Javascript to validate passwords and Bootstrap for design enhancements

I've been working on learning Javascript and some basic HTML using bootstrap v5 recently. One of the tasks I'm currently tackling is creating a Sign-in form and implementing validation for the required fields. While following the Bootstrap docu ...

The passport JWT authorization failed, not a single message is being printed to the console

I am currently working on building a login and registration system. I have experience using passport before and had it functioning properly. However, it seems like the npm documentation has been updated since then. I am facing an issue where I cannot even ...

Using a variable as an argument for a DOM function in JavaScript

I found this code snippet on a website and made some changes to it. However, the modified code below is not functioning as expected. My goal was to hide the div with the id "demo1", but for some reason, it's not working. What could be causing this is ...

Execute iMacros Loop and terminate the process before proceeding to the next command

As a newcomer to the world of iMacro scripting, I am struggling with setting up a simple data scrape. I'm looking for guidance on how to create a loop for the following commands: URL GOTO=link1 URL GOTO=link2 URL GOTO=link3 WAIT SECONDS=7.5 Once th ...

Using JavaScript, conceal a specific Div by examining the content within another Div

I am attempting to implement some logic using JavaScript. The goal is to hide the "cart-button" div if the innerHTML value of a div with the class "b-format" is set to Audio, otherwise hide the "more-button" div. However, for some reason this functionality ...

Create a scrollable div within a template

After discovering a template that I want to use for my personal project, I noticed a missing element... There's a div where content can be added. That's fine, but what if I add more content than fits in the space provided? The whole website beco ...

Learn the process of integrating JSON data into a jQuery Datatable!

I am facing an issue while trying to load data into jQuery Data table using MVC. The data is only displaying in JSON format in the browser instead of populating the data table, as shown below: {"data":[{"ID":1,"FullName":"John Smith","Email":"[email prote ...

Prevent typing in text box when drawer is activated by pressing a button

update 1 : After removing unnecessary files, I need assistance with https://codesandbox.io/s/0pk0z5prqn I am attempting to disable a textbox. When clicking the advanced sports search button, a drawer opens where I want to display a textbox. The toggleDra ...

Struggling to make an AJAX form function properly

I'm running into an issue while setting up a basic AJAX form. My goal is to have a message display on the same page upon successful login using a PHP form through AJAX, but currently, I get redirected to the PHP file after form submission. Can anyone ...