简体   繁体   中英

Ajax Get results from sql query

I'm fairly new to web development and php.

I have a js file with all my functions. In one of the functions I make an ajax call to create a new database record that person A is making a challenge to person B.

JS

var challengeeId = document.getElementById('Challengee').value;

$.ajax({
    type:"post",
    url: baseUrl+"/site/challenge",
    data:{"challengeeId":challengeeId},
    cache:false,
    success: function(html){
    }
});

PHP

$model = new Challenge();
$model->challenger_id = Yii::app()->user->id;
$model->challengee_id = $_POST['challengeeId'];
$model->date_created = date("Y-d-m H:i:s");
$model->status ="pending";
$model->save();

This is fine and saves in table correctly. The table also creates an id for every challenge. I want to know how to return that id so that I can store it as a variable in my JS file for later use. I have an SQL query which returns the ID for me, I just don't know how to return it from the PHP to JS.

Use this sure you get the last id

If using postgresql

$lastID = Yii::app()->db->getLastInsertID('table_sequence');
return $lastID;

If using mysql

$lastID = Yii::app()->db->getLastInsertID();
return $lastID;

since getLastInsertID is accessor method you also call like this too

$lastID = Yii::app()->db->lastInsertID;
return $lastID;

You'll need to return that value back either as a string or maybe a json return and then that becomes the "html" var in your "success" case of the ajax call. You then handle the rest in javascript

You could echo the id in php. the variabele html will then contain the id.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM