0

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.

1

3 Answers 3

1

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;
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much this is super useful to me. I can definitely use this.
@AlecGamble Most Welcome.
0

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

1 Comment

Thank you very much, that's useful to know :)
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.