Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery/JSON/PHP failing

Tags:

json

jquery

php

I am trying to call a php script that accepts JSON data, writes it into a file and returns simple text response using jQuery/AJAX call.

jQuery code :

   $("input.callphp").click(function() {
    var url_file = myurl;
    $.ajax({type : "POST",
            url : url_file,
            data : {puzzle: 'Reset!'},
            success : function(data){
                alert("Success");
                alert(data);
            }, 
            error : function (jqXHR, textStatus, errorThrown) {
                alert("Error: " + textStatus + "<" + errorThrown + ">");
            },
            dataType : 'text'
    });
});

PHP Code :

<?php
  $thefile = "new.json"; /* Our filename as defined earlier */
  $towrite = $_POST["puzzle"]; /* What we'll write to the file */
  $openedfile = fopen($thefile, "w");
  fwrite($openedfile, $towrite);
  fclose($openedfile);
  echo "<br> <br>".$towrite;
?>

However, the call is never a success and always gives an error with an alert "Error : [Object object]".

NOTE

This code works fine. I was trying to perform a cross domain query - I uploaded the files to the same server and it worked.

like image 564
user730936 Avatar asked Jan 23 '26 13:01

user730936


1 Answers

var url_file = myurl"; // remove `"` from end

Arguments of error function is:

.error( jqXHR, textStatus, errorThrown )

not data,

You can get data (ie. response data from server) as success() function argument.

Like:

success: function(data) {

}

For more info look .ajax()

NOTE

If you're trying to get data from cross-domain (i.e from different domain), then you need jsonp request.

like image 191
thecodeparadox Avatar answered Jan 25 '26 04:01

thecodeparadox