How to pass variables back from php ajax

I have a script from the login page that sends data to php via ajax, and php returns if successful or not, I'm just wondering how I can change my scripts so that it also sends back 2 variables and gets them in my js login script, so can I create cookies? here are my js and php scripts:

Js

$(document).on('pageinit',function(){ $("#login").click(function(){ username=$("#usr").val(); password=$("#psw").val(); $.ajax({ type: "POST", url: "http://imes.***********.com/php/login_check.php", data: "name="+username+"&pwd="+password, success: function(html){ //in case of success if(html=='true') { $("#login_message").html("Logged in, congratulation."); $.mobile.changePage("http://imes.***********.com/userpanel.php"); } //in case of error else { $("#login_message").html("Wrong username or password"); } }, beforeSend: function() { $.mobile.showPageLoadingMsg(); }, //Show spinner complete: function() { $.mobile.hidePageLoadingMsg() } //Hide spinner }); return false; }); 

Php

 <?php session_start(); $username = $_POST['name']; $password = $_POST['pwd']; include('mysql_connection.php'); mysql_select_db("jzperson_imesUsers", $con); $res1 = mysql_query( "SELECT * FROM temp_login WHERE username='$username' AND password='$password'" ); $num_row = mysql_num_rows($res1); if ($num_row == 1) { echo 'true'; } else { echo 'false'; } ?> 
+6
source share
3 answers

Try using Json as an answer:

PHP side

 ... $json = new Services_JSON(); echo $json->encode("{a:1,b:2}"); 

Js

 ... success:function(data){ if(data) { console.log(data.a); console.log(data.b); } .... 

You can encode any array in PHP and pass it as an ajax callback.

Json class you can get there

+2
source

You can use JSON to return values ​​in a JS script. In your PHP code, return something like:

 { "result": true, "your_variable": "variable_value" } 

You can use json_encode . And then in JS, parse it with jQuery.parseJSON ()

+2
source

You can use a formatted JSON response to return values ​​from PHP to JS (look at the PHP json_encode () function: http://php.net/manual/en/function.json-encode.php ).

Or just set the value in the cookie from PHP ( http://php.net/manual/en/function.setcookie.php )

0
source

All Articles