Created
April 13, 2016 20:55
-
-
Save igoralves1/a70e6f8c904f1e06020039f3fe0f3d29 to your computer and use it in GitHub Desktop.
AJAX - PHP - JS. Send data to PHP and back do JS - Method 1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Method 1 | |
//Js is not dynamic. I can not pass variables from PHP->to JS->to PHP, in the same page. | |
//Your php code | |
$arrToJSON = array( | |
"dataPHPtoJs"=>"yourData", | |
"asYouWant"=>"<div class=\".class1\">soemting</div>" | |
); | |
return json_encode(array($arrToJSON)); | |
//Your javaScript code | |
$(document).on("event", "#idElement", function(){ | |
//Data you want to send to php evaluate | |
var dt={ | |
ObjEvn:"btn_Login", | |
dataJsToPHP: $("#txt_EmailLogin").val() | |
}; | |
//Ajax | |
var request =$.ajax({//http://api.jquery.com/jQuery.ajax/ | |
url: "yourServer.php", | |
type: "POST", | |
data: dt, | |
dataType: "json" | |
}); | |
//Ajax Done catch JSON from PHP | |
request.done(function(dataset){ | |
for (var index in dataset){ | |
dataPHPtoJsJS=dataset[index].dataPHPtoJs; | |
asManyasYouWantJS=dataset[index].asYouWant; | |
} | |
//JavaScript conditions. Here you can control the behaivior of your html object, based on your PHP response | |
if(dataPHPtoJsJS){ | |
$( "#idYourHtmlElement" ).removeClass( "class1" ) | |
$( "#idYourHtmlElement" ).addClass( "class2" ) | |
} | |
}); | |
//Ajax Fail | |
request.fail(function(jqXHR, textStatus) { | |
alert("Request failed: " + textStatus); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment