0

I already have everything pre-defined in the script. What I want to do is when I click on SUBMIT it will do the work without refreshing the page. Currently it refreshes the page and shows "Working". What I am trying to do is something like this:

Image link of how I want it to be

Here is my code:

    <?php
$url="http://google.com";

if(isset($_POST["submit"])){

    $ch = curl_init("$url");
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_exec($ch);
    $retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if (200==$retcode) {
        echo "working";
    } else {
       echo "failed";
    }
}
?>

<form action='ping.php'  method='post'><input type="submit"   name="submit"></form>



<script src="plugins/jQuery/jquery-2.2.3.min.js"></script>



       <script type="text/javascript">
            var $url =  '<?php echo $url ?>';
            $('#submit').click(function(e){

        e.preventDefault();

        var $this = $(this);
        $.get($url,function(data){
            $this.text('Success');
        });
    });
                </script>

EDIT:

The script in the above example shows an error:

[The request] has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

so I was going to do it with PHP cURL. If anyone knows any solution, please help.

Sᴀᴍ Onᴇᴌᴀ
  • 8,218
  • 8
  • 36
  • 58
john wacker
  • 17
  • 1
  • 6
  • [Have you watched the AJAX request / response in the browser's developer tools? Have you included the jQuery library in the project? Are there any errors reported? Are you running this on a web-server?](http://jayblanchard.net/basics_of_jquery_ajax.html) – Jay Blanchard Mar 13 '17 at 18:00
  • Why are you loading two versions of jQuery? – jessegavin Mar 13 '17 at 18:03
  • @jessegavin forgot to remove it.Removed. – john wacker Mar 13 '17 at 18:05
  • There is no element with id attribute 'submit' so the click handler (i.e. `$('#submit').click(function(e){...`) isn't getting called – Sᴀᴍ Onᴇᴌᴀ Mar 13 '17 at 19:01
  • CORS or Cross Origin Request Sharing (https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS), the browser makes a HTTP OPTIONS request before sending the actual form data. The data source / web app needs to respond with the Allow-Access-* set of headers to tell the browser it is OK to make a request with the wanted HTTP method to the desired resource. The easy work around: make the server respond with a 200 OK and the set of CORS headers to allow the form to submit to the server. PM if you need more info. – David J Eddy Mar 14 '17 at 04:54

3 Answers3

0

I am no PHP expert, but I think this line

var $url =  '<?php echo $url ?>';

will render to html as

var $url = 'http://google.com';

This means you're trying to do an XHR call to google's website from your own domain. This is why you're getting CORS errors.

I think you're actually trying to use PHP as a proxy to communicate with Google (which should work fine).

If the code you pasted above is named ping.php, then the action on the <form> looks like it's wired up to POST to itself.

The only change you should need to make then is the following...

<form action='ping.php' method='post'>
  <button>PING</button>
</form>


<script type="text/javascript">

  // Use the `submit` event on the form instead of the click event on the button. 
  // It's good practice for this sort of thing.

  $('form').on('submit', function(e){

    e.preventDefault();



    var form = $(this);
    var button = form.find('button');

    // Set the button text to 'working'
    button.text('Working...');

    var url = form.attr('action');
    $.get(url, function(data) {
      button.text('Success');
    });
  });
</script>
jessegavin
  • 74,067
  • 28
  • 136
  • 164
0

I'm no javascript expert but when you try to make cross-domain calls, you should set the dataType to jsonp and crossDomain to true. Like this:

$.ajax({
    url: 'HTTP://THE_URL',
    type: 'GET',
    crossDomain: true,
    dataType: 'jsonp',
    success: function() { alert("Success"); },
});

I could be wrong tough :)

maesbn
  • 207
  • 3
  • 6
  • The jsonp approach might be a good idea but the URL in the OPs code (i.e. `http://google.com`) returns HTML. "_NO, you can't use JSONP for fetching html data_" - from [this answer](http://stackoverflow.com/a/7532400/1575353) – Sᴀᴍ Onᴇᴌᴀ Mar 13 '17 at 19:00
0

As others have mentioned, the Access Control Allow Origin error is a CORS issue. That is happening because the AJAX request is pointed to the url in $url (i.e. http://google.com). Instead, use the curl request at the top of the code (i.e. if(isset($_POST["submit"])){...) by using $.post() instead of $.get(). The URL of the post should be the PHP page (i.e. pong.php?). In the code sample below and demo (see end of this answer) it uses PHP_SELF (i.e $_SERVER['PHP_SELF']) for the url to send the POST request to. And it passes $url in the POST data (second parameter of .post(). Plus we need to use .val() to update the text of the button (see notes below).

var $url =  '<?php echo $_SERVER['PHP_SELF']; ?>';
$('#submit').click(function(e){
    e.preventDefault();
    var $this = $(this);
    $.post($url,{url: "<?php echo $url;?>"}, function(data){
        //see note below about using .text()
        //$this.text('Success');
        $this.val('Success');
     });
});

Also, as I mentioned in a comment, there is no element with id attribute submit so the click handler is never getting executed. And in order to update the text on the submit button, give it a value and update the value using .val().

  • Add the id and value attributes:

    <input type="submit" id="submit"  name="submit" value="Submit"> 
    
  • Use .val() in the success callback:

     $this.val('Success');
    

See a demonstration in this PHPFiddle.

One other possible function that could be used is .load() - it would still be prone to the CORS issue but at least the callback function can be called.

Sᴀᴍ Onᴇᴌᴀ
  • 8,218
  • 8
  • 36
  • 58